File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.412: download - view: text, annotated - select for diffs
Wed Aug 24 20:58:50 2022 UTC (20 months, 4 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Dual SSO and non-SSO login from /adm/login
  - Display of domain configuration for each server split into two tables
    so input textboxes can be longer.
  - "Pop-up if iframe" (Y/N) item added.  If Y, when login page is in an
    iframe, SSO log-in dialog will be displayed in a new window, i.e.,
    not within the iframe, e.g., to satisfy sameorigin requirement in
    x-frame-options in header sent by SSO server.

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.412 2022/08/24 20:58:50 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 LONCAPA qw(:DEFAULT :match);
  171: use LONCAPA::Enrollment;
  172: use LONCAPA::lonauthcgi();
  173: use LONCAPA::SSL;
  174: use File::Copy;
  175: use Locale::Language;
  176: use DateTime::TimeZone;
  177: use DateTime::Locale;
  178: use Time::HiRes qw( sleep );
  179: use Net::CIDR;
  180: 
  181: my $registered_cleanup;
  182: my $modified_urls;
  183: 
  184: sub handler {
  185:     my $r=shift;
  186:     if ($r->header_only) {
  187:         &Apache::loncommon::content_type($r,'text/html');
  188:         $r->send_http_header;
  189:         return OK;
  190:     }
  191: 
  192:     my $context = 'domain';
  193:     my $dom = $env{'request.role.domain'};
  194:     my $domdesc = &Apache::lonnet::domain($dom,'description');
  195:     if (&Apache::lonnet::allowed('mau',$dom)) {
  196:         &Apache::loncommon::content_type($r,'text/html');
  197:         $r->send_http_header;
  198:     } else {
  199:         $env{'user.error.msg'}=
  200:         "/adm/domainprefs:mau:0:0:Cannot modify domain settings";
  201:         return HTTP_NOT_ACCEPTABLE;
  202:     }
  203: 
  204:     $registered_cleanup=0;
  205:     @{$modified_urls}=();
  206: 
  207:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  208:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  209:                                             ['phase','actions']);
  210:     my $phase = 'pickactions';
  211:     if ( exists($env{'form.phase'}) ) {
  212:         $phase = $env{'form.phase'};
  213:     }
  214:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
  215:     my %domconfig =
  216:       &Apache::lonnet::get_dom('configuration',['login','rolecolors',
  217:                 'quotas','autoenroll','autoupdate','autocreate',
  218:                 'directorysrch','usercreation','usermodification',
  219:                 'contacts','defaults','scantron','coursecategories',
  220:                 'serverstatuses','requestcourses','helpsettings',
  221:                 'coursedefaults','usersessions','loadbalancing',
  222:                 'requestauthor','selfenrollment','inststatus',
  223:                 'ltitools','ssl','trust','lti','ltisec','privacy','passwords',
  224:                 'proctoring','wafproxy','ipaccess'],$dom);
  225:     my %encconfig =
  226:         &Apache::lonnet::get_dom('encconfig',['ltitools','lti','proctoring','linkprot'],$dom,undef,1);
  227:     if (ref($domconfig{'ltitools'}) eq 'HASH') {
  228:         if (ref($encconfig{'ltitools'}) eq 'HASH') {
  229:             foreach my $id (keys(%{$domconfig{'ltitools'}})) {
  230:                 if ((ref($domconfig{'ltitools'}{$id}) eq 'HASH') &&
  231:                     (ref($encconfig{'ltitools'}{$id}) eq 'HASH')) {
  232:                     foreach my $item ('key','secret') {
  233:                         $domconfig{'ltitools'}{$id}{$item} = $encconfig{'ltitools'}{$id}{$item};
  234:                     }
  235:                 }
  236:             }
  237:         }
  238:     }
  239:     if (ref($domconfig{'lti'}) eq 'HASH') {
  240:         if (ref($encconfig{'lti'}) eq 'HASH') {
  241:             foreach my $id (keys(%{$domconfig{'lti'}})) {
  242:                 if ((ref($domconfig{'lti'}{$id}) eq 'HASH') &&
  243:                     (ref($encconfig{'lti'}{$id}) eq 'HASH')) {
  244:                     foreach my $item ('key','secret') {
  245:                         $domconfig{'lti'}{$id}{$item} = $encconfig{'lti'}{$id}{$item};
  246:                     }
  247:                 }
  248:             }
  249:         }
  250:     }
  251:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
  252:         if (ref($domconfig{'ltisec'}{'linkprot'}) eq 'HASH') {
  253:             if (ref($encconfig{'linkprot'}) eq 'HASH') {
  254:                 foreach my $id (keys(%{$domconfig{'ltisec'}{'linkprot'}})) {
  255:                     unless ($id =~ /^\d+$/) {
  256:                         delete($domconfig{'ltisec'}{'linkprot'}{$id});
  257:                     }
  258:                     if ((ref($domconfig{'ltisec'}{'linkprot'}{$id}) eq 'HASH') &&
  259:                         (ref($encconfig{'linkprot'}{$id}) eq 'HASH')) {
  260:                         foreach my $item ('key','secret') {
  261:                             $domconfig{'ltisec'}{'linkprot'}{$id}{$item} = $encconfig{'linkprot'}{$id}{$item};
  262:                         }
  263:                     }
  264:                 }
  265:             }
  266:         }
  267:     }
  268:     if (ref($domconfig{'proctoring'}) eq 'HASH') {
  269:         if (ref($encconfig{'proctoring'}) eq 'HASH') {
  270:             foreach my $provider (keys(%{$domconfig{'proctoring'}})) {
  271:                 if ((ref($domconfig{'proctoring'}{$provider}) eq 'HASH') &&
  272:                     (ref($encconfig{'proctoring'}{$provider}) eq 'HASH')) {
  273:                     foreach my $item ('key','secret') {
  274:                         $domconfig{'proctoring'}{$provider}{$item} = $encconfig{'proctoring'}{$provider}{$item};
  275:                     }
  276:                 }
  277:             }
  278:         }
  279:     }
  280:     my @prefs_order = ('rolecolors','login','ipaccess','defaults','wafproxy','passwords',
  281:                        'quotas','autoenroll','autoupdate','autocreate','directorysrch',
  282:                        'contacts','privacy','usercreation','selfcreation',
  283:                        'usermodification','scantron','requestcourses','requestauthor',
  284:                        'coursecategories','serverstatuses','helpsettings','coursedefaults',
  285:                        'ltitools','proctoring','selfenrollment','usersessions','ssl',
  286:                        'trust','lti');
  287:     my %existing;
  288:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  289:         %existing = %{$domconfig{'loadbalancing'}};
  290:     }
  291:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  292:         push(@prefs_order,'loadbalancing');
  293:     }
  294:     my %prefs = (
  295:         'rolecolors' =>
  296:                    { text => 'Default color schemes',
  297:                      help => 'Domain_Configuration_Color_Schemes',
  298:                      header => [{col1 => 'Student Settings',
  299:                                  col2 => '',},
  300:                                 {col1 => 'Coordinator Settings',
  301:                                  col2 => '',},
  302:                                 {col1 => 'Author Settings',
  303:                                  col2 => '',},
  304:                                 {col1 => 'Administrator Settings',
  305:                                  col2 => '',}],
  306:                       print => \&print_rolecolors,
  307:                       modify => \&modify_rolecolors,
  308:                     },
  309:         'login' =>
  310:                     { text => 'Log-in page options',
  311:                       help => 'Domain_Configuration_Login_Page',
  312:                       header => [{col1 => 'Log-in Page Items',
  313:                                   col2 => '',},
  314:                                  {col1 => 'Log-in Help',
  315:                                   col2 => 'Value'},
  316:                                  {col1 => 'Custom HTML in document head',
  317:                                   col2 => 'Value'},
  318:                                  {col1 => 'SSO',
  319:                                   col2 => 'Dual login: SSO and non-SSO options'},
  320:                                 ],
  321:                       print => \&print_login,
  322:                       modify => \&modify_login,
  323:                     },
  324:         'defaults' => 
  325:                     { text => 'Default authentication/language/timezone/portal/types',
  326:                       help => 'Domain_Configuration_LangTZAuth',
  327:                       header => [{col1 => 'Setting',
  328:                                   col2 => 'Value'},
  329:                                  {col1 => 'Institutional user types',
  330:                                   col2 => 'Name displayed'},
  331:                                  {col1 => 'Mapping for missing usernames via standard log-in',
  332:                                   col2 => 'Rules in use'}],
  333:                       print => \&print_defaults,
  334:                       modify => \&modify_defaults,
  335:                     },
  336:         'wafproxy' =>
  337:                     { text => 'Web Application Firewall/Reverse Proxy',
  338:                       help => 'Domain_Configuration_WAF_Proxy',
  339:                       header => [{col1 => 'Domain(s)',
  340:                                   col2 => 'Servers and WAF/Reverse Proxy alias(es)',
  341:                                  },
  342:                                  {col1 => 'Domain(s)',
  343:                                   col2 => 'WAF Configuration',}],
  344:                       print => \&print_wafproxy,
  345:                       modify => \&modify_wafproxy,
  346:                     },
  347:         'passwords' =>
  348:                     { text => 'Passwords (Internal authentication)',
  349:                       help => 'Domain_Configuration_Passwords',
  350:                       header => [{col1 => 'Resetting Forgotten Password',
  351:                                   col2 => 'Settings'},
  352:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  353:                                   col2 => 'Settings'},
  354:                                  {col1 => 'Rules for LON-CAPA Passwords',
  355:                                   col2 => 'Settings'},
  356:                                  {col1 => 'Course Owner Changing Student Passwords',
  357:                                   col2 => 'Settings'}],
  358:                       print => \&print_passwords,
  359:                       modify => \&modify_passwords,
  360:                     },
  361:         'quotas' => 
  362:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  363:                       help => 'Domain_Configuration_Quotas',
  364:                       header => [{col1 => 'User affiliation',
  365:                                   col2 => 'Available tools',
  366:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  367:                       print => \&print_quotas,
  368:                       modify => \&modify_quotas,
  369:                     },
  370:         'autoenroll' =>
  371:                    { text => 'Auto-enrollment settings',
  372:                      help => 'Domain_Configuration_Auto_Enrollment',
  373:                      header => [{col1 => 'Configuration setting',
  374:                                  col2 => 'Value(s)'}],
  375:                      print => \&print_autoenroll,
  376:                      modify => \&modify_autoenroll,
  377:                    },
  378:         'autoupdate' => 
  379:                    { text => 'Auto-update settings',
  380:                      help => 'Domain_Configuration_Auto_Updates',
  381:                      header => [{col1 => 'Setting',
  382:                                  col2 => 'Value',},
  383:                                 {col1 => 'Setting',
  384:                                  col2 => 'Affiliation'},
  385:                                 {col1 => 'User population',
  386:                                  col2 => 'Updatable user data'}],
  387:                      print => \&print_autoupdate,
  388:                      modify => \&modify_autoupdate,
  389:                   },
  390:         'autocreate' => 
  391:                   { text => 'Auto-course creation settings',
  392:                      help => 'Domain_Configuration_Auto_Creation',
  393:                      header => [{col1 => 'Configuration Setting',
  394:                                  col2 => 'Value',}],
  395:                      print => \&print_autocreate,
  396:                      modify => \&modify_autocreate,
  397:                   },
  398:         'directorysrch' => 
  399:                   { text => 'Directory searches',
  400:                     help => 'Domain_Configuration_InstDirectory_Search',
  401:                     header => [{col1 => 'Institutional Directory Setting',
  402:                                 col2 => 'Value',},
  403:                                {col1 => 'LON-CAPA Directory Setting',
  404:                                 col2 => 'Value',}],
  405:                     print => \&print_directorysrch,
  406:                     modify => \&modify_directorysrch,
  407:                   },
  408:         'contacts' =>
  409:                   { text => 'E-mail addresses and helpform',
  410:                     help => 'Domain_Configuration_Contact_Info',
  411:                     header => [{col1 => 'Default e-mail addresses',
  412:                                 col2 => 'Value',},
  413:                                {col1 => 'Recipient(s) for notifications',
  414:                                 col2 => 'Value',},
  415:                                {col1 => 'Nightly status check e-mail',
  416:                                 col2 => 'Settings',},
  417:                                {col1 => 'Ask helpdesk form settings',
  418:                                 col2 => 'Value',},],
  419:                     print => \&print_contacts,
  420:                     modify => \&modify_contacts,
  421:                   },
  422:         'usercreation' => 
  423:                   { text => 'User creation',
  424:                     help => 'Domain_Configuration_User_Creation',
  425:                     header => [{col1 => 'Format rule type',
  426:                                 col2 => 'Format rules in force'},
  427:                                {col1 => 'User account creation',
  428:                                 col2 => 'Usernames which may be created',},
  429:                                {col1 => 'Context',
  430:                                 col2 => 'Assignable authentication types'}],
  431:                     print => \&print_usercreation,
  432:                     modify => \&modify_usercreation,
  433:                   },
  434:         'selfcreation' => 
  435:                   { text => 'Users self-creating accounts',
  436:                     help => 'Domain_Configuration_Self_Creation', 
  437:                     header => [{col1 => 'Self-creation with institutional username',
  438:                                 col2 => 'Enabled?'},
  439:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  440:                                 col2 => 'Information user can enter'},
  441:                                {col1 => 'Self-creation with e-mail verification',
  442:                                 col2 => 'Settings'}],
  443:                     print => \&print_selfcreation,
  444:                     modify => \&modify_selfcreation,
  445:                   },
  446:         'usermodification' =>
  447:                   { text => 'User modification',
  448:                     help => 'Domain_Configuration_User_Modification',
  449:                     header => [{col1 => 'Target user has role',
  450:                                 col2 => 'User information updatable in author context'},
  451:                                {col1 => 'Target user has role',
  452:                                 col2 => 'User information updatable in course context'}],
  453:                     print => \&print_usermodification,
  454:                     modify => \&modify_usermodification,
  455:                   },
  456:         'scantron' =>
  457:                   { text => 'Bubblesheet format',
  458:                     help => 'Domain_Configuration_Scantron_Format',
  459:                     header => [ {col1 => 'Bubblesheet format file',
  460:                                  col2 => ''},
  461:                                 {col1 => 'Bubblesheet data upload formats',
  462:                                  col2 => 'Settings'}],
  463:                     print => \&print_scantron,
  464:                     modify => \&modify_scantron,
  465:                   },
  466:         'requestcourses' => 
  467:                  {text => 'Request creation of courses',
  468:                   help => 'Domain_Configuration_Request_Courses',
  469:                   header => [{col1 => 'User affiliation',
  470:                               col2 => 'Availability/Processing of requests',},
  471:                              {col1 => 'Setting',
  472:                               col2 => 'Value'},
  473:                              {col1 => 'Available textbooks',
  474:                               col2 => ''},
  475:                              {col1 => 'Available templates',
  476:                               col2 => ''},
  477:                              {col1 => 'Validation (not official courses)',
  478:                               col2 => 'Value'},],
  479:                   print => \&print_quotas,
  480:                   modify => \&modify_quotas,
  481:                  },
  482:         'requestauthor' =>
  483:                  {text => 'Request Authoring Space',
  484:                   help => 'Domain_Configuration_Request_Author',
  485:                   header => [{col1 => 'User affiliation',
  486:                               col2 => 'Availability/Processing of requests',},
  487:                              {col1 => 'Setting',
  488:                               col2 => 'Value'}],
  489:                   print => \&print_quotas,
  490:                   modify => \&modify_quotas,
  491:                  },
  492:         'coursecategories' =>
  493:                   { text => 'Cataloging of courses/communities',
  494:                     help => 'Domain_Configuration_Cataloging_Courses',
  495:                     header => [{col1 => 'Catalog type/availability',
  496:                                 col2 => '',},
  497:                                {col1 => 'Category settings for standard catalog',
  498:                                 col2 => '',},
  499:                                {col1 => 'Categories',
  500:                                 col2 => '',
  501:                                }],
  502:                     print => \&print_coursecategories,
  503:                     modify => \&modify_coursecategories,
  504:                   },
  505:         'serverstatuses' =>
  506:                  {text   => 'Access to server status pages',
  507:                   help   => 'Domain_Configuration_Server_Status',
  508:                   header => [{col1 => 'Status Page',
  509:                               col2 => 'Other named users',
  510:                               col3 => 'Specific IPs',
  511:                             }],
  512:                   print => \&print_serverstatuses,
  513:                   modify => \&modify_serverstatuses,
  514:                  },
  515:         'helpsettings' =>
  516:                  {text   => 'Support settings',
  517:                   help   => 'Domain_Configuration_Help_Settings',
  518:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  519:                               col2 => 'Value'},
  520:                              {col1 => 'Helpdesk Roles',
  521:                               col2 => 'Settings'},],
  522:                   print  => \&print_helpsettings,
  523:                   modify => \&modify_helpsettings,
  524:                  },
  525:         'coursedefaults' => 
  526:                  {text => 'Course/Community defaults',
  527:                   help => 'Domain_Configuration_Course_Defaults',
  528:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  529:                               col2 => 'Value',},
  530:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  531:                               col2 => 'Value',},],
  532:                   print => \&print_coursedefaults,
  533:                   modify => \&modify_coursedefaults,
  534:                  },
  535:         'selfenrollment' => 
  536:                  {text   => 'Self-enrollment in Course/Community',
  537:                   help   => 'Domain_Configuration_Selfenrollment',
  538:                   header => [{col1 => 'Configuration Rights',
  539:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  540:                              {col1 => 'Defaults',
  541:                               col2 => 'Value'},
  542:                              {col1 => 'Self-enrollment validation (optional)',
  543:                               col2 => 'Value'},],
  544:                   print => \&print_selfenrollment,
  545:                   modify => \&modify_selfenrollment,
  546:                  },
  547:         'privacy' => 
  548:                  {text   => 'Availability of User Information',
  549:                   help   => 'Domain_Configuration_User_Privacy',
  550:                   header => [{col1 => 'Role assigned in different domain',
  551:                               col2 => 'Approval options'},
  552:                              {col1 => 'Role assigned in different domain to user of type',
  553:                               col2 => 'User information available in that domain'},
  554:                              {col1 => "Role assigned in user's domain",
  555:                               col2 => 'Information viewable by privileged user'},
  556:                              {col1 => "Role assigned in user's domain",
  557:                               col2 => 'Information viewable by unprivileged user'}],
  558:                   print => \&print_privacy,
  559:                   modify => \&modify_privacy,
  560:                  },
  561:         'usersessions' =>
  562:                  {text  => 'User session hosting/offloading',
  563:                   help  => 'Domain_Configuration_User_Sessions',
  564:                   header => [{col1 => 'Domain server',
  565:                               col2 => 'Servers to offload sessions to when busy'},
  566:                              {col1 => 'Hosting of users from other domains',
  567:                               col2 => 'Rules'},
  568:                              {col1 => "Hosting domain's own users elsewhere",
  569:                               col2 => 'Rules'}],
  570:                   print => \&print_usersessions,
  571:                   modify => \&modify_usersessions,
  572:                  },
  573:         'loadbalancing' =>
  574:                  {text  => 'Dedicated Load Balancer(s)',
  575:                   help  => 'Domain_Configuration_Load_Balancing',
  576:                   header => [{col1 => 'Balancers',
  577:                               col2 => 'Default destinations',
  578:                               col3 => 'User affiliation',
  579:                               col4 => 'Overrides'},
  580:                             ],
  581:                   print => \&print_loadbalancing,
  582:                   modify => \&modify_loadbalancing,
  583:                  },
  584:         'ltitools' => 
  585:                  {text => 'External Tools (LTI)',
  586:                   help => 'Domain_Configuration_LTI_Tools',
  587:                   header => [{col1 => 'Setting',
  588:                               col2 => 'Value',}],
  589:                   print => \&print_ltitools,
  590:                   modify => \&modify_ltitools,
  591:                  },
  592:         'proctoring' =>
  593:                  {text => 'Remote Proctoring Integration',
  594:                   help => 'Domain_Configuration_Proctoring',
  595:                   header => [{col1 => 'Name',
  596:                               col2 => 'Configuration'}],
  597:                   print => \&print_proctoring,
  598:                   modify => \&modify_proctoring,
  599:                  },
  600:         'ssl' =>
  601:                  {text  => 'LON-CAPA Network (SSL)',
  602:                   help  => 'Domain_Configuration_Network_SSL',
  603:                   header => [{col1 => 'Server',
  604:                               col2 => 'Certificate Status'},
  605:                              {col1 => 'Connections to other servers',
  606:                               col2 => 'Rules'},
  607:                              {col1 => 'Connections from other servers',
  608:                               col2 => 'Rules'},
  609:                              {col1 => "Replicating domain's published content",
  610:                               col2 => 'Rules'}],
  611:                   print => \&print_ssl,
  612:                   modify => \&modify_ssl,
  613:                  },
  614:         'trust' =>
  615:                  {text   => 'Trust Settings',
  616:                   help   => 'Domain_Configuration_Trust',
  617:                   header => [{col1 => "Access to this domain's content by others",
  618:                               col2 => 'Rules'},
  619:                              {col1 => "Access to other domain's content by this domain",
  620:                               col2 => 'Rules'},
  621:                              {col1 => "Enrollment in this domain's courses by others",
  622:                               col2 => 'Rules',},
  623:                              {col1 => "Co-author roles in this domain for others",
  624:                               col2 => 'Rules',},
  625:                              {col1 => "Co-author roles for this domain's users elsewhere",
  626:                               col2 => 'Rules',},
  627:                              {col1 => "Domain roles in this domain assignable to others",
  628:                               col2 => 'Rules'},
  629:                              {col1 => "Course catalog for this domain displayed elsewhere",
  630:                               col2 => 'Rules'},
  631:                              {col1 => "Requests for creation of courses in this domain by others",
  632:                               col2 => 'Rules'},
  633:                              {col1 => "Users in other domains can send messages to this domain",
  634:                               col2 => 'Rules'},],
  635:                   print => \&print_trust,
  636:                   modify => \&modify_trust,
  637:                  },
  638:           'lti' =>
  639:                  {text => 'LTI Link Protection and LTI Consumers',
  640:                   help => 'Domain_Configuration_LTI_Provider',
  641:                   header => [{col1 => 'Encryption of shared secrets',
  642:                               col2 => 'Settings'},
  643:                              {col1 => 'Rules for shared secrets', 
  644:                               col2 => 'Settings'},
  645:                              {col1 => 'Link Protectors',
  646:                               col2 => 'Settings'},
  647:                              {col1 => 'Consumers',
  648:                               col2 => 'Settings'},],
  649:                   print => \&print_lti,
  650:                   modify => \&modify_lti,
  651:                  },
  652:            'ipaccess' =>
  653:                        {text => 'IP-based access control',
  654:                         help => 'Domain_Configuration_IP_Access',
  655:                         header => [{col1 => 'Setting',
  656:                                     col2 => 'Value'},],
  657:                         print  => \&print_ipaccess,
  658:                         modify => \&modify_ipaccess,
  659:                        },
  660:     );
  661:     if (keys(%servers) > 1) {
  662:         $prefs{'login'}  = { text   => 'Log-in page options',
  663:                              help   => 'Domain_Configuration_Login_Page',
  664:                             header => [{col1 => 'Log-in Service',
  665:                                         col2 => 'Server Setting',},
  666:                                        {col1 => 'Log-in Page Items',
  667:                                         col2 => 'Settings'},
  668:                                        {col1 => 'Log-in Help',
  669:                                         col2 => 'Value'},
  670:                                        {col1 => 'Custom HTML in document head',
  671:                                         col2 => 'Value'},
  672:                                        {col1 => 'SSO',
  673:                                         col2 => 'Dual login: SSO and non-SSO options'},
  674:                                       ],
  675:                             print => \&print_login,
  676:                             modify => \&modify_login,
  677:                            };
  678:     }
  679: 
  680:     my @roles = ('student','coordinator','author','admin');
  681:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  682:     &Apache::lonhtmlcommon::add_breadcrumb
  683:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  684:       text=>"Settings to display/modify"});
  685:     my $confname = $dom.'-domainconfig';
  686: 
  687:     if ($phase eq 'process') {
  688:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  689:                                                               \%prefs,\%domconfig,$confname,\@roles);
  690:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  691:             $r->rflush();
  692:             &devalidate_remote_domconfs($dom,$result);
  693:         }
  694:     } elsif ($phase eq 'display') {
  695:         my $js = &recaptcha_js().
  696:                  &toggle_display_js();
  697:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  698:             my ($othertitle,$usertypes,$types) =
  699:                 &Apache::loncommon::sorted_inst_types($dom);
  700:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  701:                                           $domconfig{'loadbalancing'}).
  702:                    &new_spares_js().
  703:                    &common_domprefs_js().
  704:                    &Apache::loncommon::javascript_array_indexof();
  705:         }
  706:         if (grep(/^requestcourses$/,@actions)) {
  707:             my $javascript_validations;
  708:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  709:             $js .= <<END;
  710: <script type="text/javascript">
  711: $javascript_validations
  712: </script>
  713: $coursebrowserjs
  714: END
  715:         } elsif (grep(/^ipaccess$/,@actions)) {
  716:             $js .= &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
  717:         }
  718:         if (grep(/^selfcreation$/,@actions)) {
  719:             $js .= &selfcreate_javascript();
  720:         }
  721:         if (grep(/^contacts$/,@actions)) {
  722:             $js .= &contacts_javascript();
  723:         }
  724:         if (grep(/^scantron$/,@actions)) {
  725:             $js .= &scantron_javascript();
  726:         }
  727:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  728:     } else {
  729: # check if domconfig user exists for the domain.
  730:         my $servadm = $r->dir_config('lonAdmEMail');
  731:         my ($configuserok,$author_ok,$switchserver) =
  732:             &config_check($dom,$confname,$servadm);
  733:         unless ($configuserok eq 'ok') {
  734:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  735:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  736:                           $confname).
  737:                       '<br />'
  738:             );
  739:             if ($switchserver) {
  740:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  741:                           '<br />'.
  742:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  743:                           '<br />'.
  744:                           &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).
  745:                           '<br />'.
  746:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  747:                 );
  748:             } else {
  749:                 $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.').
  750:                           '<br />'.
  751:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  752:                 );
  753:             }
  754:             $r->print(&Apache::loncommon::end_page());
  755:             return OK;
  756:         }
  757:         if (keys(%domconfig) == 0) {
  758:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  759:             my @ids=&Apache::lonnet::current_machine_ids();
  760:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  761:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  762:                 my @loginimages = ('img','logo','domlogo','login');
  763:                 my $custom_img_count = 0;
  764:                 foreach my $img (@loginimages) {
  765:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  766:                         $custom_img_count ++;
  767:                     }
  768:                 }
  769:                 foreach my $role (@roles) {
  770:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  771:                         $custom_img_count ++;
  772:                     }
  773:                 }
  774:                 if ($custom_img_count > 0) {
  775:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  776:                     my $switch_server = &check_switchserver($dom,$confname);
  777:                     $r->print(
  778:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  779:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  780:     &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 />'.
  781:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  782:                     if ($switch_server) {
  783:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  784:                     }
  785:                     $r->print(&Apache::loncommon::end_page());
  786:                     return OK;
  787:                 }
  788:             }
  789:         }
  790:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  791:     }
  792:     return OK;
  793: }
  794: 
  795: sub process_changes {
  796:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  797:     my %domconfig;
  798:     if (ref($values) eq 'HASH') {
  799:         %domconfig = %{$values};
  800:     }
  801:     my $output;
  802:     if ($action eq 'login') {
  803:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  804:     } elsif ($action eq 'rolecolors') {
  805:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  806:                                      $lastactref,%domconfig);
  807:     } elsif ($action eq 'quotas') {
  808:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  809:     } elsif ($action eq 'autoenroll') {
  810:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  811:     } elsif ($action eq 'autoupdate') {
  812:         $output = &modify_autoupdate($dom,%domconfig);
  813:     } elsif ($action eq 'autocreate') {
  814:         $output = &modify_autocreate($dom,%domconfig);
  815:     } elsif ($action eq 'directorysrch') {
  816:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  817:     } elsif ($action eq 'usercreation') {
  818:         $output = &modify_usercreation($dom,%domconfig);
  819:     } elsif ($action eq 'selfcreation') {
  820:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  821:     } elsif ($action eq 'usermodification') {
  822:         $output = &modify_usermodification($dom,%domconfig);
  823:     } elsif ($action eq 'contacts') {
  824:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  825:     } elsif ($action eq 'defaults') {
  826:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  827:     } elsif ($action eq 'scantron') {
  828:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  829:     } elsif ($action eq 'coursecategories') {
  830:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  831:     } elsif ($action eq 'serverstatuses') {
  832:         $output = &modify_serverstatuses($dom,%domconfig);
  833:     } elsif ($action eq 'requestcourses') {
  834:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  835:     } elsif ($action eq 'requestauthor') {
  836:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  837:     } elsif ($action eq 'helpsettings') {
  838:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  839:     } elsif ($action eq 'coursedefaults') {
  840:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  841:     } elsif ($action eq 'selfenrollment') {
  842:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  843:     } elsif ($action eq 'usersessions') {
  844:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  845:     } elsif ($action eq 'loadbalancing') {
  846:         $output = &modify_loadbalancing($dom,%domconfig);
  847:     } elsif ($action eq 'ltitools') {
  848:         $output = &modify_ltitools($r,$dom,$action,$lastactref,%domconfig);
  849:     } elsif ($action eq 'proctoring') {
  850:         $output = &modify_proctoring($r,$dom,$action,$lastactref,%domconfig);
  851:     } elsif ($action eq 'ssl') {
  852:         $output = &modify_ssl($dom,$lastactref,%domconfig);
  853:     } elsif ($action eq 'trust') {
  854:         $output = &modify_trust($dom,$lastactref,%domconfig);
  855:     } elsif ($action eq 'lti') {
  856:         $output = &modify_lti($r,$dom,$action,$lastactref,%domconfig);
  857:     } elsif ($action eq 'privacy') {
  858:         $output = &modify_privacy($dom,%domconfig);
  859:     } elsif ($action eq 'passwords') {
  860:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  861:     } elsif ($action eq 'wafproxy') {
  862:         $output = &modify_wafproxy($dom,$action,$lastactref,%domconfig);
  863:     } elsif ($action eq 'ipaccess') {
  864:         $output = &modify_ipaccess($dom,$lastactref,%domconfig);
  865:     }
  866:     return $output;
  867: }
  868: 
  869: sub print_config_box {
  870:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  871:     my $rowtotal = 0;
  872:     my $output;
  873:     if ($action eq 'coursecategories') {
  874:         $output = &coursecategories_javascript($settings);
  875:     } elsif ($action eq 'defaults') {
  876:         $output = &defaults_javascript($settings); 
  877:     } elsif ($action eq 'passwords') {
  878:         $output = &passwords_javascript($action);
  879:     } elsif ($action eq 'helpsettings') {
  880:         my (%privs,%levelscurrent);
  881:         my %full=();
  882:         my %levels=(
  883:                      course => {},
  884:                      domain => {},
  885:                      system => {},
  886:                    );
  887:         my $context = 'domain';
  888:         my $crstype = 'Course';
  889:         my $formname = 'display';
  890:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  891:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  892:         $output =
  893:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full, 
  894:                                                       \@templateroles);
  895:     } elsif ($action eq 'ltitools') {
  896:         $output .= &ltitools_javascript($settings);
  897:     } elsif ($action eq 'lti') {
  898:         $output .= &passwords_javascript('secrets')."\n".
  899:                    &lti_javascript($dom,$settings);
  900:     } elsif ($action eq 'proctoring') {
  901:         $output .= &proctoring_javascript($settings);
  902:     } elsif ($action eq 'wafproxy') {
  903:         $output .= &wafproxy_javascript($dom);
  904:     } elsif ($action eq 'autoupdate') {
  905:         $output .= &autoupdate_javascript();
  906:     } elsif ($action eq 'autoenroll') {
  907:         $output .= &autoenroll_javascript();
  908:     } elsif ($action eq 'login') {
  909:         $output .= &saml_javascript();
  910:     } elsif ($action eq 'ipaccess') {
  911:         $output .= &ipaccess_javascript($settings);
  912:     }
  913:     $output .=
  914:          '<table class="LC_nested_outer">
  915:           <tr>
  916:            <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
  917:            &mt($item->{text}).'&nbsp;'.
  918:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  919:           '</tr>';
  920:     $rowtotal ++;
  921:     my $numheaders = 1;
  922:     if (ref($item->{'header'}) eq 'ARRAY') {
  923:         $numheaders = scalar(@{$item->{'header'}});
  924:     }
  925:     if ($numheaders > 1) {
  926:         my $colspan = '';
  927:         my $rightcolspan = '';
  928:         my $leftnobr = '';
  929:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  930:             ($action eq 'directorysrch') ||
  931:             (($action eq 'login') && ($numheaders < 5))) {
  932:             $colspan = ' colspan="2"';
  933:         }
  934:         if ($action eq 'usersessions') {
  935:             $rightcolspan = ' colspan="3"'; 
  936:         }
  937:         if ($action eq 'passwords') {
  938:             $leftnobr = ' LC_nobreak';
  939:         }
  940:         $output .= '
  941:           <tr>
  942:            <td>
  943:             <table class="LC_nested">
  944:              <tr class="LC_info_row">
  945:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  946:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  947:              </tr>';
  948:         $rowtotal ++;
  949:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  950:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  951:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'ssl') ||
  952:             ($action eq 'directorysrch') || ($action eq 'trust') || ($action eq 'helpsettings') ||
  953:             ($action eq 'contacts') || ($action eq 'privacy') || ($action eq 'wafproxy') || ($action eq 'lti')) {
  954:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  955:         } elsif ($action eq 'passwords') {
  956:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  957:         } elsif ($action eq 'coursecategories') {
  958:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  959:         } elsif ($action eq 'scantron') {
  960:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  961:         } elsif ($action eq 'login') {
  962:             if ($numheaders == 5) {
  963:                 $colspan = ' colspan="2"';
  964:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  965:             } else {
  966:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  967:             }
  968:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  969:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  970:         } elsif ($action eq 'rolecolors') {
  971:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  972:         }
  973:         $output .= '
  974:            </table>
  975:           </td>
  976:          </tr>
  977:          <tr>
  978:            <td>
  979:             <table class="LC_nested">
  980:              <tr class="LC_info_row">
  981:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  982:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  983:              </tr>';
  984:             $rowtotal ++;
  985:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  986:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  987:             ($action eq 'usersessions') || ($action eq 'coursecategories') || 
  988:             ($action eq 'trust') || ($action eq 'contacts') || ($action eq 'defaults') ||
  989:             ($action eq 'privacy') || ($action eq 'passwords') || ($action eq 'lti')) {
  990:             if ($action eq 'coursecategories') {
  991:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  992:                 $colspan = ' colspan="2"';
  993:             } elsif ($action eq 'trust') {
  994:                 $output .= $item->{'print'}->('shared',$dom,$settings,\$rowtotal);
  995:             } elsif ($action eq 'passwords') {
  996:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
  997:             } else {
  998:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  999:             }
 1000:             if ($action eq 'trust') {
 1001:                 $output .= '
 1002:             </table>
 1003:           </td>
 1004:          </tr>';
 1005:                 my @trusthdrs = qw(2 3 4 5 6 7);
 1006:                 my @prefixes = qw(enroll othcoau coaurem domroles catalog reqcrs);
 1007:                 for (my $i=0; $i<@trusthdrs; $i++) {
 1008:                     $output .= '
 1009:          <tr>
 1010:            <td>
 1011:             <table class="LC_nested">
 1012:              <tr class="LC_info_row">
 1013:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col1'}).'</td>
 1014:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col2'}).'</td></tr>'.
 1015:                            $item->{'print'}->($prefixes[$i],$dom,$settings,\$rowtotal).'
 1016:             </table>
 1017:           </td>
 1018:          </tr>';
 1019:                 }
 1020:                 $output .= '
 1021:          <tr>
 1022:            <td>
 1023:             <table class="LC_nested">
 1024:              <tr class="LC_info_row">
 1025:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col1'}).'</td>
 1026:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col2'}).'</td></tr>'.
 1027:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1028:             } else {
 1029:                 $output .= '
 1030:            </table>
 1031:           </td>
 1032:          </tr>
 1033:          <tr>
 1034:            <td>
 1035:             <table class="LC_nested">
 1036:              <tr class="LC_info_row">
 1037:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1038:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1039:              </tr>'."\n";
 1040:                 if ($action eq 'coursecategories') {
 1041:                     $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
 1042:                 } elsif (($action eq 'contacts') || ($action eq 'privacy') || 
 1043:                          ($action eq 'passwords') || ($action eq 'lti')) {
 1044:                     if ($action eq 'passwords') {
 1045:                         $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal);
 1046:                     } else {
 1047:                         $output .= $item->{'print'}->('lower',$dom,$settings,\$rowtotal);
 1048:                     }
 1049:                     $output .= '
 1050:              </tr>
 1051:             </table>
 1052:            </td>
 1053:           </tr>
 1054:           <tr>
 1055:            <td>
 1056:             <table class="LC_nested">
 1057:              <tr class="LC_info_row">
 1058:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1059:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
 1060:                     if ($action eq 'passwords') {
 1061:                         $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
 1062:                     } else {
 1063:                         $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1064:                     }
 1065:                     $output .= '
 1066:             </table>
 1067:           </td>
 1068:          </tr>
 1069:          <tr>';
 1070:                 } else {
 1071:                     $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1072:                 }
 1073:             }
 1074:             $rowtotal ++;
 1075:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
 1076:                  ($action eq 'directorysrch') || ($action eq 'helpsettings') ||
 1077:                  ($action eq 'wafproxy')) {
 1078:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1079:         } elsif ($action eq 'scantron') {
 1080:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
 1081:         } elsif ($action eq 'ssl') {
 1082:             $output .= $item->{'print'}->('connto',$dom,$settings,\$rowtotal).'
 1083:             </table>
 1084:           </td>
 1085:          </tr>
 1086:          <tr>
 1087:            <td>
 1088:             <table class="LC_nested">
 1089:              <tr class="LC_info_row">
 1090:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1091:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1092:                            $item->{'print'}->('connfrom',$dom,$settings,\$rowtotal).'
 1093:             </table>
 1094:           </td>
 1095:          </tr>
 1096:          <tr>
 1097:            <td>
 1098:             <table class="LC_nested">
 1099:              <tr class="LC_info_row">
 1100:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1101:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'.
 1102:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1103:         } elsif ($action eq 'login') {
 1104:             if ($numheaders == 5) {
 1105:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
 1106:            </table>
 1107:           </td>
 1108:          </tr>
 1109:          <tr>
 1110:            <td>
 1111:             <table class="LC_nested">
 1112:              <tr class="LC_info_row">
 1113:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1114:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1115:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1116:                 $rowtotal ++;
 1117:             } else {
 1118:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1119:             }
 1120:             $output .= '
 1121:            </table>
 1122:           </td>
 1123:          </tr>
 1124:          <tr>
 1125:            <td>
 1126:             <table class="LC_nested">
 1127:              <tr class="LC_info_row">';
 1128:             if ($numheaders == 5) {
 1129:                 $output .= '
 1130:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1131:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1132:              </tr>';
 1133:             } else {
 1134:                 $output .= '
 1135:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1136:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1137:              </tr>';
 1138:             }
 1139:             $rowtotal ++;
 1140:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal).'
 1141:            </table>
 1142:           </td>
 1143:          </tr>
 1144:          <tr>
 1145:            <td>
 1146:             <table class="LC_nested">
 1147:              <tr class="LC_info_row">';
 1148:             if ($numheaders == 5) {
 1149:                 $output .= '
 1150:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1151:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1152:              </tr>';
 1153:             } else {
 1154:                 $output .= '
 1155:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1156:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1157:              </tr>';
 1158:             }
 1159:             $rowtotal ++;
 1160:             $output .= &print_login('saml',$dom,$confname,$phase,$settings,\$rowtotal);
 1161:         } elsif ($action eq 'requestcourses') {
 1162:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1163:             $rowtotal ++;
 1164:             $output .= &print_studentcode($settings,\$rowtotal).'
 1165:            </table>
 1166:           </td>
 1167:          </tr>
 1168:          <tr>
 1169:            <td>
 1170:             <table class="LC_nested">
 1171:              <tr class="LC_info_row">
 1172:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1173:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
 1174:                        &textbookcourses_javascript($settings).
 1175:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
 1176:             </table>
 1177:            </td>
 1178:           </tr>
 1179:          <tr>
 1180:            <td>
 1181:             <table class="LC_nested">
 1182:              <tr class="LC_info_row">
 1183:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1184:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
 1185:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
 1186:             </table>
 1187:            </td>
 1188:           </tr>
 1189:           <tr>
 1190:            <td>
 1191:             <table class="LC_nested">
 1192:              <tr class="LC_info_row">
 1193:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1194:               <td class="LC_right_item" style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1195:              </tr>'.
 1196:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
 1197:         } elsif ($action eq 'requestauthor') {
 1198:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1199:             $rowtotal ++;
 1200:         } elsif ($action eq 'rolecolors') {
 1201:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
 1202:            </table>
 1203:           </td>
 1204:          </tr>
 1205:          <tr>
 1206:            <td>
 1207:             <table class="LC_nested">
 1208:              <tr class="LC_info_row">
 1209:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.
 1210:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
 1211:               <td class="LC_right_item" style="vertical-align: top">'.
 1212:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
 1213:              </tr>'.
 1214:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
 1215:            </table>
 1216:           </td>
 1217:          </tr>
 1218:          <tr>
 1219:            <td>
 1220:             <table class="LC_nested">
 1221:              <tr class="LC_info_row">
 1222:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1223:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1224:              </tr>'.
 1225:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
 1226:             $rowtotal += 2;
 1227:         }
 1228:     } else {
 1229:         $output .= '
 1230:           <tr>
 1231:            <td>
 1232:             <table class="LC_nested">
 1233:              <tr class="LC_info_row">';
 1234:         if ($action eq 'login') {
 1235:             $output .= '  
 1236:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1237:         } elsif ($action eq 'serverstatuses') {
 1238:             $output .= '
 1239:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).
 1240:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
 1241: 
 1242:         } else {
 1243:             $output .= '
 1244:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1245:         }
 1246:         if (defined($item->{'header'}->[0]->{'col3'})) {
 1247:             $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1248:                        &mt($item->{'header'}->[0]->{'col2'});
 1249:             if ($action eq 'serverstatuses') {
 1250:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
 1251:             } 
 1252:         } else {
 1253:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1254:                        &mt($item->{'header'}->[0]->{'col2'});
 1255:         }
 1256:         $output .= '</td>';
 1257:         if ($item->{'header'}->[0]->{'col3'}) {
 1258:             if (defined($item->{'header'}->[0]->{'col4'})) {
 1259:                 $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1260:                             &mt($item->{'header'}->[0]->{'col3'});
 1261:             } else {
 1262:                 $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1263:                            &mt($item->{'header'}->[0]->{'col3'});
 1264:             }
 1265:             if ($action eq 'serverstatuses') {
 1266:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
 1267:             }
 1268:             $output .= '</td>';
 1269:         }
 1270:         if ($item->{'header'}->[0]->{'col4'}) {
 1271:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1272:                        &mt($item->{'header'}->[0]->{'col4'});
 1273:         }
 1274:         $output .= '</tr>';
 1275:         $rowtotal ++;
 1276:         if ($action eq 'quotas') {
 1277:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
 1278:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
 1279:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') || 
 1280:                  ($action eq 'ltitools') || ($action eq 'proctoring') ||
 1281:                  ($action eq 'ipaccess')) {
 1282:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
 1283:         }
 1284:     }
 1285:     $output .= '
 1286:    </table>
 1287:   </td>
 1288:  </tr>
 1289: </table><br />';
 1290:     return ($output,$rowtotal);
 1291: }
 1292: 
 1293: sub print_login {
 1294:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
 1295:     my ($css_class,$datatable,$switchserver,%lt);
 1296:     my %choices = &login_choices();
 1297:     if (($caller eq 'help') || ($caller eq 'headtag') || ($caller eq 'saml')) {
 1298:         %lt = &login_file_options();
 1299:         $switchserver = &check_switchserver($dom,$confname);
 1300:     }
 1301:     if ($caller eq 'service') {
 1302:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1303:         my $choice = $choices{'disallowlogin'};
 1304:         $css_class = ' class="LC_odd_row"';
 1305:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1306:                       '<td style="text-align: right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1307:                       '<th>'.$choices{'server'}.'</th>'.
 1308:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1309:                       '<th>'.$choices{'custompath'}.'</th>'.
 1310:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1311:         my %disallowed;
 1312:         if (ref($settings) eq 'HASH') {
 1313:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1314:                %disallowed = %{$settings->{'loginvia'}};
 1315:             }
 1316:         }
 1317:         foreach my $lonhost (sort(keys(%servers))) {
 1318:             my $direct = 'selected="selected"';
 1319:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1320:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1321:                     $direct = '';
 1322:                 }
 1323:             }
 1324:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1325:                           '<td><select name="'.$lonhost.'_server">'.
 1326:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1327:                           '</option>';
 1328:             foreach my $hostid (sort(keys(%servers))) {
 1329:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1330:                 my $selected = '';
 1331:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1332:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1333:                         $selected = 'selected="selected"';
 1334:                     }
 1335:                 }
 1336:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1337:                               $servers{$hostid}.'</option>';
 1338:             }
 1339:             $datatable .= '</select></td>'.
 1340:                           '<td><select name="'.$lonhost.'_serverpath">';
 1341:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1342:                 my $pathname = $path;
 1343:                 if ($path eq 'custom') {
 1344:                     $pathname = &mt('Custom Path').' ->';
 1345:                 }
 1346:                 my $selected = '';
 1347:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1348:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1349:                         $selected = 'selected="selected"';
 1350:                     }
 1351:                 } elsif ($path eq '') {
 1352:                     $selected = 'selected="selected"';
 1353:                 }
 1354:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1355:             }
 1356:             $datatable .= '</select></td>';
 1357:             my ($custom,$exempt);
 1358:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1359:                 $custom = $disallowed{$lonhost}{'custompath'};
 1360:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1361:             }
 1362:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1363:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1364:                           '</tr>';
 1365:         }
 1366:         $datatable .= '</table></td></tr>';
 1367:         return $datatable;
 1368:     } elsif ($caller eq 'page') {
 1369:         my %defaultchecked = ( 
 1370:                                'coursecatalog' => 'on',
 1371:                                'helpdesk'      => 'on',
 1372:                                'adminmail'     => 'off',
 1373:                                'newuser'       => 'off',
 1374:                              );
 1375:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1376:         my (%checkedon,%checkedoff);
 1377:         foreach my $item (@toggles) {
 1378:             if ($defaultchecked{$item} eq 'on') { 
 1379:                 $checkedon{$item} = ' checked="checked" ';
 1380:                 $checkedoff{$item} = ' ';
 1381:             } elsif ($defaultchecked{$item} eq 'off') {
 1382:                 $checkedoff{$item} = ' checked="checked" ';
 1383:                 $checkedon{$item} = ' ';
 1384:             }
 1385:         }
 1386:         my @images = ('img','logo','domlogo','login');
 1387:         my @alttext = ('img','logo','domlogo');
 1388:         my @logintext = ('textcol','bgcol');
 1389:         my @bgs = ('pgbg','mainbg','sidebg');
 1390:         my @links = ('link','alink','vlink');
 1391:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1392:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1393:         my (%is_custom,%designs);
 1394:         my %defaults = (
 1395:                        font => $defaultdesign{'login.font'},
 1396:                        );
 1397:         foreach my $item (@images) {
 1398:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1399:             $defaults{'showlogo'}{$item} = 1;
 1400:         }
 1401:         foreach my $item (@bgs) {
 1402:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1403:         }
 1404:         foreach my $item (@logintext) {
 1405:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1406:         }
 1407:         foreach my $item (@links) {
 1408:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1409:         }
 1410:         if (ref($settings) eq 'HASH') {
 1411:             foreach my $item (@toggles) {
 1412:                 if ($settings->{$item} eq '1') {
 1413:                     $checkedon{$item} =  ' checked="checked" ';
 1414:                     $checkedoff{$item} = ' ';
 1415:                 } elsif ($settings->{$item} eq '0') {
 1416:                     $checkedoff{$item} =  ' checked="checked" ';
 1417:                     $checkedon{$item} = ' ';
 1418:                 }
 1419:             }
 1420:             foreach my $item (@images) {
 1421:                 if (defined($settings->{$item})) {
 1422:                     $designs{$item} = $settings->{$item};
 1423:                     $is_custom{$item} = 1;
 1424:                 }
 1425:                 if (defined($settings->{'showlogo'}{$item})) {
 1426:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1427:                 }
 1428:             }
 1429:             foreach my $item (@alttext) {
 1430:                 if (ref($settings->{'alttext'}) eq 'HASH') {
 1431:                     if ($settings->{'alttext'}->{$item} ne '') {
 1432:                         $designs{'alttext'}{$item} = $settings->{'alttext'}{$item};
 1433:                     }
 1434:                 }
 1435:             }
 1436:             foreach my $item (@logintext) {
 1437:                 if ($settings->{$item} ne '') {
 1438:                     $designs{'logintext'}{$item} = $settings->{$item};
 1439:                     $is_custom{$item} = 1;
 1440:                 }
 1441:             }
 1442:             if ($settings->{'font'} ne '') {
 1443:                 $designs{'font'} = $settings->{'font'};
 1444:                 $is_custom{'font'} = 1;
 1445:             }
 1446:             foreach my $item (@bgs) {
 1447:                 if ($settings->{$item} ne '') {
 1448:                     $designs{'bgs'}{$item} = $settings->{$item};
 1449:                     $is_custom{$item} = 1;
 1450:                 }
 1451:             }
 1452:             foreach my $item (@links) {
 1453:                 if ($settings->{$item} ne '') {
 1454:                     $designs{'links'}{$item} = $settings->{$item};
 1455:                     $is_custom{$item} = 1;
 1456:                 }
 1457:             }
 1458:         } else {
 1459:             if ($designhash{$dom.'.login.font'} ne '') {
 1460:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1461:                 $is_custom{'font'} = 1;
 1462:             }
 1463:             foreach my $item (@images) {
 1464:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1465:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1466:                     $is_custom{$item} = 1;
 1467:                 }
 1468:             }
 1469:             foreach my $item (@bgs) {
 1470:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1471:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1472:                     $is_custom{$item} = 1;
 1473:                 }
 1474:             }
 1475:             foreach my $item (@links) {
 1476:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1477:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1478:                     $is_custom{$item} = 1;
 1479:                 }
 1480:             }
 1481:         }
 1482:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1483:                                                       logo => 'Institution Logo',
 1484:                                                       domlogo => 'Domain Logo',
 1485:                                                       login => 'Login box');
 1486:         my $itemcount = 1;
 1487:         foreach my $item (@toggles) {
 1488:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1489:             $datatable .=  
 1490:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1491:                 '</td><td>'.
 1492:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1493:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1494:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1495:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1496:                 '</tr>';
 1497:             $itemcount ++;
 1498:         }
 1499:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1500:         $datatable .= '</tr></table></td></tr>';
 1501:     } elsif ($caller eq 'help') {
 1502:         my ($defaulturl,$defaulttype,%url,%type,%langchoices);
 1503:         my $itemcount = 1;
 1504:         $defaulturl = '/adm/loginproblems.html';
 1505:         $defaulttype = 'default';
 1506:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1507:         my @currlangs;
 1508:         if (ref($settings) eq 'HASH') {
 1509:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1510:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1511:                     next if ($settings->{'helpurl'}{$key} eq '');
 1512:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1513:                     $type{$key} = 'custom';
 1514:                     unless ($key eq 'nolang') {
 1515:                         push(@currlangs,$key);
 1516:                     }
 1517:                 }
 1518:             } elsif ($settings->{'helpurl'} ne '') {
 1519:                 $type{'nolang'} = 'custom';
 1520:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1521:             }
 1522:         }
 1523:         foreach my $lang ('nolang',sort(@currlangs)) {
 1524:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1525:             $datatable .= '<tr'.$css_class.'>';
 1526:             if ($url{$lang} eq '') {
 1527:                 $url{$lang} = $defaulturl;
 1528:             }
 1529:             if ($type{$lang} eq '') {
 1530:                 $type{$lang} = $defaulttype;
 1531:             }
 1532:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1533:             if ($lang eq 'nolang') {
 1534:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1535:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1536:             } else {
 1537:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1538:                                   $langchoices{$lang},
 1539:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1540:             }
 1541:             $datatable .= '</span></td>'."\n".
 1542:                           '<td class="LC_left_item">';
 1543:             if ($type{$lang} eq 'custom') {
 1544:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1545:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1546:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1547:             } else {
 1548:                 $datatable .= $lt{'upl'};
 1549:             }
 1550:             $datatable .='<br />';
 1551:             if ($switchserver) {
 1552:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1553:             } else {
 1554:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1555:             }
 1556:             $datatable .= '</td></tr>';
 1557:             $itemcount ++;
 1558:         }
 1559:         my @addlangs;
 1560:         foreach my $lang (sort(keys(%langchoices))) {
 1561:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1562:             push(@addlangs,$lang);
 1563:         }
 1564:         if (@addlangs > 0) {
 1565:             my %toadd;
 1566:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1567:             $toadd{''} = &mt('Select');
 1568:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1569:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1570:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1571:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1572:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1573:             if ($switchserver) {
 1574:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1575:             } else {
 1576:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1577:             }
 1578:             $datatable .= '</td></tr>';
 1579:             $itemcount ++;
 1580:         }
 1581:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1582:     } elsif ($caller eq 'headtag') {
 1583:         my %domservers = &Apache::lonnet::get_servers($dom);
 1584:         my $choice = $choices{'headtag'};
 1585:         $css_class = ' class="LC_odd_row"';
 1586:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1587:                       '<td style="text-align: left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1588:                       '<th>'.$choices{'current'}.'</th>'.
 1589:                       '<th>'.$choices{'action'}.'</th>'.
 1590:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1591:         my (%currurls,%currexempt);
 1592:         if (ref($settings) eq 'HASH') {
 1593:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1594:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1595:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1596:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1597:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1598:                     }
 1599:                 }
 1600:             }
 1601:         }
 1602:         foreach my $lonhost (sort(keys(%domservers))) {
 1603:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1604:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1605:             if ($currurls{$lonhost}) {
 1606:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1607:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1608:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1609:                               '">'.$lt{'curr'}.'</a></td>'.
 1610:                               '<td><span class="LC_nobreak"><label>'.
 1611:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1612:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1613:             } else {
 1614:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1615:             }
 1616:             $datatable .='<br />';
 1617:             if ($switchserver) {
 1618:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1619:             } else {
 1620:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1621:             }
 1622:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1623:         }
 1624:         $datatable .= '</table></td></tr>';
 1625:     } elsif ($caller eq 'saml') {
 1626:         my %domservers = &Apache::lonnet::get_servers($dom);
 1627:         $datatable .= '<tr><td colspan="3" style="text-align: left">'.
 1628:                       '<table><tr><th>'.$choices{'hostid'}.'</th>'.
 1629:                       '<th>'.$choices{'samllanding'}.'</th>'.
 1630:                       '<th>'.$choices{'samloptions'}.'</th></tr>'."\n";
 1631:         my (%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlwindow,%samlnotsso,%styleon,%styleoff);
 1632:         foreach my $lonhost (keys(%domservers)) {
 1633:             $samlurl{$lonhost} = '/adm/sso';
 1634:             $styleon{$lonhost} = 'display:none';
 1635:             $styleoff{$lonhost} = '';
 1636:         }
 1637:         if ((ref($settings) eq 'HASH') && (ref($settings->{'saml'}) eq 'HASH')) {
 1638:             foreach my $lonhost (keys(%{$settings->{'saml'}})) {
 1639:                 if (ref($settings->{'saml'}{$lonhost}) eq 'HASH') {
 1640:                     $saml{$lonhost} = 1;
 1641:                     $samltext{$lonhost} = $settings->{'saml'}{$lonhost}{'text'};
 1642:                     $samlimg{$lonhost} = $settings->{'saml'}{$lonhost}{'img'};
 1643:                     $samlalt{$lonhost} = $settings->{'saml'}{$lonhost}{'alt'};
 1644:                     $samlurl{$lonhost} = $settings->{'saml'}{$lonhost}{'url'};
 1645:                     $samltitle{$lonhost} = $settings->{'saml'}{$lonhost}{'title'};
 1646:                     $samlwindow{$lonhost} = $settings->{'saml'}{$lonhost}{'window'};
 1647:                     $samlnotsso{$lonhost} = $settings->{'saml'}{$lonhost}{'notsso'};
 1648:                     $styleon{$lonhost} = '';
 1649:                     $styleoff{$lonhost} = 'display:none';
 1650:                 } else {
 1651:                     $styleon{$lonhost} = 'display:none';
 1652:                     $styleoff{$lonhost} = '';
 1653:                 }
 1654:             }
 1655:         }
 1656:         my $itemcount = 1;
 1657:         foreach my $lonhost (sort(keys(%domservers))) {
 1658:             my $samlon = ' ';
 1659:             my $samloff = ' checked="checked" ';
 1660:             if ($saml{$lonhost}) {
 1661:                 $samlon = $samloff;
 1662:                 $samloff = ' ';
 1663:             }
 1664:             my $samlwinon = '';
 1665:             my $samlwinoff = ' checked="checked"';
 1666:             if ($samlwindow{$lonhost}) {
 1667:                 $samlwinon = $samlwinoff;
 1668:                 $samlwinoff = '';
 1669:             }
 1670:             my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1671:             $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.$domservers{$lonhost}.'</span></td>'.
 1672:                           '<td><span class="LC_nobreak"><label><input type="radio" name="saml_'.$lonhost.'"'.$samloff.
 1673:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="0" />'.
 1674:                           &mt('No').'</label>'.('&nbsp;'x2).
 1675:                           '<label><input type="radio" name="saml_'.$lonhost.'"'.$samlon.
 1676:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="1" />'.
 1677:                           &mt('Yes').'</label></span></td>'.
 1678:                           '<td id="samloptionson_'.$lonhost.'" style="'.$styleon{$lonhost}.'" width="100%">'.
 1679:                           '<table width="100%"><tr><th colspan="3" align="center">'.&mt('SSO').'</th></tr>'.
 1680:                           '<tr><th>'.&mt('Text').'</th><th>'.&mt('Image').'</th>'.
 1681:                           '<th>'.&mt('Alt Text').'</th></tr>'.
 1682:                           '<tr'.$css_class.'><td><input type="text" name="saml_text_'.$lonhost.'" size="20" value="'.
 1683:                           $samltext{$lonhost}.'" /></td><td>';
 1684:             if ($samlimg{$lonhost}) {
 1685:                 $datatable .= '<img src="'.$samlimg{$lonhost}.'" /><br />'.
 1686:                               '<span class="LC_nobreak"><label>'.
 1687:                               '<input type="checkbox" name="saml_img_del" value="'.$lonhost.'" />'.
 1688:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1689:             } else {
 1690:                 $datatable .= $lt{'upl'};
 1691:             }
 1692:             $datatable .='<br />';
 1693:             if ($switchserver) {
 1694:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1695:             } else {
 1696:                 $datatable .= '<input type="file" name="saml_img_'.$lonhost.'" />';
 1697:             }
 1698:             $datatable .= '</td>'.
 1699:                           '<td><input type="text" name="saml_alt_'.$lonhost.'" size="25" '.
 1700:                           'value="'.$samlalt{$lonhost}.'" /></td></tr></table><br />'.
 1701:                           '<table width="100%"><tr><th colspan="3" align="center">'.&mt('SSO').'</th><th align="center">'.
 1702:                           '<span class="LC_nobreak">'.&mt('Non-SSO').'</span></th></tr>'.
 1703:                           '<tr><th>'.&mt('URL').'</th><th>'.&mt('Tool Tip').'</th>'.
 1704:                           '<th>'.&mt('Pop-up if iframe').'</th><th>'.&mt('Text').'</th></tr>'.
 1705:                           '<tr'.$css_class.'>'.
 1706:                           '<td><input type="text" name="saml_url_'.$lonhost.'" size="30" '.
 1707:                           'value="'.$samlurl{$lonhost}.'" /></td>'.
 1708:                           '<td><textarea name="saml_title_'.$lonhost.'" rows="3" cols="20">'.
 1709:                           $samltitle{$lonhost}.'</textarea></td>'.
 1710:                           '<td><label><input type="radio" name="saml_window_'.$lonhost.'" value=""'.$samlwinoff.'>'.
 1711:                           &mt('No').'</label>'.('&nbsp;'x2).'<label><input type="radio" '.
 1712:                           'name="saml_window_'.$lonhost.'" value="1"'.$samlwinon.'>'.&mt('Yes').'</label></td>'.
 1713:                           '<td><input type="text" name="saml_notsso_'.$lonhost.'" size="12" '.
 1714:                           'value="'.$samlnotsso{$lonhost}.'" /></td></tr>'.
 1715:                           '</table></td>'.
 1716:                           '<td id="samloptionsoff_'.$lonhost.'" style="'.$styleoff{$lonhost}.'" width="100%">&nbsp;</td></tr>';
 1717:            $itemcount ++;
 1718:         }
 1719:         $datatable .= '</table></td></tr>';
 1720:     }
 1721:     return $datatable;
 1722: }
 1723: 
 1724: sub login_choices {
 1725:     my %choices =
 1726:         &Apache::lonlocal::texthash (
 1727:             coursecatalog => 'Display Course/Community Catalog link?',
 1728:             adminmail     => "Display Administrator's E-mail Address?",
 1729:             helpdesk      => 'Display "Contact Helpdesk" link',
 1730:             disallowlogin => "Login page requests redirected",
 1731:             hostid        => "Server",
 1732:             server        => "Redirect to:",
 1733:             serverpath    => "Path",
 1734:             custompath    => "Custom", 
 1735:             exempt        => "Exempt IP(s)",
 1736:             directlogin   => "No redirect",
 1737:             newuser       => "Link to create a user account",
 1738:             img           => "Header",
 1739:             logo          => "Main Logo",
 1740:             domlogo       => "Domain Logo",
 1741:             login         => "Log-in Header", 
 1742:             textcol       => "Text color",
 1743:             bgcol         => "Box color",
 1744:             bgs           => "Background colors",
 1745:             links         => "Link colors",
 1746:             font          => "Font color",
 1747:             pgbg          => "Header",
 1748:             mainbg        => "Page",
 1749:             sidebg        => "Login box",
 1750:             link          => "Link",
 1751:             alink         => "Active link",
 1752:             vlink         => "Visited link",
 1753:             headtag       => "Custom markup",
 1754:             action        => "Action",
 1755:             current       => "Current",
 1756:             samllanding   => "Dual login?",
 1757:             samloptions   => "Options",
 1758:             alttext       => "Alt text",
 1759:         );
 1760:     return %choices;
 1761: }
 1762: 
 1763: sub login_file_options {
 1764:       return &Apache::lonlocal::texthash(
 1765:                                            del     => 'Delete?',
 1766:                                            rep     => 'Replace:',
 1767:                                            upl     => 'Upload:',
 1768:                                            curr    => 'View contents',
 1769:                                            default => 'Default',
 1770:                                            custom  => 'Custom',
 1771:                                            none    => 'None',
 1772:       );
 1773: }
 1774: 
 1775: sub print_ipaccess {
 1776:     my ($dom,$settings,$rowtotal) = @_;
 1777:     my $css_class;
 1778:     my $itemcount = 0;
 1779:     my $datatable;
 1780:     my %ordered;
 1781:     if (ref($settings) eq 'HASH') {
 1782:         foreach my $item (keys(%{$settings})) {
 1783:             if (ref($settings->{$item}) eq 'HASH') {
 1784:                 my $num = $settings->{$item}{'order'};
 1785:                 if ($num eq '') {
 1786:                     $num = scalar(keys(%{$settings}));
 1787:                 }
 1788:                 $ordered{$num} = $item;
 1789:             }
 1790:         }
 1791:     }
 1792:     my $maxnum = scalar(keys(%ordered));
 1793:     if (keys(%ordered)) {
 1794:         my @items = sort { $a <=> $b } keys(%ordered);
 1795:         for (my $i=0; $i<@items; $i++) {
 1796:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1797:             my $item = $ordered{$items[$i]};
 1798:             my ($name,$ipranges,%commblocks,%courses);
 1799:             if (ref($settings->{$item}) eq 'HASH') {
 1800:                 $name = $settings->{$item}->{'name'};
 1801:                 $ipranges = $settings->{$item}->{'ip'};
 1802:                 if (ref($settings->{$item}->{'commblocks'}) eq 'HASH') {
 1803:                     %commblocks = %{$settings->{$item}->{'commblocks'}};
 1804:                 }
 1805:                 if (ref($settings->{$item}->{'courses'}) eq 'HASH') {
 1806:                     %courses = %{$settings->{$item}->{'courses'}};
 1807:                 }
 1808:             }
 1809:             my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_".$item."'".');"';
 1810:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 1811:                          .'<select name="ipaccess_pos_'.$item.'"'.$chgstr.'>';
 1812:             for (my $k=0; $k<=$maxnum; $k++) {
 1813:                 my $vpos = $k+1;
 1814:                 my $selstr;
 1815:                 if ($k == $i) {
 1816:                     $selstr = ' selected="selected" ';
 1817:                 }
 1818:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1819:             }
 1820:             $datatable .= '</select>'.('&nbsp;'x2).
 1821:                 '<label><input type="checkbox" name="ipaccess_del" value="'.$item.'" />'.
 1822:                 &mt('Delete?').'</label></span></td>'.
 1823:                 '<td colspan="2"><input type="hidden" name="ipaccess_id_'.$i.'" value="'.$item.'" />'.
 1824:                 &ipaccess_options($i,$itemcount,$dom,$name,$ipranges,\%commblocks,\%courses).
 1825:                 '</td></tr>';
 1826:             $itemcount ++;
 1827:         }
 1828:     }
 1829:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1830:     my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_add'".');"';
 1831:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 1832:                   '<input type="hidden" name="ipaccess_maxnum" value="'.$maxnum.'" />'."\n".
 1833:                   '<select name="ipaccess_pos_add"'.$chgstr.'>';
 1834:     for (my $k=0; $k<$maxnum+1; $k++) {
 1835:         my $vpos = $k+1;
 1836:         my $selstr;
 1837:         if ($k == $maxnum) {
 1838:             $selstr = ' selected="selected" ';
 1839:         }
 1840:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1841:     }
 1842:     $datatable .= '</select>&nbsp;'."\n".
 1843:                   '<input type="checkbox" name="ipaccess_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 1844:                   '<td colspan="2">'.
 1845:                   &ipaccess_options('add',$itemcount,$dom).
 1846:                   '</td>'."\n".
 1847:                   '</tr>'."\n";
 1848:     $$rowtotal ++;
 1849:     return $datatable;
 1850: }
 1851: 
 1852: sub ipaccess_options {
 1853:     my ($num,$itemcount,$dom,$name,$ipranges,$blocksref,$coursesref) = @_;
 1854:     my (%currblocks,%currcourses,$output);
 1855:     if (ref($blocksref) eq 'HASH') {
 1856:         %currblocks = %{$blocksref};
 1857:     }
 1858:     if (ref($coursesref) eq 'HASH') {
 1859:         %currcourses = %{$coursesref};
 1860:     }
 1861:     $output = '<fieldset><legend>'.&mt('Location(s)').'</legend>'.
 1862:               '<span class="LC_nobreak">'.&mt('Name').':&nbsp;'.
 1863:               '<input type="text" name="ipaccess_name_'.$num.'" value="'.$name.'" />'.
 1864:               '</span></fieldset>'.
 1865:               '<fieldset><legend>'.&mt('IP Range(s)').'</legend>'.
 1866:               &mt('Format for each IP range').': '.&mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 1867:               &mt('Range(s) will be stored as IP netblock(s) in CIDR notation (comma separated)').'<br />'.
 1868:               '<textarea name="ipaccess_range_'.$num.'" rows="3" cols="80">'.
 1869:               $ipranges.'</textarea></fieldset>'.
 1870:               '<fieldset><legend>'.&mt('Functionality Blocked?').'</legend>'.
 1871:               &blocker_checkboxes($num,$blocksref).'</fieldset>'.
 1872:               '<fieldset><legend>'.&mt('Courses/Communities allowed').'</legend>'.
 1873:               '<table>';
 1874:     foreach my $cid (sort(keys(%currcourses))) {
 1875:         my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
 1876:         $output .= '<tr><td><span class="LC_nobreak">'.
 1877:                    '<label><input type="checkbox" name="ipaccess_course_delete_'.$num.'" value="'.$cid.'" />'.
 1878:                    &mt('Delete?').'&nbsp;<span class="LC_cusr_emph">'.$courseinfo{'description'}.'</span></label></span>'.
 1879:                    ' <span class="LC_fontsize_medium">('.$cid.')</span></td></tr>';
 1880:     }
 1881:     $output .= '<tr><td><span class="LC_nobreak">'.&mt('Add').':&nbsp;'.
 1882:                '<input type="text" name="ipaccess_cdesc_'.$num.'" value="" onfocus="this.blur();opencrsbrowser('."'display','ipaccess_cnum_$num','ipaccess_cdom_$num','ipaccess_cdesc_$num'".');" />'.
 1883:                 &Apache::loncommon::selectcourse_link('display','ipaccess_cnum_'.$num,'ipaccess_cdom_'.$num,'ipaccess_cdesc_'.$num,$dom,undef,'Course/Community').
 1884:                '<input type="hidden" name="ipaccess_cnum_'.$num.'" value="" />'.
 1885:                '<input type="hidden" name="ipaccess_cdom_'.$num.'" value="" />'.
 1886:                '</span></td></tr></table>'."\n".
 1887:                '</fieldset>';
 1888:     return $output;
 1889: }
 1890: 
 1891: sub blocker_checkboxes {
 1892:     my ($num,$blocks) = @_;
 1893:     my ($typeorder,$types) = &commblocktype_text();
 1894:     my $numinrow = 6;
 1895:     my $output = '<table>';
 1896:     for (my $i=0; $i<@{$typeorder}; $i++) {
 1897:         my $block = $typeorder->[$i];
 1898:         my $blockstatus;
 1899:         if (ref($blocks) eq 'HASH') {
 1900:             if ($blocks->{$block} eq 'on') {
 1901:                 $blockstatus = 'checked="checked"';
 1902:             }
 1903:         }
 1904:         my $rem = $i%($numinrow);
 1905:         if ($rem == 0) {
 1906:             if ($i > 0) {
 1907:                 $output .= '</tr>';
 1908:             }
 1909:             $output .= '<tr>';
 1910:         }
 1911:         if ($i == scalar(@{$typeorder})-1) {
 1912:             my $colsleft = $numinrow-$rem;
 1913:             if ($colsleft > 1) {
 1914:                 $output .= '<td colspan="'.$colsleft.'">';
 1915:             } else {
 1916:                 $output .= '<td>';
 1917:             }
 1918:         } else {
 1919:             $output .= '<td>';
 1920:         }
 1921:         my $item = 'ipaccess_block_'.$num;
 1922:         if ($blockstatus) {
 1923:             $blockstatus = ' '.$blockstatus;
 1924:         }
 1925:         $output .= '<span class="LC_nobreak"><label>'."\n".
 1926:                    '<input type="checkbox" name="'.$item.'"'.
 1927:                    $blockstatus.' value="'.$block.'"'.' />'.
 1928:                    $types->{$block}.'</label></span>'."\n".
 1929:                    '<br /></td>';
 1930:     }
 1931:     $output .= '</tr></table>';
 1932:     return $output;
 1933: }
 1934: 
 1935: sub commblocktype_text {
 1936:     my %types = &Apache::lonlocal::texthash(
 1937:         'com' => 'Messaging',
 1938:         'chat' => 'Chat Room',
 1939:         'boards' => 'Discussion',
 1940:         'port' => 'Portfolio',
 1941:         'groups' => 'Groups',
 1942:         'blogs' => 'Blogs',
 1943:         'about' => 'User Information',
 1944:         'printout' => 'Printouts',
 1945:         'passwd' => 'Change Password',
 1946:         'grades' => 'Gradebook',
 1947:         'search' => 'Course search',
 1948:         'wishlist' => 'Stored links',
 1949:         'annotate' => 'Annotations',
 1950:     );
 1951:     my $typeorder = ['com','chat','boards','port','groups','blogs','about','wishlist','printout','grades','search','annotate','passwd'];
 1952:     return ($typeorder,\%types);
 1953: }
 1954: 
 1955: sub print_rolecolors {
 1956:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1957:     my %choices = &color_font_choices();
 1958:     my @bgs = ('pgbg','tabbg','sidebg');
 1959:     my @links = ('link','alink','vlink');
 1960:     my @images = ('img');
 1961:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1962:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1963:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1964:     my (%is_custom,%designs);
 1965:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1966:     if (ref($settings) eq 'HASH') {
 1967:         if (ref($settings->{$role}) eq 'HASH') {
 1968:             if ($settings->{$role}->{'img'} ne '') {
 1969:                 $designs{'img'} = $settings->{$role}->{'img'};
 1970:                 $is_custom{'img'} = 1;
 1971:             }
 1972:             if ($settings->{$role}->{'font'} ne '') {
 1973:                 $designs{'font'} = $settings->{$role}->{'font'};
 1974:                 $is_custom{'font'} = 1;
 1975:             }
 1976:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1977:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1978:                 $is_custom{'fontmenu'} = 1;
 1979:             }
 1980:             foreach my $item (@bgs) {
 1981:                 if ($settings->{$role}->{$item} ne '') {
 1982:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1983:                     $is_custom{$item} = 1;
 1984:                 }
 1985:             }
 1986:             foreach my $item (@links) {
 1987:                 if ($settings->{$role}->{$item} ne '') {
 1988:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1989:                     $is_custom{$item} = 1;
 1990:                 }
 1991:             }
 1992:         }
 1993:     } else {
 1994:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1995:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1996:             $is_custom{'img'} = 1;
 1997:         }
 1998:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1999:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 2000:             $is_custom{'fontmenu'} = 1; 
 2001:         }
 2002:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 2003:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 2004:             $is_custom{'font'} = 1;
 2005:         }
 2006:         foreach my $item (@bgs) {
 2007:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 2008:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 2009:                 $is_custom{$item} = 1;
 2010:             
 2011:             }
 2012:         }
 2013:         foreach my $item (@links) {
 2014:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 2015:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 2016:                 $is_custom{$item} = 1;
 2017:             }
 2018:         }
 2019:     }
 2020:     my $itemcount = 1;
 2021:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 2022:     $datatable .= '</tr></table></td></tr>';
 2023:     return $datatable;
 2024: }
 2025: 
 2026: sub role_defaults {
 2027:     my ($role,$bgs,$links,$images,$logintext) = @_;
 2028:     my %defaults;
 2029:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 2030:         return %defaults;
 2031:     }
 2032:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 2033:     if ($role eq 'login') {
 2034:         %defaults = (
 2035:                        font => $defaultdesign{$role.'.font'},
 2036:                     );
 2037:         if (ref($logintext) eq 'ARRAY') {
 2038:             foreach my $item (@{$logintext}) {
 2039:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 2040:             }
 2041:         }
 2042:         foreach my $item (@{$images}) {
 2043:             $defaults{'showlogo'}{$item} = 1;
 2044:         }
 2045:     } else {
 2046:         %defaults = (
 2047:                        img => $defaultdesign{$role.'.img'},
 2048:                        font => $defaultdesign{$role.'.font'},
 2049:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 2050:                     );
 2051:     }
 2052:     foreach my $item (@{$bgs}) {
 2053:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 2054:     }
 2055:     foreach my $item (@{$links}) {
 2056:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 2057:     }
 2058:     foreach my $item (@{$images}) {
 2059:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 2060:     }
 2061:     return %defaults;
 2062: }
 2063: 
 2064: sub display_color_options {
 2065:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 2066:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 2067:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2068:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2069:     my $datatable = '<tr'.$css_class.'>'.
 2070:         '<td>'.$choices->{'font'}.'</td>';
 2071:     if (!$is_custom->{'font'}) {
 2072:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 2073:     } else {
 2074:         $datatable .= '<td>&nbsp;</td>';
 2075:     }
 2076:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 2077: 
 2078:     $datatable .= '<td><span class="LC_nobreak">'.
 2079:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 2080:                   ' value="'.$current_color.'" />&nbsp;'.
 2081:                   '&nbsp;</span></td></tr>';
 2082:     unless ($role eq 'login') { 
 2083:         $datatable .= '<tr'.$css_class.'>'.
 2084:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 2085:         if (!$is_custom->{'fontmenu'}) {
 2086:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 2087:         } else {
 2088:             $datatable .= '<td>&nbsp;</td>';
 2089:         }
 2090: 	$current_color = $designs->{'fontmenu'} ?
 2091: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 2092:         $datatable .= '<td><span class="LC_nobreak">'.
 2093:                       '<input class="colorchooser" type="text" size="10" name="'
 2094: 		      .$role.'_fontmenu"'.
 2095:                       ' value="'.$current_color.'" />&nbsp;'.
 2096:                       '&nbsp;</span></td></tr>';
 2097:     }
 2098:     my $switchserver = &check_switchserver($dom,$confname);
 2099:     foreach my $img (@{$images}) {
 2100: 	$itemcount ++;
 2101:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2102:         $datatable .= '<tr'.$css_class.'>'.
 2103:                       '<td>'.$choices->{$img};
 2104:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors,$alttext);
 2105:         if ($role eq 'login') {
 2106:             if ($img eq 'login') {
 2107:                 $login_hdr_pick =
 2108:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 2109:                 $logincolors =
 2110:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 2111:                                        $designs,$defaults);
 2112:             } else {
 2113:                 if ($img ne 'domlogo') {
 2114:                     $datatable.= &logo_display_options($img,$defaults,$designs);
 2115:                 }
 2116:                 if (ref($designs->{'alttext'}) eq 'HASH') {
 2117:                     $alttext = $designs->{'alttext'}{$img};
 2118:                 }
 2119:             }
 2120:         }
 2121:         $datatable .= '</td>';
 2122:         if ($designs->{$img} ne '') {
 2123:             $imgfile = $designs->{$img};
 2124: 	    $img_import = ($imgfile =~ m{^/adm/});
 2125:         } else {
 2126:             $imgfile = $defaults->{$img};
 2127:         }
 2128:         if ($imgfile) {
 2129:             my ($showfile,$fullsize);
 2130:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 2131:                 my $urldir = $1;
 2132:                 my $filename = $2;
 2133:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 2134:                 if (@info) {
 2135:                     my $thumbfile = 'tn-'.$filename;
 2136:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 2137:                     if (@thumb) {
 2138:                         $showfile = $urldir.'/'.$thumbfile;
 2139:                     } else {
 2140:                         $showfile = $imgfile;
 2141:                     }
 2142:                 } else {
 2143:                     $showfile = '';
 2144:                 }
 2145:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 2146:                 $showfile = $imgfile;
 2147:                 my $imgdir = $1;
 2148:                 my $filename = $2;
 2149:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 2150:                     $showfile = "/$imgdir/tn-".$filename;
 2151:                 } else {
 2152:                     my $input = $londocroot.$imgfile;
 2153:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 2154:                     if (!-e $output) {
 2155:                         my ($width,$height) = &thumb_dimensions();
 2156:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 2157:                         if ($fullwidth ne '' && $fullheight ne '') {
 2158:                             if ($fullwidth > $width && $fullheight > $height) { 
 2159:                                 my $size = $width.'x'.$height;
 2160:                                 my @args = ('convert','-sample',$size,$input,$output);
 2161:                                 system({$args[0]} @args);
 2162:                                 $showfile = "/$imgdir/tn-".$filename;
 2163:                             }
 2164:                         }
 2165:                     }
 2166:                 }
 2167:             }
 2168:             if ($showfile) {
 2169:                 if ($showfile =~ m{^/(adm|res)/}) {
 2170:                     if ($showfile =~ m{^/res/}) {
 2171:                         my $local_showfile =
 2172:                             &Apache::lonnet::filelocation('',$showfile);
 2173:                         &Apache::lonnet::repcopy($local_showfile);
 2174:                     }
 2175:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 2176:                 }
 2177:                 if ($imgfile) {
 2178:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 2179:                         if ($imgfile =~ m{^/res/}) {
 2180:                             my $local_imgfile =
 2181:                                 &Apache::lonnet::filelocation('',$imgfile);
 2182:                             &Apache::lonnet::repcopy($local_imgfile);
 2183:                         }
 2184:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 2185:                     } else {
 2186:                         $fullsize = $imgfile;
 2187:                     }
 2188:                 }
 2189:                 $datatable .= '<td>';
 2190:                 if ($img eq 'login') {
 2191:                     $datatable .= $login_hdr_pick;
 2192:                 } 
 2193:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 2194:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 2195:             } else {
 2196:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2197:                               &mt('Upload:').'<br />';
 2198:             }
 2199:         } else {
 2200:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2201:                           &mt('Upload:').'<br />';
 2202:         }
 2203:         if ($switchserver) {
 2204:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2205:         } else {
 2206:             if ($img ne 'login') { # suppress file selection for Log-in header
 2207:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 2208:             }
 2209:         }
 2210:         if (($role eq 'login') && ($img ne 'login')) {
 2211:             $datatable .= ('&nbsp;' x2).' <span class="LC_nobreak"><label>'.$choices->{'alttext'}.':'.
 2212:                           '<input type="text" name="'.$role.'_alt_'.$img.'" size="10" value="'.$alttext.'" />'.
 2213:                           '</label></span>';
 2214:         }
 2215:         $datatable .= '</td></tr>';
 2216:     }
 2217:     $itemcount ++;
 2218:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2219:     $datatable .= '<tr'.$css_class.'>'.
 2220:                   '<td>'.$choices->{'bgs'}.'</td>';
 2221:     my $bgs_def;
 2222:     foreach my $item (@{$bgs}) {
 2223:         if (!$is_custom->{$item}) {
 2224:             $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>';
 2225:         }
 2226:     }
 2227:     if ($bgs_def) {
 2228:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 2229:     } else {
 2230:         $datatable .= '<td>&nbsp;</td>';
 2231:     }
 2232:     $datatable .= '<td class="LC_right_item">'.
 2233:                   '<table border="0"><tr>';
 2234: 
 2235:     foreach my $item (@{$bgs}) {
 2236:         $datatable .= '<td style="text-align: center">'.$choices->{$item};
 2237: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 2238:         if ($designs->{'bgs'}{$item}) {
 2239:             $datatable .= '&nbsp;';
 2240:         }
 2241:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2242:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2243:     }
 2244:     $datatable .= '</tr></table></td></tr>';
 2245:     $itemcount ++;
 2246:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2247:     $datatable .= '<tr'.$css_class.'>'.
 2248:                   '<td>'.$choices->{'links'}.'</td>';
 2249:     my $links_def;
 2250:     foreach my $item (@{$links}) {
 2251:         if (!$is_custom->{$item}) {
 2252:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 2253:         }
 2254:     }
 2255:     if ($links_def) {
 2256:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 2257:     } else {
 2258:         $datatable .= '<td>&nbsp;</td>';
 2259:     }
 2260:     $datatable .= '<td class="LC_right_item">'.
 2261:                   '<table border="0"><tr>';
 2262:     foreach my $item (@{$links}) {
 2263: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 2264:         $datatable .= '<td style="text-align: center">'.$choices->{$item}."\n";
 2265:         if ($designs->{'links'}{$item}) {
 2266:             $datatable.='&nbsp;';
 2267:         }
 2268:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 2269:                       '" /></td>';
 2270:     }
 2271:     $$rowtotal += $itemcount;
 2272:     return $datatable;
 2273: }
 2274: 
 2275: sub logo_display_options {
 2276:     my ($img,$defaults,$designs) = @_;
 2277:     my $checkedon;
 2278:     if (ref($defaults) eq 'HASH') {
 2279:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 2280:             if ($defaults->{'showlogo'}{$img}) {
 2281:                 $checkedon = 'checked="checked" ';     
 2282:             }
 2283:         } 
 2284:     }
 2285:     if (ref($designs) eq 'HASH') {
 2286:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 2287:             if (defined($designs->{'showlogo'}{$img})) {
 2288:                 if ($designs->{'showlogo'}{$img} == 0) {
 2289:                     $checkedon = '';
 2290:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 2291:                     $checkedon = 'checked="checked" ';
 2292:                 }
 2293:             }
 2294:         }
 2295:     }
 2296:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 2297:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 2298:            &mt('show').'</label>'."\n";
 2299: }
 2300: 
 2301: sub login_header_options  {
 2302:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 2303:     my $output = '';
 2304:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 2305:         $output .= &mt('Text default(s):').'<br />';
 2306:         if (!$is_custom->{'textcol'}) {
 2307:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 2308:                        '&nbsp;&nbsp;&nbsp;';
 2309:         }
 2310:         if (!$is_custom->{'bgcol'}) {
 2311:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 2312:                        '<span id="css_'.$role.'_font" style="background-color: '.
 2313:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 2314:         }
 2315:         $output .= '<br />';
 2316:     }
 2317:     $output .='<br />';
 2318:     return $output;
 2319: }
 2320: 
 2321: sub login_text_colors {
 2322:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 2323:     my $color_menu = '<table border="0"><tr>';
 2324:     foreach my $item (@{$logintext}) {
 2325:         $color_menu .= '<td style="text-align: center">'.$choices->{$item};
 2326:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 2327:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2328:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2329:     }
 2330:     $color_menu .= '</tr></table><br />';
 2331:     return $color_menu;
 2332: }
 2333: 
 2334: sub image_changes {
 2335:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 2336:     my $output;
 2337:     if ($img eq 'login') {
 2338:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 2339:     } elsif (!$is_custom) {
 2340:         if ($img ne 'domlogo') {
 2341:             $output = &mt('Default image:').'<br />';
 2342:         } else {
 2343:             $output = &mt('Default in use:').'<br />';
 2344:         }
 2345:     }
 2346:     if ($img ne 'login') {
 2347:         if ($img_import) {
 2348:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 2349:         }
 2350:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 2351:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 2352:         if ($is_custom) {
 2353:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 2354:                        '<input type="checkbox" name="'.
 2355:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 2356:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 2357:         } else {
 2358:             $output .= '<td class="LC_middle">'.$logincolors.&mt('Upload:').'<br />';
 2359:         }
 2360:     }
 2361:     return $output;
 2362: }
 2363: 
 2364: sub print_quotas {
 2365:     my ($dom,$settings,$rowtotal,$action) = @_;
 2366:     my $context;
 2367:     if ($action eq 'quotas') {
 2368:         $context = 'tools';
 2369:     } else {
 2370:         $context = $action;
 2371:     }
 2372:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 2373:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2374:     my $typecount = 0;
 2375:     my ($css_class,%titles);
 2376:     if ($context eq 'requestcourses') {
 2377:         @usertools = ('official','unofficial','community','textbook','placement','lti');
 2378:         @options =('norequest','approval','validate','autolimit');
 2379:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 2380:         %titles = &courserequest_titles();
 2381:     } elsif ($context eq 'requestauthor') {
 2382:         @usertools = ('author');
 2383:         @options = ('norequest','approval','automatic');
 2384:         %titles = &authorrequest_titles();
 2385:     } else {
 2386:         @usertools = ('aboutme','blog','webdav','portfolio');
 2387:         %titles = &tool_titles();
 2388:     }
 2389:     if (ref($types) eq 'ARRAY') {
 2390:         foreach my $type (@{$types}) {
 2391:             my ($currdefquota,$currauthorquota);
 2392:             unless (($context eq 'requestcourses') ||
 2393:                     ($context eq 'requestauthor')) {
 2394:                 if (ref($settings) eq 'HASH') {
 2395:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 2396:                         $currdefquota = $settings->{defaultquota}->{$type};
 2397:                     } else {
 2398:                         $currdefquota = $settings->{$type};
 2399:                     }
 2400:                     if (ref($settings->{authorquota}) eq 'HASH') {
 2401:                         $currauthorquota = $settings->{authorquota}->{$type};
 2402:                     }
 2403:                 }
 2404:             }
 2405:             if (defined($usertypes->{$type})) {
 2406:                 $typecount ++;
 2407:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 2408:                 $datatable .= '<tr'.$css_class.'>'.
 2409:                               '<td>'.$usertypes->{$type}.'</td>'.
 2410:                               '<td class="LC_left_item">';
 2411:                 if ($context eq 'requestcourses') {
 2412:                     $datatable .= '<table><tr>';
 2413:                 }
 2414:                 my %cell;  
 2415:                 foreach my $item (@usertools) {
 2416:                     if ($context eq 'requestcourses') {
 2417:                         my ($curroption,$currlimit);
 2418:                         if (ref($settings) eq 'HASH') {
 2419:                             if (ref($settings->{$item}) eq 'HASH') {
 2420:                                 $curroption = $settings->{$item}->{$type};
 2421:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 2422:                                     $currlimit = $1; 
 2423:                                 }
 2424:                             }
 2425:                         }
 2426:                         if (!$curroption) {
 2427:                             $curroption = 'norequest';
 2428:                         }
 2429:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 2430:                         foreach my $option (@options) {
 2431:                             my $val = $option;
 2432:                             if ($option eq 'norequest') {
 2433:                                 $val = 0;  
 2434:                             }
 2435:                             if ($option eq 'validate') {
 2436:                                 my $canvalidate = 0;
 2437:                                 if (ref($validations{$item}) eq 'HASH') { 
 2438:                                     if ($validations{$item}{$type}) {
 2439:                                         $canvalidate = 1;
 2440:                                     }
 2441:                                 }
 2442:                                 next if (!$canvalidate);
 2443:                             }
 2444:                             my $checked = '';
 2445:                             if ($option eq $curroption) {
 2446:                                 $checked = ' checked="checked"';
 2447:                             } elsif ($option eq 'autolimit') {
 2448:                                 if ($curroption =~ /^autolimit/) {
 2449:                                     $checked = ' checked="checked"';
 2450:                                 }                       
 2451:                             } 
 2452:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 2453:                                   '<input type="radio" name="crsreq_'.$item.
 2454:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 2455:                                   $titles{$option}.'</label>';
 2456:                             if ($option eq 'autolimit') {
 2457:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2458:                                                 $item.'_limit_'.$type.'" size="1" '.
 2459:                                                 'value="'.$currlimit.'" />';
 2460:                             }
 2461:                             $cell{$item} .= '</span> ';
 2462:                             if ($option eq 'autolimit') {
 2463:                                 $cell{$item} .= $titles{'unlimited'};
 2464:                             }
 2465:                         }
 2466:                     } elsif ($context eq 'requestauthor') {
 2467:                         my $curroption;
 2468:                         if (ref($settings) eq 'HASH') {
 2469:                             $curroption = $settings->{$type};
 2470:                         }
 2471:                         if (!$curroption) {
 2472:                             $curroption = 'norequest';
 2473:                         }
 2474:                         foreach my $option (@options) {
 2475:                             my $val = $option;
 2476:                             if ($option eq 'norequest') {
 2477:                                 $val = 0;
 2478:                             }
 2479:                             my $checked = '';
 2480:                             if ($option eq $curroption) {
 2481:                                 $checked = ' checked="checked"';
 2482:                             }
 2483:                             $datatable .= '<span class="LC_nobreak"><label>'.
 2484:                                   '<input type="radio" name="authorreq_'.$type.
 2485:                                   '" value="'.$val.'"'.$checked.' />'.
 2486:                                   $titles{$option}.'</label></span>&nbsp; ';
 2487:                         }
 2488:                     } else {
 2489:                         my $checked = 'checked="checked" ';
 2490:                         if (ref($settings) eq 'HASH') {
 2491:                             if (ref($settings->{$item}) eq 'HASH') {
 2492:                                 if ($settings->{$item}->{$type} == 0) {
 2493:                                     $checked = '';
 2494:                                 } elsif ($settings->{$item}->{$type} == 1) {
 2495:                                     $checked =  'checked="checked" ';
 2496:                                 }
 2497:                             }
 2498:                         }
 2499:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2500:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 2501:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 2502:                                       '</label></span>&nbsp; ';
 2503:                     }
 2504:                 }
 2505:                 if ($context eq 'requestcourses') {
 2506:                     $datatable .= '</tr><tr>';
 2507:                     foreach my $item (@usertools) {
 2508:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 2509:                     }
 2510:                     $datatable .= '</tr></table>';
 2511:                 }
 2512:                 $datatable .= '</td>';
 2513:                 unless (($context eq 'requestcourses') ||
 2514:                         ($context eq 'requestauthor')) {
 2515:                     $datatable .= 
 2516:                               '<td class="LC_right_item">'.
 2517:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2518:                               '<input type="text" name="quota_'.$type.
 2519:                               '" value="'.$currdefquota.
 2520:                               '" size="5" /></span>'.('&nbsp;' x 2).
 2521:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2522:                               '<input type="text" name="authorquota_'.$type.
 2523:                               '" value="'.$currauthorquota.
 2524:                               '" size="5" /></span></td>';
 2525:                 }
 2526:                 $datatable .= '</tr>';
 2527:             }
 2528:         }
 2529:     }
 2530:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2531:         $defaultquota = '20';
 2532:         $authorquota = '500';
 2533:         if (ref($settings) eq 'HASH') {
 2534:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 2535:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 2536:             } elsif (defined($settings->{'default'})) {
 2537:                 $defaultquota = $settings->{'default'};
 2538:             }
 2539:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 2540:                 $authorquota = $settings->{'authorquota'}->{'default'};
 2541:             }
 2542:         }
 2543:     }
 2544:     $typecount ++;
 2545:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2546:     $datatable .= '<tr'.$css_class.'>'.
 2547:                   '<td>'.$othertitle.'</td>'.
 2548:                   '<td class="LC_left_item">';
 2549:     if ($context eq 'requestcourses') {
 2550:         $datatable .= '<table><tr>';
 2551:     }
 2552:     my %defcell;
 2553:     foreach my $item (@usertools) {
 2554:         if ($context eq 'requestcourses') {
 2555:             my ($curroption,$currlimit);
 2556:             if (ref($settings) eq 'HASH') {
 2557:                 if (ref($settings->{$item}) eq 'HASH') {
 2558:                     $curroption = $settings->{$item}->{'default'};
 2559:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2560:                         $currlimit = $1;
 2561:                     }
 2562:                 }
 2563:             }
 2564:             if (!$curroption) {
 2565:                 $curroption = 'norequest';
 2566:             }
 2567:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2568:             foreach my $option (@options) {
 2569:                 my $val = $option;
 2570:                 if ($option eq 'norequest') {
 2571:                     $val = 0;
 2572:                 }
 2573:                 if ($option eq 'validate') {
 2574:                     my $canvalidate = 0;
 2575:                     if (ref($validations{$item}) eq 'HASH') {
 2576:                         if ($validations{$item}{'default'}) {
 2577:                             $canvalidate = 1;
 2578:                         }
 2579:                     }
 2580:                     next if (!$canvalidate);
 2581:                 }
 2582:                 my $checked = '';
 2583:                 if ($option eq $curroption) {
 2584:                     $checked = ' checked="checked"';
 2585:                 } elsif ($option eq 'autolimit') {
 2586:                     if ($curroption =~ /^autolimit/) {
 2587:                         $checked = ' checked="checked"';
 2588:                     }
 2589:                 }
 2590:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2591:                                   '<input type="radio" name="crsreq_'.$item.
 2592:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2593:                                   $titles{$option}.'</label>';
 2594:                 if ($option eq 'autolimit') {
 2595:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2596:                                        $item.'_limit_default" size="1" '.
 2597:                                        'value="'.$currlimit.'" />';
 2598:                 }
 2599:                 $defcell{$item} .= '</span> ';
 2600:                 if ($option eq 'autolimit') {
 2601:                     $defcell{$item} .= $titles{'unlimited'};
 2602:                 }
 2603:             }
 2604:         } elsif ($context eq 'requestauthor') {
 2605:             my $curroption;
 2606:             if (ref($settings) eq 'HASH') {
 2607:                 $curroption = $settings->{'default'};
 2608:             }
 2609:             if (!$curroption) {
 2610:                 $curroption = 'norequest';
 2611:             }
 2612:             foreach my $option (@options) {
 2613:                 my $val = $option;
 2614:                 if ($option eq 'norequest') {
 2615:                     $val = 0;
 2616:                 }
 2617:                 my $checked = '';
 2618:                 if ($option eq $curroption) {
 2619:                     $checked = ' checked="checked"';
 2620:                 }
 2621:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2622:                               '<input type="radio" name="authorreq_default"'.
 2623:                               ' value="'.$val.'"'.$checked.' />'.
 2624:                               $titles{$option}.'</label></span>&nbsp; ';
 2625:             }
 2626:         } else {
 2627:             my $checked = 'checked="checked" ';
 2628:             if (ref($settings) eq 'HASH') {
 2629:                 if (ref($settings->{$item}) eq 'HASH') {
 2630:                     if ($settings->{$item}->{'default'} == 0) {
 2631:                         $checked = '';
 2632:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2633:                         $checked = 'checked="checked" ';
 2634:                     }
 2635:                 }
 2636:             }
 2637:             $datatable .= '<span class="LC_nobreak"><label>'.
 2638:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2639:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2640:                           '</label></span>&nbsp; ';
 2641:         }
 2642:     }
 2643:     if ($context eq 'requestcourses') {
 2644:         $datatable .= '</tr><tr>';
 2645:         foreach my $item (@usertools) {
 2646:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2647:         }
 2648:         $datatable .= '</tr></table>';
 2649:     }
 2650:     $datatable .= '</td>';
 2651:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2652:         $datatable .= '<td class="LC_right_item">'.
 2653:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2654:                       '<input type="text" name="defaultquota" value="'.
 2655:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2656:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2657:                       '<input type="text" name="authorquota" value="'.
 2658:                       $authorquota.'" size="5" /></span></td>';
 2659:     }
 2660:     $datatable .= '</tr>';
 2661:     $typecount ++;
 2662:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2663:     $datatable .= '<tr'.$css_class.'>'.
 2664:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2665:     if ($context eq 'requestcourses') {
 2666:         $datatable .= &mt('(overrides affiliation, if set)').
 2667:                       '</td>'.
 2668:                       '<td class="LC_left_item">'.
 2669:                       '<table><tr>';
 2670:     } else {
 2671:         $datatable .= &mt('(overrides affiliation, if checked)').
 2672:                       '</td>'.
 2673:                       '<td class="LC_left_item" colspan="2">'.
 2674:                       '<br />';
 2675:     }
 2676:     my %advcell;
 2677:     foreach my $item (@usertools) {
 2678:         if ($context eq 'requestcourses') {
 2679:             my ($curroption,$currlimit);
 2680:             if (ref($settings) eq 'HASH') {
 2681:                 if (ref($settings->{$item}) eq 'HASH') {
 2682:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2683:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2684:                         $currlimit = $1;
 2685:                     }
 2686:                 }
 2687:             }
 2688:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2689:             my $checked = '';
 2690:             if ($curroption eq '') {
 2691:                 $checked = ' checked="checked"';
 2692:             }
 2693:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2694:                                '<input type="radio" name="crsreq_'.$item.
 2695:                                '__LC_adv" value=""'.$checked.' />'.
 2696:                                &mt('No override set').'</label></span>&nbsp; ';
 2697:             foreach my $option (@options) {
 2698:                 my $val = $option;
 2699:                 if ($option eq 'norequest') {
 2700:                     $val = 0;
 2701:                 }
 2702:                 if ($option eq 'validate') {
 2703:                     my $canvalidate = 0;
 2704:                     if (ref($validations{$item}) eq 'HASH') {
 2705:                         if ($validations{$item}{'_LC_adv'}) {
 2706:                             $canvalidate = 1;
 2707:                         }
 2708:                     }
 2709:                     next if (!$canvalidate);
 2710:                 }
 2711:                 my $checked = '';
 2712:                 if ($val eq $curroption) {
 2713:                     $checked = ' checked="checked"';
 2714:                 } elsif ($option eq 'autolimit') {
 2715:                     if ($curroption =~ /^autolimit/) {
 2716:                         $checked = ' checked="checked"';
 2717:                     }
 2718:                 }
 2719:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2720:                                   '<input type="radio" name="crsreq_'.$item.
 2721:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2722:                                   $titles{$option}.'</label>';
 2723:                 if ($option eq 'autolimit') {
 2724:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2725:                                        $item.'_limit__LC_adv" size="1" '.
 2726:                                        'value="'.$currlimit.'" />';
 2727:                 }
 2728:                 $advcell{$item} .= '</span> ';
 2729:                 if ($option eq 'autolimit') {
 2730:                     $advcell{$item} .= $titles{'unlimited'};
 2731:                 }
 2732:             }
 2733:         } elsif ($context eq 'requestauthor') {
 2734:             my $curroption;
 2735:             if (ref($settings) eq 'HASH') {
 2736:                 $curroption = $settings->{'_LC_adv'};
 2737:             }
 2738:             my $checked = '';
 2739:             if ($curroption eq '') {
 2740:                 $checked = ' checked="checked"';
 2741:             }
 2742:             $datatable .= '<span class="LC_nobreak"><label>'.
 2743:                           '<input type="radio" name="authorreq__LC_adv"'.
 2744:                           ' value=""'.$checked.' />'.
 2745:                           &mt('No override set').'</label></span>&nbsp; ';
 2746:             foreach my $option (@options) {
 2747:                 my $val = $option;
 2748:                 if ($option eq 'norequest') {
 2749:                     $val = 0;
 2750:                 }
 2751:                 my $checked = '';
 2752:                 if ($val eq $curroption) {
 2753:                     $checked = ' checked="checked"';
 2754:                 }
 2755:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2756:                               '<input type="radio" name="authorreq__LC_adv"'.
 2757:                               ' value="'.$val.'"'.$checked.' />'.
 2758:                               $titles{$option}.'</label></span>&nbsp; ';
 2759:             }
 2760:         } else {
 2761:             my $checked = 'checked="checked" ';
 2762:             if (ref($settings) eq 'HASH') {
 2763:                 if (ref($settings->{$item}) eq 'HASH') {
 2764:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2765:                         $checked = '';
 2766:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2767:                         $checked = 'checked="checked" ';
 2768:                     }
 2769:                 }
 2770:             }
 2771:             $datatable .= '<span class="LC_nobreak"><label>'.
 2772:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2773:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2774:                           '</label></span>&nbsp; ';
 2775:         }
 2776:     }
 2777:     if ($context eq 'requestcourses') {
 2778:         $datatable .= '</tr><tr>';
 2779:         foreach my $item (@usertools) {
 2780:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2781:         }
 2782:         $datatable .= '</tr></table>';
 2783:     }
 2784:     $datatable .= '</td></tr>';
 2785:     $$rowtotal += $typecount;
 2786:     return $datatable;
 2787: }
 2788: 
 2789: sub print_requestmail {
 2790:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2791:     my ($now,$datatable,%currapp);
 2792:     $now = time;
 2793:     if (ref($settings) eq 'HASH') {
 2794:         if (ref($settings->{'notify'}) eq 'HASH') {
 2795:             if ($settings->{'notify'}{'approval'} ne '') {
 2796:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2797:             }
 2798:         }
 2799:     }
 2800:     my $numinrow = 2;
 2801:     my $css_class;
 2802:     if ($$rowtotal%2) {
 2803:         $css_class = 'LC_odd_row';
 2804:     }
 2805:     if ($customcss) {
 2806:         $css_class .= " $customcss";
 2807:     }
 2808:     $css_class =~ s/^\s+//;
 2809:     if ($css_class) {
 2810:         $css_class = ' class="'.$css_class.'"';
 2811:     }
 2812:     if ($rowstyle) {
 2813:         $css_class .= ' style="'.$rowstyle.'"';
 2814:     }
 2815:     my $text;
 2816:     if ($action eq 'requestcourses') {
 2817:         $text = &mt('Receive notification of course requests requiring approval');
 2818:     } elsif ($action eq 'requestauthor') {
 2819:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2820:     } else {
 2821:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2822:     }
 2823:     $datatable = '<tr'.$css_class.'>'.
 2824:                  ' <td>'.$text.'</td>'.
 2825:                  ' <td class="LC_left_item">';
 2826:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2827:                                                  $action.'notifyapproval',%currapp);
 2828:     if ($numdc > 0) {
 2829:         $datatable .= $table;
 2830:     } else {
 2831:         $datatable .= &mt('There are no active Domain Coordinators');
 2832:     }
 2833:     $datatable .='</td></tr>';
 2834:     return $datatable;
 2835: }
 2836: 
 2837: sub print_studentcode {
 2838:     my ($settings,$rowtotal) = @_;
 2839:     my $rownum = 0; 
 2840:     my ($output,%current);
 2841:     my @crstypes = ('official','unofficial','community','textbook','placement','lti');
 2842:     if (ref($settings) eq 'HASH') {
 2843:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2844:             foreach my $type (@crstypes) {
 2845:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2846:             }
 2847:         }
 2848:     }
 2849:     $output .= '<tr>'.
 2850:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2851:                '<td class="LC_left_item">';
 2852:     foreach my $type (@crstypes) {
 2853:         my $check = ' ';
 2854:         if ($current{$type}) {
 2855:             $check = ' checked="checked" ';
 2856:         }
 2857:         $output .= '<span class="LC_nobreak"><label>'.
 2858:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2859:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2860:     }
 2861:     $output .= '</td></tr>';
 2862:     $$rowtotal ++;
 2863:     return $output;
 2864: }
 2865: 
 2866: sub print_textbookcourses {
 2867:     my ($dom,$type,$settings,$rowtotal) = @_;
 2868:     my $rownum = 0;
 2869:     my $css_class;
 2870:     my $itemcount = 1;
 2871:     my $maxnum = 0;
 2872:     my $bookshash;
 2873:     if (ref($settings) eq 'HASH') {
 2874:         $bookshash = $settings->{$type};
 2875:     }
 2876:     my %ordered;
 2877:     if (ref($bookshash) eq 'HASH') {
 2878:         foreach my $item (keys(%{$bookshash})) {
 2879:             if (ref($bookshash->{$item}) eq 'HASH') {
 2880:                 my $num = $bookshash->{$item}{'order'};
 2881:                 $ordered{$num} = $item;
 2882:             }
 2883:         }
 2884:     }
 2885:     my $confname = $dom.'-domainconfig';
 2886:     my $switchserver = &check_switchserver($dom,$confname);
 2887:     my $maxnum = scalar(keys(%ordered));
 2888:     my $datatable;
 2889:     if (keys(%ordered)) {
 2890:         my @items = sort { $a <=> $b } keys(%ordered);
 2891:         for (my $i=0; $i<@items; $i++) {
 2892:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2893:             my $key = $ordered{$items[$i]};
 2894:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2895:             my $coursetitle = $coursehash{'description'};
 2896:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2897:             if (ref($bookshash->{$key}) eq 'HASH') {
 2898:                 $subject = $bookshash->{$key}->{'subject'};
 2899:                 $title = $bookshash->{$key}->{'title'};
 2900:                 if ($type eq 'textbooks') {
 2901:                     $publisher = $bookshash->{$key}->{'publisher'};
 2902:                     $author = $bookshash->{$key}->{'author'};
 2903:                     $image = $bookshash->{$key}->{'image'};
 2904:                     if ($image ne '') {
 2905:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2906:                         my $imagethumb = "$path/tn-".$imagefile;
 2907:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2908:                     }
 2909:                 }
 2910:             }
 2911:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2912:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2913:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2914:             for (my $k=0; $k<=$maxnum; $k++) {
 2915:                 my $vpos = $k+1;
 2916:                 my $selstr;
 2917:                 if ($k == $i) {
 2918:                     $selstr = ' selected="selected" ';
 2919:                 }
 2920:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2921:             }
 2922:             $datatable .= '</select>'.('&nbsp;'x2).
 2923:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2924:                 &mt('Delete?').'</label></span></td>'.
 2925:                 '<td colspan="2">'.
 2926:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2927:                 ('&nbsp;'x2).
 2928:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2929:             if ($type eq 'textbooks') {
 2930:                 $datatable .= ('&nbsp;'x2).
 2931:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2932:                               ('&nbsp;'x2).
 2933:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2934:                               ('&nbsp;'x2).
 2935:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2936:                 if ($image) {
 2937:                     $datatable .= $imgsrc.
 2938:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2939:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2940:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2941:                 }
 2942:                 if ($switchserver) {
 2943:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2944:                 } else {
 2945:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2946:                 }
 2947:             }
 2948:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2949:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2950:                           $coursetitle.'</span></td></tr>'."\n";
 2951:             $itemcount ++;
 2952:         }
 2953:     }
 2954:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2955:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2956:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2957:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2958:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2959:     for (my $k=0; $k<$maxnum+1; $k++) {
 2960:         my $vpos = $k+1;
 2961:         my $selstr;
 2962:         if ($k == $maxnum) {
 2963:             $selstr = ' selected="selected" ';
 2964:         }
 2965:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2966:     }
 2967:     $datatable .= '</select>&nbsp;'."\n".
 2968:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2969:                   '<td colspan="2">'.
 2970:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2971:                   ('&nbsp;'x2).
 2972:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2973:                   ('&nbsp;'x2);
 2974:     if ($type eq 'textbooks') {
 2975:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2976:                       ('&nbsp;'x2).
 2977:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2978:                       ('&nbsp;'x2).
 2979:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2980:         if ($switchserver) {
 2981:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2982:         } else {
 2983:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2984:         }
 2985:         $datatable .= '</span>'."\n";
 2986:     }
 2987:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2988:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2989:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2990:                   &Apache::loncommon::selectcourse_link
 2991:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2992:                   '</span></td>'."\n".
 2993:                   '</tr>'."\n";
 2994:     $itemcount ++;
 2995:     return $datatable;
 2996: }
 2997: 
 2998: sub textbookcourses_javascript {
 2999:     my ($settings) = @_;
 3000:     return unless(ref($settings) eq 'HASH');
 3001:     my (%ordered,%total,%jstext);
 3002:     foreach my $type ('textbooks','templates') {
 3003:         $total{$type} = 0;
 3004:         if (ref($settings->{$type}) eq 'HASH') {
 3005:             foreach my $item (keys(%{$settings->{$type}})) {
 3006:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 3007:                     my $num = $settings->{$type}->{$item}{'order'};
 3008:                     $ordered{$type}{$num} = $item;
 3009:                 }
 3010:             }
 3011:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 3012:         }
 3013:         my @jsarray = ();
 3014:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 3015:             push(@jsarray,$ordered{$type}{$item});
 3016:         }
 3017:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 3018:     }
 3019:     return <<"ENDSCRIPT";
 3020: <script type="text/javascript">
 3021: // <![CDATA[
 3022: function reorderBooks(form,item,caller) {
 3023:     var changedVal;
 3024: $jstext{'textbooks'};
 3025: $jstext{'templates'};
 3026:     var newpos;
 3027:     var maxh;
 3028:     if (caller == 'textbooks') {  
 3029:         newpos = 'textbooks_addbook_pos';
 3030:         maxh = 1 + $total{'textbooks'};
 3031:     } else {
 3032:         newpos = 'templates_addbook_pos';
 3033:         maxh = 1 + $total{'templates'};
 3034:     }
 3035:     var current = new Array;
 3036:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3037:     if (item == newpos) {
 3038:         changedVal = newitemVal;
 3039:     } else {
 3040:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3041:         current[newitemVal] = newpos;
 3042:     }
 3043:     if (caller == 'textbooks') {
 3044:         for (var i=0; i<textbooks.length; i++) {
 3045:             var elementName = 'textbooks_'+textbooks[i];
 3046:             if (elementName != item) {
 3047:                 if (form.elements[elementName]) {
 3048:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3049:                     current[currVal] = elementName;
 3050:                 }
 3051:             }
 3052:         }
 3053:     }
 3054:     if (caller == 'templates') {
 3055:         for (var i=0; i<templates.length; i++) {
 3056:             var elementName = 'templates_'+templates[i];
 3057:             if (elementName != item) {
 3058:                 if (form.elements[elementName]) {
 3059:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3060:                     current[currVal] = elementName;
 3061:                 }
 3062:             }
 3063:         }
 3064:     }
 3065:     var oldVal;
 3066:     for (var j=0; j<maxh; j++) {
 3067:         if (current[j] == undefined) {
 3068:             oldVal = j;
 3069:         }
 3070:     }
 3071:     if (oldVal < changedVal) {
 3072:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3073:            var elementName = current[k];
 3074:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3075:         }
 3076:     } else {
 3077:         for (var k=changedVal; k<oldVal; k++) {
 3078:             var elementName = current[k];
 3079:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3080:         }
 3081:     }
 3082:     return;
 3083: }
 3084: 
 3085: // ]]>
 3086: </script>
 3087: 
 3088: ENDSCRIPT
 3089: }
 3090: 
 3091: sub ltitools_javascript {
 3092:     my ($settings) = @_;
 3093:     my $togglejs = &ltitools_toggle_js();
 3094:     unless (ref($settings) eq 'HASH') {
 3095:         return $togglejs;
 3096:     }
 3097:     my (%ordered,$total,%jstext);
 3098:     $total = 0;
 3099:     foreach my $item (keys(%{$settings})) {
 3100:         if (ref($settings->{$item}) eq 'HASH') {
 3101:             my $num = $settings->{$item}{'order'};
 3102:             $ordered{$num} = $item;
 3103:         }
 3104:     }
 3105:     $total = scalar(keys(%{$settings}));
 3106:     my @jsarray = ();
 3107:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3108:         push(@jsarray,$ordered{$item});
 3109:     }
 3110:     my $jstext = '    var ltitools = Array('."'".join("','",@jsarray)."'".');'."\n";
 3111:     return <<"ENDSCRIPT";
 3112: <script type="text/javascript">
 3113: // <![CDATA[
 3114: function reorderLTITools(form,item) {
 3115:     var changedVal;
 3116: $jstext
 3117:     var newpos = 'ltitools_add_pos';
 3118:     var maxh = 1 + $total;
 3119:     var current = new Array;
 3120:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3121:     if (item == newpos) {
 3122:         changedVal = newitemVal;
 3123:     } else {
 3124:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3125:         current[newitemVal] = newpos;
 3126:     }
 3127:     for (var i=0; i<ltitools.length; i++) {
 3128:         var elementName = 'ltitools_'+ltitools[i];
 3129:         if (elementName != item) {
 3130:             if (form.elements[elementName]) {
 3131:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3132:                 current[currVal] = elementName;
 3133:             }
 3134:         }
 3135:     }
 3136:     var oldVal;
 3137:     for (var j=0; j<maxh; j++) {
 3138:         if (current[j] == undefined) {
 3139:             oldVal = j;
 3140:         }
 3141:     }
 3142:     if (oldVal < changedVal) {
 3143:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3144:            var elementName = current[k];
 3145:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3146:         }
 3147:     } else {
 3148:         for (var k=changedVal; k<oldVal; k++) {
 3149:             var elementName = current[k];
 3150:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3151:         }
 3152:     }
 3153:     return;
 3154: }
 3155: 
 3156: // ]]>
 3157: </script>
 3158: 
 3159: $togglejs
 3160: 
 3161: ENDSCRIPT
 3162: }
 3163: 
 3164: sub ltitools_toggle_js {
 3165:     return <<"ENDSCRIPT";
 3166: <script type="text/javascript">
 3167: // <![CDATA[
 3168: 
 3169: function toggleLTITools(form,setting,item) {
 3170:     var radioname = '';
 3171:     var divid = '';
 3172:     if ((setting == 'passback') || (setting == 'roster')) {
 3173:         radioname = 'ltitools_'+setting+'_'+item;
 3174:         divid = 'ltitools_'+setting+'time_'+item;
 3175:         var num = form.elements[radioname].length;
 3176:         if (num) {
 3177:             var setvis = '';
 3178:             for (var i=0; i<num; i++) {
 3179:                 if (form.elements[radioname][i].checked) {
 3180:                     if (form.elements[radioname][i].value == '1') {
 3181:                         if (document.getElementById(divid)) {
 3182:                             document.getElementById(divid).style.display = 'inline-block';
 3183:                         }
 3184:                         setvis = 1;
 3185:                     }
 3186:                     break;
 3187:                 }
 3188:             }
 3189:         }
 3190:         if (!setvis) {
 3191:             if (document.getElementById(divid)) {
 3192:                 document.getElementById(divid).style.display = 'none';
 3193:             }
 3194:         }
 3195:     }
 3196:     if (setting == 'user') {
 3197:         divid = 'ltitools_'+setting+'_div_'+item;
 3198:         var checkid = 'ltitools_'+setting+'_field_'+item;
 3199:         if (document.getElementById(divid)) {
 3200:             if (document.getElementById(checkid)) {
 3201:                 if (document.getElementById(checkid).checked) {
 3202:                     document.getElementById(divid).style.display = 'inline-block';
 3203:                 } else {
 3204:                     document.getElementById(divid).style.display = 'none';
 3205:                 }
 3206:             }
 3207:         }
 3208:     }
 3209:     return;
 3210: }
 3211: // ]]>
 3212: </script>
 3213: 
 3214: ENDSCRIPT
 3215: }
 3216: 
 3217: sub wafproxy_javascript {
 3218:     my ($dom) = @_;
 3219:     return <<"ENDSCRIPT";
 3220: <script type="text/javascript">
 3221: // <![CDATA[
 3222: function updateWAF() {
 3223:     if (document.getElementById('wafproxy_remoteip')) {
 3224:         var wafremote = 0;
 3225:         if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value == 'h') {
 3226:             wafremote = 1;
 3227:         }
 3228:         var fields = new Array('header','trust');
 3229:         for (var i=0; i<fields.length; i++) {
 3230:             if (document.getElementById('wafproxy_'+fields[i])) {
 3231:                 if (wafremote == 1) {
 3232:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'table-row';
 3233:                 }
 3234:                 else {
 3235:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'none';
 3236:                 }
 3237:             }
 3238:         }
 3239:         if (document.getElementById('wafproxyranges_$dom')) {
 3240:             if (wafremote == 1) {
 3241:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3242:             } else {
 3243:                 for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3244:                     if (document.display.wafproxy_vpnaccess[i].checked) {
 3245:                         if (document.display.wafproxy_vpnaccess[i].value == 0) {
 3246:                             document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3247:                         }
 3248:                     }
 3249:                 }
 3250:             }
 3251:         }
 3252:     }
 3253:     return;
 3254: }
 3255: 
 3256: function checkWAF() {
 3257:     if (document.getElementById('wafproxy_remoteip')) {
 3258:         var wafvpn = 0;
 3259:         for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3260:             if (document.display.wafproxy_vpnaccess[i].checked) {
 3261:                 if (document.display.wafproxy_vpnaccess[i].value == 1) {
 3262:                     wafvpn = 1;
 3263:                 }
 3264:                 break;
 3265:             }
 3266:         }
 3267:         var vpn = new Array('vpnint','vpnext');
 3268:         for (var i=0; i<vpn.length; i++) {
 3269:             if (document.getElementById('wafproxy_show_'+vpn[i])) {
 3270:                 if (wafvpn == 1) {
 3271:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'table-row';
 3272:                 }
 3273:                 else {
 3274:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'none';
 3275:                 }
 3276:             }
 3277:         }
 3278:         if (document.getElementById('wafproxyranges_$dom')) {
 3279:             if (wafvpn == 1) {
 3280:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3281:             }
 3282:             else if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value != 'h') {
 3283:                 document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3284:             }
 3285:         }
 3286:     }
 3287:     return;
 3288: }
 3289: 
 3290: function toggleWAF() {
 3291:     if (document.getElementById('wafproxy_table')) {
 3292:         var wafproxy = 0;
 3293:         for (var i=0; i<document.display.wafproxy_${dom}.length; i++) {
 3294:              if (document.display.wafproxy_${dom}[i].checked) {
 3295:                  if (document.display.wafproxy_${dom}[i].value == 1) {
 3296:                      wafproxy = 1;
 3297:                      break;
 3298:                 }
 3299:             }
 3300:         }
 3301:         if (wafproxy == 1) {
 3302:             document.getElementById('wafproxy_table').style.display='inline';
 3303:         }
 3304:         else {
 3305:            document.getElementById('wafproxy_table').style.display='none';
 3306:         }
 3307:         if (document.getElementById('wafproxyrow_${dom}')) {
 3308:             if (wafproxy == 1) {
 3309:                 document.getElementById('wafproxyrow_${dom}').style.display = 'table-row';
 3310:             }
 3311:             else {
 3312:                 document.getElementById('wafproxyrow_${dom}').style.display = 'none';
 3313:             }
 3314:         }
 3315:         if (document.getElementById('nowafproxyrow_$dom')) {
 3316:             if (wafproxy == 1) {
 3317:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'none';
 3318:             }
 3319:             else {
 3320:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'table-row';
 3321:             }
 3322:         }
 3323:     }
 3324:     return;
 3325: }
 3326: // ]]>
 3327: </script>
 3328: 
 3329: ENDSCRIPT
 3330: }
 3331: 
 3332: sub proctoring_javascript {
 3333:     my ($settings) = @_;
 3334:     my (%ordered,$total,%jstext);
 3335:     $total = 0;
 3336:     if (ref($settings) eq 'HASH') {
 3337:         foreach my $item (keys(%{$settings})) {
 3338:             if (ref($settings->{$item}) eq 'HASH') {
 3339:                 my $num = $settings->{$item}{'order'};
 3340:                 $ordered{$num} = $item;
 3341:             }
 3342:         }
 3343:         $total = scalar(keys(%{$settings}));
 3344:     } else {
 3345:         %ordered = (
 3346:                        0 => 'proctorio',
 3347:                        1 => 'examity',
 3348:                    );
 3349:         $total = 2; 
 3350:     }
 3351:     my @jsarray = ();
 3352:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3353:         push(@jsarray,$ordered{$item});
 3354:     }
 3355:     my $jstext = '    var proctors = Array('."'".join("','",@jsarray)."'".');'."\n";
 3356:     return <<"ENDSCRIPT";
 3357: <script type="text/javascript">
 3358: // <![CDATA[
 3359: function reorderProctoring(form,item) {
 3360:     var changedVal;
 3361: $jstext
 3362:     var maxh = $total;
 3363:     var current = new Array;
 3364:     var changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3365:     for (var i=0; i<proctors.length; i++) {
 3366:         var elementName = 'proctoring_pos_'+proctors[i];
 3367:         if (elementName != item) {
 3368:             if (form.elements[elementName]) {
 3369:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3370:                 current[currVal] = elementName;
 3371:             }
 3372:         }
 3373:     }
 3374:     var oldVal;
 3375:     for (var j=0; j<maxh; j++) {
 3376:         if (current[j] == undefined) {
 3377:             oldVal = j;
 3378:         }
 3379:     }
 3380:     if (oldVal < changedVal) {
 3381:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3382:            var elementName = current[k];
 3383:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3384:         }
 3385:     } else {
 3386:         for (var k=changedVal; k<oldVal; k++) {
 3387:             var elementName = current[k];
 3388:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3389:         }
 3390:     }
 3391:     return;
 3392: }
 3393: 
 3394: function toggleProctoring(form,item) {
 3395:     var fieldsets = document.getElementsByClassName('proctoring_'+item);
 3396:     if (fieldsets.length) {
 3397:         var radioname = 'proctoring_available_'+item;
 3398:         var num = form.elements[radioname].length;
 3399:         if (num) {
 3400:             var setvis = '';
 3401:             for (var i=0; i<num; i++) {
 3402:                 if (form.elements[radioname][i].checked) {
 3403:                     if (form.elements[radioname][i].value == '1') {
 3404:                        setvis = 1;
 3405:                        break;
 3406:                     }
 3407:                 }
 3408:             }
 3409:             for (var j=0; j<fieldsets.length; j++) {
 3410:                 if (setvis) {
 3411:                     fieldsets[j].style.display = 'block';
 3412:                 } else {
 3413:                     fieldsets[j].style.display = 'none';
 3414:                 }
 3415:             }
 3416:         }
 3417:     }
 3418:     return;
 3419: }
 3420: 
 3421: // ]]>
 3422: </script>
 3423: 
 3424: ENDSCRIPT
 3425: }
 3426: 
 3427: 
 3428: sub lti_javascript {
 3429:     my ($dom,$settings) = @_;
 3430:     my $togglejs = &lti_toggle_js($dom);
 3431:     unless (ref($settings) eq 'HASH') {
 3432:         return $togglejs;
 3433:     }
 3434:     my (%ordered,$total,%jstext);
 3435:     $total = scalar(keys(%{$settings}));
 3436:     foreach my $item (keys(%{$settings})) {
 3437:         if (ref($settings->{$item}) eq 'HASH') {
 3438:             my $num = $settings->{$item}{'order'};
 3439:             if ($num eq '') {
 3440:                 $num = $total - 1;
 3441:             }
 3442:             $ordered{$num} = $item;
 3443:         }
 3444:     }
 3445:     my @jsarray = ();
 3446:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3447:         push(@jsarray,$ordered{$item});
 3448:     }
 3449:     my $jstext = '    var lti = Array('."'".join("','",@jsarray)."'".');'."\n";
 3450:     my $linkprot_js = &Apache::courseprefs::linkprot_javascript();
 3451:     return <<"ENDSCRIPT";
 3452: <script type="text/javascript">
 3453: // <![CDATA[
 3454: function reorderLTI(form,item) {
 3455:     var changedVal;
 3456: $jstext
 3457:     var newpos = 'lti_pos_add';
 3458:     var maxh = 1 + $total;
 3459:     var current = new Array;
 3460:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3461:     if (item == newpos) {
 3462:         changedVal = newitemVal;
 3463:     } else {
 3464:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3465:         current[newitemVal] = newpos;
 3466:     }
 3467:     for (var i=0; i<lti.length; i++) {
 3468:         var elementName = 'lti_pos_'+lti[i];
 3469:         if (elementName != item) {
 3470:             if (form.elements[elementName]) {
 3471:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3472:                 current[currVal] = elementName;
 3473:             }
 3474:         }
 3475:     }
 3476:     var oldVal;
 3477:     for (var j=0; j<maxh; j++) {
 3478:         if (current[j] == undefined) {
 3479:             oldVal = j;
 3480:         }
 3481:     }
 3482:     if (oldVal < changedVal) {
 3483:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3484:            var elementName = current[k];
 3485:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3486:         }
 3487:     } else {
 3488:         for (var k=changedVal; k<oldVal; k++) {
 3489:             var elementName = current[k];
 3490:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3491:         }
 3492:     }
 3493:     return;
 3494: }
 3495: 
 3496: $linkprot_js
 3497: 
 3498: // ]]>
 3499: </script>
 3500: 
 3501: $togglejs
 3502: 
 3503: ENDSCRIPT
 3504: }
 3505: 
 3506: sub lti_toggle_js {
 3507:     my ($dom) = @_;
 3508:     my %lcauthparmtext = &Apache::lonlocal::texthash (
 3509:                             localauth => 'Local auth argument',
 3510:                             krb       => 'Kerberos domain',
 3511:                          );
 3512:     my $crsincalert = &mt('"User\'s identity sent" needs to be set to "Yes" first,[_1] before setting "Course\'s identity sent" to "Yes"',"\n");
 3513:     &js_escape(\$crsincalert);
 3514:     my %servers = &Apache::lonnet::get_servers($dom,'library');
 3515:     my $primary = &Apache::lonnet::domain($dom,'primary');
 3516:     my $course_servers = "'".join("','",keys(%servers))."'";
 3517: 
 3518:     return <<"ENDSCRIPT";
 3519: <script type="text/javascript">
 3520: // <![CDATA[
 3521: 
 3522: function toggleLTI(form,setting,item) {
 3523:     if ((setting == 'requser') || (setting == 'crsinc')) {
 3524:         var usrfieldsets = document.getElementsByClassName('ltioption_usr_'+item);
 3525:         var setvis = '';
 3526:         var radioname = 'lti_requser_'+item;
 3527:         var num = form.elements[radioname].length;
 3528:         if (num) {
 3529:             for (var i=0; i<num; i++) {
 3530:                 if (form.elements[radioname][i].checked) {
 3531:                     if (form.elements[radioname][i].value == '1') {
 3532:                         setvis = 1;
 3533:                         break;
 3534:                     }
 3535:                 }
 3536:             }
 3537:         }
 3538:         if (usrfieldsets.length) {
 3539:             for (var j=0; j<usrfieldsets.length; j++) {
 3540:                 if (setvis) {
 3541:                     usrfieldsets[j].style.display = 'block';
 3542:                 } else {
 3543:                     usrfieldsets[j].style.display = 'none';
 3544:                 }
 3545:             }
 3546:         }
 3547:         var crsfieldsets = document.getElementsByClassName('ltioption_crs_'+item);
 3548:         if (crsfieldsets.length) {
 3549:             radioname = 'lti_crsinc_'+item;
 3550:             var num = form.elements[radioname].length;
 3551:             if (num) {
 3552:                 var crsvis = '';
 3553:                 for (var i=0; i<num; i++) {
 3554:                     if (form.elements[radioname][i].checked) {
 3555:                         if (form.elements[radioname][i].value == '1') {
 3556:                             if (setvis == '') {
 3557:                                 if (setting == 'crsinc'){
 3558:                                     alert("$crsincalert");
 3559:                                     form.elements[radioname][0].checked = true;
 3560:                                 }
 3561:                             } else {
 3562:                                 crsvis = 1;
 3563:                             }
 3564:                             break;
 3565:                         }
 3566:                     }
 3567:                 }
 3568:                 setvis = crsvis;
 3569:             }
 3570:             for (var j=0; j<crsfieldsets.length; j++) {
 3571:                 if (setvis) {
 3572:                     crsfieldsets[j].style.display = 'block';
 3573:                 } else {
 3574:                     crsfieldsets[j].style.display = 'none';
 3575:                 }
 3576:             }
 3577:         }
 3578:     } else if ((setting == 'user') || (setting == 'crs') || (setting == 'passback') || (setting == 'callback')) {
 3579:         var radioname = '';
 3580:         var divid = '';
 3581:         if (setting == 'user') {
 3582:             radioname = 'lti_mapuser_'+item;
 3583:             divid = 'lti_userfield_'+item;
 3584:         } else if (setting == 'crs') {
 3585:             radioname = 'lti_mapcrs_'+item;
 3586:             divid = 'lti_crsfield_'+item;
 3587:         } else if (setting == 'callback') {
 3588:             radioname = 'lti_callback_'+item;
 3589:             divid = 'lti_callbackfield_'+item;
 3590:         } else {
 3591:             radioname = 'lti_passback_'+item;
 3592:             divid =  'lti_passback_'+item;
 3593:         }
 3594:         var num = form.elements[radioname].length;
 3595:         if (num) {
 3596:             var setvis = '';
 3597:             for (var i=0; i<num; i++) {
 3598:                if (form.elements[radioname][i].checked) {
 3599:                    if ((setting == 'passback') || (setting == 'callback')) {
 3600:                        if (form.elements[radioname][i].value == '1') {
 3601:                            if (document.getElementById(divid)) {
 3602:                                document.getElementById(divid).style.display = 'inline-block';
 3603:                            }
 3604:                            setvis = 1;
 3605:                            break;
 3606:                        }
 3607:                    } else {
 3608:                        if (form.elements[radioname][i].value == 'other') {
 3609:                            if (document.getElementById(divid)) {
 3610:                                document.getElementById(divid).style.display = 'inline-block';
 3611:                            }
 3612:                            setvis = 1;
 3613:                            break;
 3614:                        }
 3615:                    }
 3616:                } 
 3617:             }
 3618:             if (!setvis) {
 3619:                 if (document.getElementById(divid)) {
 3620:                     document.getElementById(divid).style.display = 'none';
 3621:                 }
 3622:             }
 3623:         }
 3624:     } else if ((setting == 'sec') || (setting == 'secsrc')) {
 3625:         var numsec = form.elements['lti_crssec_'+item].length;
 3626:         if (numsec) {
 3627:             var setvis = '';
 3628:             for (var i=0; i<numsec; i++) {
 3629:                 if (form.elements['lti_crssec_'+item][i].checked) {
 3630:                     if (form.elements['lti_crssec_'+item][i].value == '1') {
 3631:                         if (document.getElementById('lti_crssecfield_'+item)) {
 3632:                             document.getElementById('lti_crssecfield_'+item).style.display = 'inline-block';
 3633:                             setvis = 1;
 3634:                             var numsrcsec = form.elements['lti_crssecsrc_'+item].length;
 3635:                             if (numsrcsec) {
 3636:                                 var setsrcvis = '';
 3637:                                 for (var j=0; j<numsrcsec; j++) {
 3638:                                     if (form.elements['lti_crssecsrc_'+item][j].checked) {
 3639:                                         if (form.elements['lti_crssecsrc_'+item][j].value == 'other') {
 3640:                                             if (document.getElementById('lti_secsrcfield_'+item)) {
 3641:                                                 document.getElementById('lti_secsrcfield_'+item).style.display = 'inline-block';
 3642:                                                 setsrcvis = 1;
 3643:                                             }
 3644:                                         }
 3645:                                     }
 3646:                                 }
 3647:                                 if (!setsrcvis) {
 3648:                                     if (document.getElementById('lti_secsrcfield_'+item)) {
 3649:                                         document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3650:                                     }
 3651:                                 }
 3652:                             }
 3653:                         }
 3654:                     }
 3655:                 }
 3656:             }
 3657:             if (!setvis) {
 3658:                 if (document.getElementById('lti_crssecfield_'+item)) {
 3659:                     document.getElementById('lti_crssecfield_'+item).style.display = 'none';
 3660:                 }
 3661:                 if (document.getElementById('lti_secsrcfield_'+item)) {
 3662:                     document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3663:                 }
 3664:             }
 3665:         }
 3666:     } else if (setting == 'lcauth') {
 3667:         var numauth = form.elements['lti_lcauth_'+item].length;
 3668:         if (numauth) {
 3669:             for (var i=0; i<numauth; i++) {
 3670:                 if (form.elements['lti_lcauth_'+item][i].checked) {
 3671:                     if (document.getElementById('lti_'+setting+'_parmrow_'+item)) {
 3672:                         if ((form.elements['lti_'+setting+'_'+item][i].value == 'internal') || (form.elements['lti_'+setting+'_'+item][i].value == 'lti')) {
 3673:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'none';
 3674:                         } else {
 3675:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'table-row';
 3676:                             if (document.getElementById('lti_'+setting+'_parmtext_'+item)) {
 3677:                                 if (form.elements['lti_'+setting+'_'+item][i].value == 'localauth') {
 3678:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'localauth'}";
 3679:                                 } else {
 3680:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'krb'}";
 3681:                                 }
 3682:                             }
 3683:                         }
 3684:                     }
 3685:                 }
 3686:             }
 3687:         }
 3688:     } else if (setting == 'lcmenu') {
 3689:         var menus = new Array('lti_topmenu_'+item,'lti_inlinemenu_'+item);
 3690:         var divid = 'lti_menufield_'+item;
 3691:         var setvis = '';
 3692:         for (var i=0; i<menus.length; i++) {
 3693:             var radioname = menus[i];  
 3694:             var num = form.elements[radioname].length;
 3695:             if (num) {
 3696:                 for (var j=0; j<num; j++) {
 3697:                     if (form.elements[radioname][j].checked) {
 3698:                         if (form.elements[radioname][j].value == '1') {
 3699:                             if (document.getElementById(divid)) {
 3700:                                 document.getElementById(divid).style.display = 'inline-block';
 3701:                             }
 3702:                             setvis = 1;
 3703:                             break;
 3704:                         }
 3705:                     }
 3706:                 }
 3707:             }
 3708:             if (setvis == 1) {
 3709:                 break;
 3710:             }
 3711:         }
 3712:         if (!setvis) {
 3713:             if (document.getElementById(divid)) {
 3714:                 document.getElementById(divid).style.display = 'none';
 3715:             }
 3716:         }
 3717:     }
 3718:     return;
 3719: }
 3720: 
 3721: function toggleLTIEncKey(form) {
 3722:     var shownhosts = new Array();
 3723:     var hiddenhosts = new Array();
 3724:     var forcourse = new Array($course_servers);
 3725:     var fromdomain = '$primary';
 3726:     var crsradio = form.elements['ltisec_crslinkprot'];
 3727:     if (crsradio.length) {
 3728:         for (var i=0; i<crsradio.length; i++) {
 3729:             if (crsradio[i].checked) {
 3730:                 if (crsradio[i].value == 1) {
 3731:                     if (forcourse.length > 0) {
 3732:                         for (var j=0; j<forcourse.length; j++) {
 3733:                             if (!shownhosts.includes(forcourse[j])) {
 3734:                                 shownhosts.push(forcourse[j]);
 3735:                             }
 3736:                         }
 3737:                     }
 3738:                 } else {
 3739:                     if (forcourse.length > 0) {
 3740:                         for (var j=0; j<forcourse.length; j++) {
 3741:                             if (!hiddenhosts.includes(forcourse[j])) { 
 3742:                                 hiddenhosts.push(forcourse[j]);
 3743:                             }
 3744:                         }
 3745:                     } 
 3746:                 }
 3747:             }
 3748:         }
 3749:     }
 3750:     var domradio = form.elements['ltisec_domlinkprot'];
 3751:     if (domradio.length) {
 3752:         for (var i=0; i<domradio.length; i++) {
 3753:             if (domradio[i].checked) {
 3754:                 if (domradio[i].value == 1) {
 3755:                     if (!shownhosts.includes(fromdomain)) { 
 3756:                         shownhosts.push(fromdomain);
 3757:                     }
 3758:                 } else {
 3759:                     if (!hiddenhosts.includes(fromdomain)) {
 3760:                         hiddenhosts.push(fromdomain);
 3761:                     }
 3762:                 }
 3763:             }
 3764:         }
 3765:     }
 3766:     var consumersradio = form.elements['ltisec_consumers'];
 3767:     if (consumersradio.length) {
 3768:         for (var i=0; i<consumersradio.length; i++) {
 3769:             if (consumersradio[i].checked) {
 3770:                 if (consumersradio[i].value == 1) {
 3771:                     if (!shownhosts.includes(fromdomain)) {     
 3772:                         shownhosts.push(fromdomain);
 3773:                     }
 3774:                 } else {
 3775:                     if (!hiddenhosts.includes(fromdomain)) {
 3776:                         hiddenhosts.push(fromdomain);
 3777:                     }
 3778:                 }
 3779:             }
 3780:         }
 3781:     }
 3782:     if (shownhosts.length > 0) {
 3783:         for (var i=0; i<shownhosts.length; i++) {
 3784:             if (document.getElementById('ltisec_info_'+shownhosts[i])) {
 3785:                 document.getElementById('ltisec_info_'+shownhosts[i]).style.display = 'block';                 
 3786:             }
 3787:         }
 3788:         if (document.getElementById('ltisec_noprivkey')) {
 3789:             document.getElementById('ltisec_noprivkey').style.display = 'none';
 3790:         }
 3791:     } else {
 3792:         if (document.getElementById('ltisec_noprivkey')) {
 3793:             document.getElementById('ltisec_noprivkey').style.display = 'inline-block';
 3794:         }
 3795:     }
 3796:     if (hiddenhosts.length > 0) {
 3797:         for (var i=0; i<hiddenhosts.length; i++) {
 3798:             if (!shownhosts.includes(hiddenhosts[i])) {
 3799:                 if (document.getElementById('ltisec_info_'+hiddenhosts[i])) {
 3800:                     document.getElementById('ltisec_info_'+hiddenhosts[i]).style.display = 'none';
 3801:                 }
 3802:             }
 3803:         }
 3804:     }
 3805:     return;
 3806: }
 3807: 
 3808: function togglePrivKey(form,hostid) {
 3809:     var radioname = '';
 3810:     var currdivid = '';
 3811:     var newdivid = '';
 3812:     if ((document.getElementById('ltisec_divcurrprivkey_'+hostid)) &&
 3813:         (document.getElementById('ltisec_divchgprivkey_'+hostid))) {
 3814:         currdivid = document.getElementById('ltisec_divcurrprivkey_'+hostid);
 3815:         newdivid = document.getElementById('ltisec_divchgprivkey_'+hostid);
 3816:         radioname = form.elements['ltisec_changeprivkey_'+hostid];
 3817:         if (radioname) {
 3818:             if (radioname.length > 0) {
 3819:                 var setvis;
 3820:                 for (var i=0; i<radioname.length; i++) {
 3821:                     if (radioname[i].checked == true) {
 3822:                         if (radioname[i].value == 1) {
 3823:                             newdivid.style.display = 'inline-block';
 3824:                             currdivid.style.display = 'none';
 3825:                             setvis = 1;
 3826:                         }
 3827:                         break;
 3828:                     }
 3829:                 }
 3830:                 if (!setvis) {
 3831:                     newdivid.style.display = 'none';
 3832:                     currdivid.style.display = 'inline-block';
 3833:                 }
 3834:             }
 3835:         }
 3836:     }
 3837: }
 3838: 
 3839: // ]]>
 3840: </script>
 3841: 
 3842: ENDSCRIPT
 3843: }
 3844: 
 3845: sub autoupdate_javascript {
 3846:     return <<"ENDSCRIPT";
 3847: <script type="text/javascript">
 3848: // <![CDATA[
 3849: function toggleLastActiveDays(form) {
 3850:     var radioname = 'lastactive';
 3851:     var divid = 'lastactive_div';
 3852:     var num = form.elements[radioname].length;
 3853:     if (num) {
 3854:         var setvis = '';
 3855:         for (var i=0; i<num; i++) {
 3856:             if (form.elements[radioname][i].checked) {
 3857:                 if (form.elements[radioname][i].value == '1') {
 3858:                     if (document.getElementById(divid)) {
 3859:                         document.getElementById(divid).style.display = 'inline-block';
 3860:                     }
 3861:                     setvis = 1;
 3862:                 }
 3863:                 break;
 3864:             }
 3865:         }
 3866:         if (!setvis) {
 3867:             if (document.getElementById(divid)) {
 3868:                 document.getElementById(divid).style.display = 'none';
 3869:             }
 3870:         }
 3871:     }
 3872:     return;
 3873: }
 3874: // ]]>
 3875: </script>
 3876: 
 3877: ENDSCRIPT
 3878: }
 3879: 
 3880: sub autoenroll_javascript {
 3881:     return <<"ENDSCRIPT";
 3882: <script type="text/javascript">
 3883: // <![CDATA[
 3884: function toggleFailsafe(form) {
 3885:     var radioname = 'autoenroll_failsafe';
 3886:     var divid = 'autoenroll_failsafe_div';
 3887:     var num = form.elements[radioname].length;
 3888:     if (num) {
 3889:         var setvis = '';
 3890:         for (var i=0; i<num; i++) {
 3891:             if (form.elements[radioname][i].checked) {
 3892:                 if ((form.elements[radioname][i].value == 'zero') || (form.elements[radioname][i].value == 'any')) {
 3893:                     if (document.getElementById(divid)) {
 3894:                         document.getElementById(divid).style.display = 'inline-block';
 3895:                     }
 3896:                     setvis = 1;
 3897:                 }
 3898:                 break;
 3899:             }
 3900:         }
 3901:         if (!setvis) {
 3902:             if (document.getElementById(divid)) {
 3903:                 document.getElementById(divid).style.display = 'none';
 3904:             }
 3905:         }
 3906:     }
 3907:     return;
 3908: }
 3909: // ]]>
 3910: </script>
 3911: 
 3912: ENDSCRIPT
 3913: }
 3914: 
 3915: sub saml_javascript {
 3916:     return <<"ENDSCRIPT";
 3917: <script type="text/javascript">
 3918: // <![CDATA[
 3919: function toggleSamlOptions(form,hostid) { 
 3920:     var radioname = 'saml_'+hostid;
 3921:     var tablecellon = 'samloptionson_'+hostid;
 3922:     var tablecelloff = 'samloptionsoff_'+hostid;
 3923:     var num = form.elements[radioname].length;
 3924:     if (num) {
 3925:         var setvis = ''; 
 3926:         for (var i=0; i<num; i++) {
 3927:             if (form.elements[radioname][i].checked) {
 3928:                 if (form.elements[radioname][i].value == '1') { 
 3929:                     if (document.getElementById(tablecellon)) {
 3930:                         document.getElementById(tablecellon).style.display='';
 3931:                     }
 3932:                     if (document.getElementById(tablecelloff)) {
 3933:                         document.getElementById(tablecelloff).style.display='none';
 3934:                     }
 3935:                     setvis = 1;
 3936:                 }
 3937:                 break;
 3938:             }
 3939:         }
 3940:         if (!setvis) {
 3941:             if (document.getElementById(tablecellon)) {
 3942:                 document.getElementById(tablecellon).style.display='none';
 3943:             }
 3944:             if (document.getElementById(tablecelloff)) {
 3945:                 document.getElementById(tablecelloff).style.display='';
 3946:             }
 3947:         }
 3948:     }
 3949:     return;
 3950: }
 3951: // ]]>
 3952: </script>
 3953: 
 3954: ENDSCRIPT
 3955: }
 3956: 
 3957: sub ipaccess_javascript {
 3958:     my ($settings) = @_;
 3959:     my (%ordered,$total,%jstext);
 3960:     $total = 0;
 3961:     if (ref($settings) eq 'HASH') {
 3962:         foreach my $item (keys(%{$settings})) {
 3963:             if (ref($settings->{$item}) eq 'HASH') {
 3964:                 my $num = $settings->{$item}{'order'};
 3965:                 $ordered{$num} = $item;
 3966:             }
 3967:         }
 3968:         $total = scalar(keys(%{$settings}));
 3969:     }
 3970:     my @jsarray = ();
 3971:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3972:         push(@jsarray,$ordered{$item});
 3973:     }
 3974:     my $jstext = '    var ipaccess = Array('."'".join("','",@jsarray)."'".');'."\n";
 3975:     return <<"ENDSCRIPT";
 3976: <script type="text/javascript">
 3977: // <![CDATA[
 3978: function reorderIPaccess(form,item) {
 3979:     var changedVal;
 3980: $jstext
 3981:     var newpos = 'ipaccess_pos_add';
 3982:     var maxh = 1 + $total;
 3983:     var current = new Array;
 3984:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3985:     if (item == newpos) {
 3986:         changedVal = newitemVal;
 3987:     } else {
 3988:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3989:         current[newitemVal] = newpos;
 3990:     }
 3991:     for (var i=0; i<ipaccess.length; i++) {
 3992:         var elementName = 'ipaccess_pos_'+ipaccess[i];
 3993:         if (elementName != item) {
 3994:             if (form.elements[elementName]) {
 3995:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3996:                 current[currVal] = elementName;
 3997:             }
 3998:         }
 3999:     }
 4000:     var oldVal;
 4001:     for (var j=0; j<maxh; j++) {
 4002:         if (current[j] == undefined) {
 4003:             oldVal = j;
 4004:         }
 4005:     }
 4006:     if (oldVal < changedVal) {
 4007:         for (var k=oldVal+1; k<=changedVal ; k++) {
 4008:            var elementName = current[k];
 4009:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 4010:         }
 4011:     } else {
 4012:         for (var k=changedVal; k<oldVal; k++) {
 4013:             var elementName = current[k];
 4014:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 4015:         }
 4016:     }
 4017:     return;
 4018: }
 4019: // ]]>
 4020: </script>
 4021: 
 4022: ENDSCRIPT
 4023: }
 4024: 
 4025: sub print_autoenroll {
 4026:     my ($dom,$settings,$rowtotal) = @_;
 4027:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 4028:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,
 4029:         $failsafe,$autofailsafe,$failsafesty,%failsafechecked);
 4030:     $failsafesty = 'none';
 4031:     %failsafechecked = (
 4032:         off => ' checked="checked"',
 4033:     );
 4034:     if (ref($settings) eq 'HASH') {
 4035:         if (exists($settings->{'run'})) {
 4036:             if ($settings->{'run'} eq '0') {
 4037:                 $runoff = ' checked="checked" ';
 4038:                 $runon = ' ';
 4039:             } else {
 4040:                 $runon = ' checked="checked" ';
 4041:                 $runoff = ' ';
 4042:             }
 4043:         } else {
 4044:             if ($autorun) {
 4045:                 $runon = ' checked="checked" ';
 4046:                 $runoff = ' ';
 4047:             } else {
 4048:                 $runoff = ' checked="checked" ';
 4049:                 $runon = ' ';
 4050:             }
 4051:         }
 4052:         if (exists($settings->{'co-owners'})) {
 4053:             if ($settings->{'co-owners'} eq '0') {
 4054:                 $coownersoff = ' checked="checked" ';
 4055:                 $coownerson = ' ';
 4056:             } else {
 4057:                 $coownerson = ' checked="checked" ';
 4058:                 $coownersoff = ' ';
 4059:             }
 4060:         } else {
 4061:             $coownersoff = ' checked="checked" ';
 4062:             $coownerson = ' ';
 4063:         }
 4064:         if (exists($settings->{'sender_domain'})) {
 4065:             $defdom = $settings->{'sender_domain'};
 4066:         }
 4067:         if (exists($settings->{'failsafe'})) {
 4068:             $failsafe = $settings->{'failsafe'};
 4069:             if ($failsafe eq 'zero') {
 4070:                 $failsafechecked{'zero'} = ' checked="checked"';
 4071:                 $failsafechecked{'off'} = '';
 4072:                 $failsafesty = 'inline-block';
 4073:             } elsif ($failsafe eq 'any') {
 4074:                 $failsafechecked{'any'} = ' checked="checked"';
 4075:                 $failsafechecked{'off'} = '';
 4076:             }
 4077:             $autofailsafe = $settings->{'autofailsafe'};
 4078:         } elsif (exists($settings->{'autofailsafe'})) {
 4079:             $autofailsafe = $settings->{'autofailsafe'};
 4080:             if ($autofailsafe ne '') {
 4081:                 $failsafechecked{'zero'} = ' checked="checked"';
 4082:                 $failsafe = 'zero';
 4083:                 $failsafechecked{'off'} = '';
 4084:             }
 4085:         }
 4086:     } else {
 4087:         if ($autorun) {
 4088:             $runon = ' checked="checked" ';
 4089:             $runoff = ' ';
 4090:         } else {
 4091:             $runoff = ' checked="checked" ';
 4092:             $runon = ' ';
 4093:         }
 4094:     }
 4095:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 4096:     my $notif_sender;
 4097:     if (ref($settings) eq 'HASH') {
 4098:         $notif_sender = $settings->{'sender_uname'};
 4099:     }
 4100:     my $datatable='<tr class="LC_odd_row">'.
 4101:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 4102:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4103:                   '<input type="radio" name="autoenroll_run"'.
 4104:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4105:                   '<label><input type="radio" name="autoenroll_run"'.
 4106:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4107:                   '</tr><tr>'.
 4108:                   '<td>'.&mt('Notification messages - sender').
 4109:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 4110:                   &mt('username').':&nbsp;'.
 4111:                   '<input type="text" name="sender_uname" value="'.
 4112:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 4113:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 4114:                   '<tr class="LC_odd_row">'.
 4115:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 4116:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4117:                   '<input type="radio" name="autoassign_coowners"'.
 4118:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4119:                   '<label><input type="radio" name="autoassign_coowners"'.
 4120:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4121:                   '</tr><tr>'.
 4122:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 4123:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 4124:                   '<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; '.
 4125:                   '<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 />'.
 4126:                   '<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>'.
 4127:                   '<div class="LC_floatleft" style="display:'.$failsafesty.';" id="autoenroll_failsafe_div">'.
 4128:                   '<span class="LC_nobreak">'.
 4129:                   &mt('Threshold for number of students in section to drop: [_1]',
 4130:                       '<input type="text" name="autoenroll_autofailsafe" value="'.$autofailsafe.'" size="4" />').
 4131:                   '</span></div></td></tr>';
 4132:     $$rowtotal += 4;
 4133:     return $datatable;
 4134: }
 4135: 
 4136: sub print_autoupdate {
 4137:     my ($position,$dom,$settings,$rowtotal) = @_;
 4138:     my ($enable,$datatable);
 4139:     if ($position eq 'top') {
 4140:         my %choices = &Apache::lonlocal::texthash (
 4141:                           run        => 'Auto-update active?',
 4142:                           classlists => 'Update information in classlists?',
 4143:                           unexpired  => 'Skip updates for users without active or future roles?',
 4144:                           lastactive => 'Skip updates for inactive users?',
 4145:         );
 4146:         my $itemcount = 0;
 4147:         my $updateon = ' ';
 4148:         my $updateoff = ' checked="checked" ';
 4149:         if (ref($settings) eq 'HASH') {
 4150:             if ($settings->{'run'} eq '1') {
 4151:                 $updateon = $updateoff;
 4152:                 $updateoff = ' ';
 4153:             }
 4154:         }
 4155:         $enable = '<tr class="LC_odd_row">'.
 4156:                   '<td>'.$choices{'run'}.'</td>'.
 4157:                   '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 4158:                   '<input type="radio" name="autoupdate_run"'.
 4159:                   $updateoff.'value="0" />'.&mt('No').'</label>&nbsp;'.
 4160:                   '<label><input type="radio" name="autoupdate_run"'.
 4161:                   $updateon.'value="1" />'.&mt('Yes').'</label></span></td>'.
 4162:                   '</tr>';
 4163:         my @toggles = ('classlists','unexpired');
 4164:         my %defaultchecked = ('classlists' => 'off',
 4165:                               'unexpired'  => 'off'
 4166:                               );
 4167:         $$rowtotal ++;
 4168:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4169:                                                      \%choices,$itemcount,'','','left','no');
 4170:         $datatable = $enable.$datatable;
 4171:         $$rowtotal += $itemcount;
 4172:         my $lastactiveon = ' ';
 4173:         my $lastactiveoff = ' checked="checked" ';
 4174:         my $lastactivestyle = 'none';
 4175:         my $lastactivedays;
 4176:         my $onclick = ' onclick="javascript:toggleLastActiveDays(this.form);"';
 4177:         if (ref($settings) eq 'HASH') {
 4178:             if ($settings->{'lastactive'} =~ /^\d+$/) {
 4179:                 $lastactiveon = $lastactiveoff;
 4180:                 $lastactiveoff = ' ';
 4181:                 $lastactivestyle = 'inline-block';
 4182:                 $lastactivedays = $settings->{'lastactive'};
 4183:             }
 4184:         }
 4185:         my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4186:         $datatable .= '<tr'.$css_class.'>'.
 4187:                       '<td>'.$choices{'lastactive'}.'</td>'.
 4188:                       '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 4189:                       '<input type="radio" name="lastactive"'.
 4190:                       $lastactiveoff.'value="0"'.$onclick.' />'.&mt('No').'</label>'.
 4191:                       '&nbsp;<label>'.
 4192:                       '<input type="radio" name="lastactive"'.
 4193:                       $lastactiveon.' value="1"'.$onclick.' />'.&mt('Yes').'</label>'.
 4194:                       '<div id="lastactive_div" style="display:'.$lastactivestyle.';">'.
 4195:                       ':&nbsp;'.&mt('inactive = no activity in last [_1] days',
 4196:                           '<input type="text" size="5" name="lastactivedays" value="'.
 4197:                           $lastactivedays.'" />').
 4198:                       '</span></td>'.
 4199:                       '</tr>';
 4200:         $$rowtotal ++;
 4201:     } elsif ($position eq 'middle') {
 4202:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4203:         my $numinrow = 3;
 4204:         my $locknamesettings;
 4205:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 4206:                                      $dom,$numinrow,$othertitle,
 4207:                                     'lockablenames',$rowtotal);
 4208:         $$rowtotal ++;
 4209:     } else {
 4210:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4211:         my @fields = ('lastname','firstname','middlename','generation',
 4212:                       'permanentemail','id');
 4213:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 4214:         my $numrows = 0;
 4215:         if (ref($types) eq 'ARRAY') {
 4216:             if (@{$types} > 0) {
 4217:                 $datatable = 
 4218:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 4219:                                          \@fields,$types,\$numrows);
 4220:                     $$rowtotal += @{$types}; 
 4221:             }
 4222:         }
 4223:         $datatable .= 
 4224:             &usertype_update_row($settings,{'default' => $othertitle},
 4225:                                  \%fieldtitles,\@fields,['default'],
 4226:                                  \$numrows);
 4227:         $$rowtotal ++;     
 4228:     }
 4229:     return $datatable;
 4230: }
 4231: 
 4232: sub print_autocreate {
 4233:     my ($dom,$settings,$rowtotal) = @_;
 4234:     my (%createon,%createoff,%currhash);
 4235:     my @types = ('xml','req');
 4236:     if (ref($settings) eq 'HASH') {
 4237:         foreach my $item (@types) {
 4238:             $createoff{$item} = ' checked="checked" ';
 4239:             $createon{$item} = ' ';
 4240:             if (exists($settings->{$item})) {
 4241:                 if ($settings->{$item}) {
 4242:                     $createon{$item} = ' checked="checked" ';
 4243:                     $createoff{$item} = ' ';
 4244:                 }
 4245:             }
 4246:         }
 4247:         if ($settings->{'xmldc'} ne '') {
 4248:             $currhash{$settings->{'xmldc'}} = 1;
 4249:         }
 4250:     } else {
 4251:         foreach my $item (@types) {
 4252:             $createoff{$item} = ' checked="checked" ';
 4253:             $createon{$item} = ' ';
 4254:         }
 4255:     }
 4256:     $$rowtotal += 2;
 4257:     my $numinrow = 2;
 4258:     my $datatable='<tr class="LC_odd_row">'.
 4259:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 4260:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4261:                   '<input type="radio" name="autocreate_xml"'.
 4262:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4263:                   '<label><input type="radio" name="autocreate_xml"'.
 4264:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 4265:                   '</td></tr><tr>'.
 4266:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 4267:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4268:                   '<input type="radio" name="autocreate_req"'.
 4269:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4270:                   '<label><input type="radio" name="autocreate_req"'.
 4271:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 4272:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 4273:                                                    'autocreate_xmldc',%currhash);
 4274:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 4275:     if ($numdc > 1) {
 4276:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 4277:                       '</td><td class="LC_left_item">';
 4278:     } else {
 4279:         $datatable .= &mt('Course creation processed as:').
 4280:                       '</td><td class="LC_right_item">';
 4281:     }
 4282:     $datatable .= $dctable.'</td></tr>';
 4283:     $$rowtotal += $rows;
 4284:     return $datatable;
 4285: }
 4286: 
 4287: sub print_directorysrch {
 4288:     my ($position,$dom,$settings,$rowtotal) = @_;
 4289:     my $datatable;
 4290:     if ($position eq 'top') {
 4291:         my $instsrchon = ' ';
 4292:         my $instsrchoff = ' checked="checked" ';
 4293:         my ($exacton,$containson,$beginson);
 4294:         my $instlocalon = ' ';
 4295:         my $instlocaloff = ' checked="checked" ';
 4296:         if (ref($settings) eq 'HASH') {
 4297:             if ($settings->{'available'} eq '1') {
 4298:                 $instsrchon = $instsrchoff;
 4299:                 $instsrchoff = ' ';
 4300:             }
 4301:             if ($settings->{'localonly'} eq '1') {
 4302:                 $instlocalon = $instlocaloff;
 4303:                 $instlocaloff = ' ';
 4304:             }
 4305:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 4306:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 4307:                     if ($type eq 'exact') {
 4308:                         $exacton = ' checked="checked" ';
 4309:                     } elsif ($type eq 'contains') {
 4310:                         $containson = ' checked="checked" ';
 4311:                     } elsif ($type eq 'begins') {
 4312:                         $beginson = ' checked="checked" ';
 4313:                     }
 4314:                 }
 4315:             } else {
 4316:                 if ($settings->{'searchtypes'} eq 'exact') {
 4317:                     $exacton = ' checked="checked" ';
 4318:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 4319:                     $containson = ' checked="checked" ';
 4320:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 4321:                     $exacton = ' checked="checked" ';
 4322:                     $containson = ' checked="checked" ';
 4323:                 }
 4324:             }
 4325:         }
 4326:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 4327:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4328: 
 4329:         my $numinrow = 4;
 4330:         my $cansrchrow = 0;
 4331:         $datatable='<tr class="LC_odd_row">'.
 4332:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 4333:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4334:                    '<input type="radio" name="dirsrch_available"'.
 4335:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4336:                    '<label><input type="radio" name="dirsrch_available"'.
 4337:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4338:                    '</tr><tr>'.
 4339:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 4340:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4341:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 4342:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 4343:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 4344:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 4345:                    '</tr>';
 4346:         $$rowtotal += 2;
 4347:         if (ref($usertypes) eq 'HASH') {
 4348:             if (keys(%{$usertypes}) > 0) {
 4349:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4350:                                              $numinrow,$othertitle,'cansearch',
 4351:                                              $rowtotal);
 4352:                 $cansrchrow = 1;
 4353:             }
 4354:         }
 4355:         if ($cansrchrow) {
 4356:             $$rowtotal ++;
 4357:             $datatable .= '<tr>';
 4358:         } else {
 4359:             $datatable .= '<tr class="LC_odd_row">';
 4360:         }
 4361:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 4362:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 4363:         foreach my $title (@{$titleorder}) {
 4364:             if (defined($searchtitles->{$title})) {
 4365:                 my $check = ' ';
 4366:                 if (ref($settings) eq 'HASH') {
 4367:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 4368:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 4369:                             $check = ' checked="checked" ';
 4370:                         }
 4371:                     }
 4372:                 }
 4373:                 $datatable .= '<td class="LC_left_item">'.
 4374:                               '<span class="LC_nobreak"><label>'.
 4375:                               '<input type="checkbox" name="searchby" '.
 4376:                               'value="'.$title.'"'.$check.'/>'.
 4377:                               $searchtitles->{$title}.'</label></span></td>';
 4378:             }
 4379:         }
 4380:         $datatable .= '</tr></table></td></tr>';
 4381:         $$rowtotal ++;
 4382:         if ($cansrchrow) {
 4383:             $datatable .= '<tr class="LC_odd_row">';
 4384:         } else {
 4385:             $datatable .= '<tr>';
 4386:         }
 4387:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 4388:                       '<td class="LC_left_item" colspan="2">'.
 4389:                       '<span class="LC_nobreak"><label>'.
 4390:                       '<input type="checkbox" name="searchtypes" '.
 4391:                       $exacton.' value="exact" />'.&mt('Exact match').
 4392:                       '</label>&nbsp;'.
 4393:                       '<label><input type="checkbox" name="searchtypes" '.
 4394:                       $beginson.' value="begins" />'.&mt('Begins with').
 4395:                       '</label>&nbsp;'.
 4396:                       '<label><input type="checkbox" name="searchtypes" '.
 4397:                       $containson.' value="contains" />'.&mt('Contains').
 4398:                       '</label></span></td></tr>';
 4399:         $$rowtotal ++;
 4400:     } else {
 4401:         my $domsrchon = ' checked="checked" ';
 4402:         my $domsrchoff = ' ';
 4403:         my $domlocalon = ' ';
 4404:         my $domlocaloff = ' checked="checked" ';
 4405:         if (ref($settings) eq 'HASH') {
 4406:             if ($settings->{'lclocalonly'} eq '1') {
 4407:                 $domlocalon = $domlocaloff;
 4408:                 $domlocaloff = ' ';
 4409:             }
 4410:             if ($settings->{'lcavailable'} eq '0') {
 4411:                 $domsrchoff = $domsrchon;
 4412:                 $domsrchon = ' ';
 4413:             }
 4414:         }
 4415:         $datatable='<tr class="LC_odd_row">'.
 4416:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 4417:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4418:                       '<input type="radio" name="dirsrch_domavailable"'.
 4419:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4420:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 4421:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4422:                       '</tr><tr>'.
 4423:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 4424:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4425:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 4426:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 4427:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 4428:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 4429:                       '</tr>';
 4430:         $$rowtotal += 2;
 4431:     }
 4432:     return $datatable;
 4433: }
 4434: 
 4435: sub print_contacts {
 4436:     my ($position,$dom,$settings,$rowtotal) = @_;
 4437:     my $datatable;
 4438:     my @contacts = ('adminemail','supportemail');
 4439:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 4440:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings,%lonstatus);
 4441:     if ($position eq 'top') {
 4442:         if (ref($settings) eq 'HASH') {
 4443:             foreach my $item (@contacts) {
 4444:                 if (exists($settings->{$item})) {
 4445:                     $to{$item} = $settings->{$item};
 4446:                 }
 4447:             }
 4448:         }
 4449:     } elsif ($position eq 'middle') {
 4450:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 4451:                      'updatesmail','idconflictsmail','hostipmail');
 4452:         foreach my $type (@mailings) {
 4453:             $otheremails{$type} = '';
 4454:         }
 4455:     } elsif ($position eq 'lower') {
 4456:         if (ref($settings) eq 'HASH') {
 4457:             if (ref($settings->{'lonstatus'}) eq 'HASH') {
 4458:                 %lonstatus = %{$settings->{'lonstatus'}};
 4459:             }
 4460:         }
 4461:     } else {
 4462:         @mailings = ('helpdeskmail','otherdomsmail');
 4463:         foreach my $type (@mailings) {
 4464:             $otheremails{$type} = '';
 4465:         }
 4466:         $bccemails{'helpdeskmail'} = '';
 4467:         $bccemails{'otherdomsmail'} = '';
 4468:         $includestr{'helpdeskmail'} = '';
 4469:         $includestr{'otherdomsmail'} = '';
 4470:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 4471:     }
 4472:     if (ref($settings) eq 'HASH') {
 4473:         unless (($position eq 'top') || ($position eq 'lower')) {
 4474:             foreach my $type (@mailings) {
 4475:                 if (exists($settings->{$type})) {
 4476:                     if (ref($settings->{$type}) eq 'HASH') {
 4477:                         foreach my $item (@contacts) {
 4478:                             if ($settings->{$type}{$item}) {
 4479:                                 $checked{$type}{$item} = ' checked="checked" ';
 4480:                             }
 4481:                         }
 4482:                         $otheremails{$type} = $settings->{$type}{'others'};
 4483:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4484:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 4485:                             if ($settings->{$type}{'include'} ne '') {
 4486:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 4487:                                 $includestr{$type} = &unescape($includestr{$type});
 4488:                             }
 4489:                         }
 4490:                     }
 4491:                 } elsif ($type eq 'lonstatusmail') {
 4492:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 4493:                 }
 4494:             }
 4495:         }
 4496:         if ($position eq 'bottom') {
 4497:             foreach my $type (@mailings) {
 4498:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 4499:                 if ($settings->{$type}{'include'} ne '') {
 4500:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 4501:                     $includestr{$type} = &unescape($includestr{$type});
 4502:                 }
 4503:             }
 4504:             if (ref($settings->{'helpform'}) eq 'HASH') {
 4505:                 if (ref($fields) eq 'ARRAY') {
 4506:                     foreach my $field (@{$fields}) {
 4507:                         $currfield{$field} = $settings->{'helpform'}{$field};
 4508:                     }
 4509:                 }
 4510:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 4511:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 4512:                 } else {
 4513:                     $maxsize = '1.0';
 4514:                 }
 4515:             } else {
 4516:                 if (ref($fields) eq 'ARRAY') {
 4517:                     foreach my $field (@{$fields}) {
 4518:                         $currfield{$field} = 'yes';
 4519:                     }
 4520:                 }
 4521:                 $maxsize = '1.0';
 4522:             }
 4523:         }
 4524:     } else {
 4525:         if ($position eq 'top') {
 4526:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 4527:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 4528:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 4529:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 4530:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 4531:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 4532:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 4533:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 4534:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 4535:         } elsif ($position eq 'bottom') {
 4536:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 4537:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 4538:             if (ref($fields) eq 'ARRAY') {
 4539:                 foreach my $field (@{$fields}) {
 4540:                     $currfield{$field} = 'yes';
 4541:                 }
 4542:             }
 4543:             $maxsize = '1.0';
 4544:         }
 4545:     }
 4546:     my ($titles,$short_titles) = &contact_titles();
 4547:     my $rownum = 0;
 4548:     my $css_class;
 4549:     if ($position eq 'top') {
 4550:         foreach my $item (@contacts) {
 4551:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4552:             $datatable .= '<tr'.$css_class.'>'. 
 4553:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 4554:                           '</span></td><td class="LC_right_item">'.
 4555:                           '<input type="text" name="'.$item.'" value="'.
 4556:                           $to{$item}.'" /></td></tr>';
 4557:             $rownum ++;
 4558:         }
 4559:     } elsif ($position eq 'bottom') {
 4560:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4561:         $datatable .= '<tr'.$css_class.'>'.
 4562:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 4563:                       &mt('(e-mail, subject, and description always shown)').
 4564:                       '</td><td class="LC_left_item">';
 4565:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 4566:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 4567:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 4568:             foreach my $field (@{$fields}) {
 4569:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 4570:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 4571:                     $datatable .= ' '.&mt('(logged-in users)');
 4572:                 }
 4573:                 $datatable .='</td><td>';
 4574:                 my $clickaction;
 4575:                 if ($field eq 'screenshot') {
 4576:                     $clickaction = ' onclick="screenshotSize(this);"';
 4577:                 }
 4578:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 4579:                     foreach my $option (@{$possoptions->{$field}}) {
 4580:                         my $checked;
 4581:                         if ($currfield{$field} eq $option) {
 4582:                             $checked = ' checked="checked"';
 4583:                         }
 4584:                         $datatable .= '<span class="LC_nobreak"><label>'.
 4585:                                       '<input type="radio" name="helpform_'.$field.'" '.
 4586:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 4587:                                       '</label></span>'.('&nbsp;'x2);
 4588:                     }
 4589:                 }
 4590:                 if ($field eq 'screenshot') {
 4591:                     my $display;
 4592:                     if ($currfield{$field} eq 'no') {
 4593:                         $display = ' style="display:none"';
 4594:                     }
 4595:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 4596:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 4597:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 4598:                 }
 4599:                 $datatable .= '</td></tr>';
 4600:             }
 4601:             $datatable .= '</table>';
 4602:         }
 4603:         $datatable .= '</td></tr>'."\n";
 4604:         $rownum ++;
 4605:     }
 4606:     unless (($position eq 'top') || ($position eq 'lower')) {
 4607:         foreach my $type (@mailings) {
 4608:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4609:             $datatable .= '<tr'.$css_class.'>'.
 4610:                           '<td><span class="LC_nobreak">'.
 4611:                           $titles->{$type}.': </span></td>'.
 4612:                           '<td class="LC_left_item">';
 4613:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4614:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 4615:             }
 4616:             $datatable .= '<span class="LC_nobreak">';
 4617:             foreach my $item (@contacts) {
 4618:                 $datatable .= '<label>'.
 4619:                               '<input type="checkbox" name="'.$type.'"'.
 4620:                               $checked{$type}{$item}.
 4621:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 4622:                               '</label>&nbsp;';
 4623:             }
 4624:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4625:                           '<input type="text" name="'.$type.'_others" '.
 4626:                           'value="'.$otheremails{$type}.'"  />';
 4627:             my %locchecked;
 4628:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4629:                 foreach my $loc ('s','b') {
 4630:                     if ($includeloc{$type} eq $loc) {
 4631:                         $locchecked{$loc} = ' checked="checked"';
 4632:                         last;
 4633:                     }
 4634:                 }
 4635:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4636:                               '<input type="text" name="'.$type.'_bcc" '.
 4637:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 4638:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4639:                               &mt('Text automatically added to e-mail:').' '.
 4640:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 4641:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4642:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4643:                               ('&nbsp;'x2).
 4644:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4645:                               '</span></fieldset>';
 4646:             }
 4647:             $datatable .= '</td></tr>'."\n";
 4648:             $rownum ++;
 4649:         }
 4650:     }
 4651:     if ($position eq 'middle') {
 4652:         my %choices;
 4653:         my $corelink = &core_link_msu();
 4654:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',$corelink);
 4655:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 4656:                                         $corelink);
 4657:         $choices{'reportstatus'} = &mt('E-mail status if errors above threshold to [_1]',$corelink);
 4658:         my @toggles = ('reporterrors','reportupdates','reportstatus');
 4659:         my %defaultchecked = ('reporterrors'  => 'on',
 4660:                               'reportupdates' => 'on',
 4661:                               'reportstatus'  => 'on');
 4662:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4663:                                                    \%choices,$rownum);
 4664:         $datatable .= $reports;
 4665:     } elsif ($position eq 'lower') {
 4666:         my (%current,%excluded,%weights);
 4667:         my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 4668:         if ($lonstatus{'threshold'} =~ /^\d+$/) {
 4669:             $current{'errorthreshold'} = $lonstatus{'threshold'};
 4670:         } else {
 4671:             $current{'errorthreshold'} = $defaults->{'threshold'};
 4672:         }
 4673:         if ($lonstatus{'sysmail'} =~ /^\d+$/) {
 4674:             $current{'errorsysmail'} = $lonstatus{'sysmail'};
 4675:         } else {
 4676:             $current{'errorsysmail'} = $defaults->{'sysmail'};
 4677:         }
 4678:         if (ref($lonstatus{'weights'}) eq 'HASH') {
 4679:             foreach my $type ('E','W','N','U') {
 4680:                 if ($lonstatus{'weights'}{$type} =~ /^\d+$/) {
 4681:                     $weights{$type} = $lonstatus{'weights'}{$type};
 4682:                 } else {
 4683:                     $weights{$type} = $defaults->{$type};
 4684:                 }
 4685:             }
 4686:         } else {
 4687:             foreach my $type ('E','W','N','U') {
 4688:                 $weights{$type} = $defaults->{$type};
 4689:             }
 4690:         }
 4691:         if (ref($lonstatus{'excluded'}) eq 'ARRAY') {
 4692:             if (@{$lonstatus{'excluded'}} > 0) {
 4693:                 map {$excluded{$_} = 1; } @{$lonstatus{'excluded'}};
 4694:             }
 4695:         }
 4696:         foreach my $item ('errorthreshold','errorsysmail') { 
 4697:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4698:             $datatable .= '<tr'.$css_class.'>'.
 4699:                           '<td class="LC_left_item"><span class="LC_nobreak">'.
 4700:                           $titles->{$item}.
 4701:                           '</span></td><td class="LC_left_item">'.
 4702:                           '<input type="text" name="'.$item.'" value="'.
 4703:                           $current{$item}.'" size="5" /></td></tr>';
 4704:             $rownum ++;
 4705:         }
 4706:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4707:         $datatable .= '<tr'.$css_class.'>'.
 4708:                       '<td class="LC_left_item">'.
 4709:                       '<span class="LC_nobreak">'.$titles->{'errorweights'}.
 4710:                       '</span></td><td class="LC_left_item"><table><tr>';
 4711:         foreach my $type ('E','W','N','U') {
 4712:             $datatable .= '<td>'.$names->{$type}.'<br />'.
 4713:                           '<input type="text" name="errorweights_'.$type.'" value="'.
 4714:                           $weights{$type}.'" size="5" /></td>';
 4715:         }
 4716:         $datatable .= '</tr></table></tr>';
 4717:         $rownum ++;
 4718:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4719:         $datatable .= '<tr'.$css_class.'><td class="LC_left_item">'.
 4720:                       $titles->{'errorexcluded'}.'</td>'.
 4721:                       '<td class="LC_left_item"><table>';
 4722:         my $numinrow = 4;
 4723:         my @ids = sort(values(%Apache::lonnet::serverhomeIDs));
 4724:         for (my $i=0; $i<@ids; $i++) {
 4725:             my $rem = $i%($numinrow);
 4726:             if ($rem == 0) {
 4727:                 if ($i > 0) {
 4728:                     $datatable .= '</tr>';
 4729:                 }
 4730:                 $datatable .= '<tr>';
 4731:             }
 4732:             my $check;
 4733:             if ($excluded{$ids[$i]}) {
 4734:                 $check = ' checked="checked" ';
 4735:             }
 4736:             $datatable .= '<td class="LC_left_item">'.
 4737:                           '<span class="LC_nobreak"><label>'.
 4738:                           '<input type="checkbox" name="errorexcluded" '.
 4739:                           'value="'.$ids[$i].'"'.$check.' />'.
 4740:                           $ids[$i].'</label></span></td>';
 4741:         }
 4742:         my $colsleft = $numinrow - @ids%($numinrow);
 4743:         if ($colsleft > 1 ) {
 4744:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4745:                           '&nbsp;</td>';
 4746:         } elsif ($colsleft == 1) {
 4747:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 4748:         }
 4749:         $datatable .= '</tr></table></td></tr>';
 4750:         $rownum ++;
 4751:     } elsif ($position eq 'bottom') {
 4752:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4753:         my (@posstypes,%usertypeshash);
 4754:         if (ref($types) eq 'ARRAY') {
 4755:             @posstypes = @{$types};
 4756:         }
 4757:         if (@posstypes) {
 4758:             if (ref($usertypes) eq 'HASH') {
 4759:                 %usertypeshash = %{$usertypes};
 4760:             }
 4761:             my @overridden;
 4762:             my $numinrow = 4;
 4763:             if (ref($settings) eq 'HASH') {
 4764:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 4765:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 4766:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 4767:                             push(@overridden,$key);
 4768:                             foreach my $item (@contacts) {
 4769:                                 if ($settings->{'overrides'}{$key}{$item}) {
 4770:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 4771:                                 }
 4772:                             }
 4773:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 4774:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 4775:                             $includeloc{'override_'.$key} = '';
 4776:                             $includestr{'override_'.$key} = '';
 4777:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 4778:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) = 
 4779:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 4780:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 4781:                             }
 4782:                         }
 4783:                     }
 4784:                 }
 4785:             }
 4786:             my $customclass = 'LC_helpdesk_override';
 4787:             my $optionsprefix = 'LC_options_helpdesk_';
 4788: 
 4789:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 4790:  
 4791:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4792:                                          $numinrow,$othertitle,'overrides',
 4793:                                          \$rownum,$onclicktypes,$customclass);
 4794:             $rownum ++;
 4795:             $usertypeshash{'default'} = $othertitle;
 4796:             foreach my $status (@posstypes) {
 4797:                 my $css_class;
 4798:                 if ($rownum%2) {
 4799:                     $css_class = 'LC_odd_row ';
 4800:                 }
 4801:                 $css_class .= $customclass;
 4802:                 my $rowid = $optionsprefix.$status;
 4803:                 my $hidden = 1;
 4804:                 my $currstyle = 'display:none';
 4805:                 if (grep(/^\Q$status\E$/,@overridden)) {
 4806:                     $currstyle = 'display:table-row';
 4807:                     $hidden = 0;
 4808:                 }
 4809:                 my $key = 'override_'.$status;
 4810:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 4811:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 4812:                                                   $usertypeshash{$status},$css_class,$currstyle,
 4813:                                                   \@contacts,$short_titles);
 4814:                 unless ($hidden) {
 4815:                     $rownum ++;
 4816:                 }
 4817:             }
 4818:         }
 4819:     }
 4820:     $$rowtotal += $rownum;
 4821:     return $datatable;
 4822: }
 4823: 
 4824: sub core_link_msu {
 4825:     return &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 4826:                                           &mt('LON-CAPA core group - MSU'),600,500);
 4827: }
 4828: 
 4829: sub overridden_helpdesk {
 4830:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 4831:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 4832:     my $class = 'LC_left_item';
 4833:     if ($css_class) {
 4834:         $css_class = ' class="'.$css_class.'"';
 4835:     }
 4836:     if ($rowid) {
 4837:         $rowid = ' id="'.$rowid.'"';
 4838:     }
 4839:     if ($rowstyle) {
 4840:         $rowstyle = ' style="'.$rowstyle.'"';
 4841:     }
 4842:     my ($output,$description);
 4843:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 4844:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 4845:               "<td>$description</td>\n".
 4846:               '<td class="'.$class.'" colspan="2">'.
 4847:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 4848:               '<span class="LC_nobreak">';
 4849:     if (ref($contacts) eq 'ARRAY') {
 4850:         foreach my $item (@{$contacts}) {
 4851:             my $check;
 4852:             if (ref($checked) eq 'HASH') {
 4853:                $check = $checked->{$item};
 4854:             }
 4855:             my $title;
 4856:             if (ref($short_titles) eq 'HASH') {
 4857:                 $title = $short_titles->{$item}; 
 4858:             }
 4859:             $output .= '<label>'.
 4860:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 4861:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 4862:         }
 4863:     }
 4864:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4865:                '<input type="text" name="override_'.$type.'_others" '.
 4866:                'value="'.$otheremails.'"  />';
 4867:     my %locchecked;
 4868:     foreach my $loc ('s','b') {
 4869:         if ($includeloc eq $loc) {
 4870:             $locchecked{$loc} = ' checked="checked"';
 4871:             last;
 4872:         }
 4873:     }
 4874:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4875:                '<input type="text" name="override_'.$type.'_bcc" '.
 4876:                'value="'.$bccemails.'"  /></fieldset>'.
 4877:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4878:                &mt('Text automatically added to e-mail:').' '.
 4879:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 4880:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4881:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4882:                ('&nbsp;'x2).
 4883:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4884:                '</span></fieldset>'.
 4885:                '</td></tr>'."\n";
 4886:     return $output;
 4887: }
 4888: 
 4889: sub contacts_javascript {
 4890:     return <<"ENDSCRIPT";
 4891: 
 4892: <script type="text/javascript">
 4893: // <![CDATA[
 4894: 
 4895: function screenshotSize(field) {
 4896:     if (document.getElementById('help_screenshotsize')) {
 4897:         if (field.value == 'no') {
 4898:             document.getElementById('help_screenshotsize').style.display="none";
 4899:         } else {
 4900:             document.getElementById('help_screenshotsize').style.display="";
 4901:         }
 4902:     }
 4903:     return;
 4904: }
 4905: 
 4906: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 4907:     if (form.elements[checkbox].length != undefined) {
 4908:         var count = 0;
 4909:         if (docount) {
 4910:             for (var i=0; i<form.elements[checkbox].length; i++) {
 4911:                 if (form.elements[checkbox][i].checked) {
 4912:                     count ++;
 4913:                 }
 4914:             }
 4915:         }
 4916:         for (var i=0; i<form.elements[checkbox].length; i++) {
 4917:             var type = form.elements[checkbox][i].value;
 4918:             if (document.getElementById(prefix+type)) {
 4919:                 if (form.elements[checkbox][i].checked) {
 4920:                     document.getElementById(prefix+type).style.display = 'table-row';
 4921:                     if (count % 2 == 1) {
 4922:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 4923:                     } else {
 4924:                         document.getElementById(prefix+type).className = target;
 4925:                     }
 4926:                     count ++;
 4927:                 } else {
 4928:                     document.getElementById(prefix+type).style.display = 'none';
 4929:                 }
 4930:             }
 4931:         }
 4932:     }
 4933:     return;
 4934: }
 4935: 
 4936: 
 4937: // ]]>
 4938: </script>
 4939: 
 4940: ENDSCRIPT
 4941: }
 4942: 
 4943: sub print_helpsettings {
 4944:     my ($position,$dom,$settings,$rowtotal) = @_;
 4945:     my $confname = $dom.'-domainconfig';
 4946:     my $formname = 'display';
 4947:     my ($datatable,$itemcount);
 4948:     if ($position eq 'top') {
 4949:         $itemcount = 1;
 4950:         my (%choices,%defaultchecked,@toggles);
 4951:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 4952:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 4953:                                      &mt('LON-CAPA bug tracker'),600,500));
 4954:         %defaultchecked = ('submitbugs' => 'on');
 4955:         @toggles = ('submitbugs');
 4956:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4957:                                                      \%choices,$itemcount);
 4958:         $$rowtotal ++;
 4959:     } else {
 4960:         my $css_class;
 4961:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 4962:         my (%customroles,%ordered,%current);
 4963:         if (ref($settings) eq 'HASH') {
 4964:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 4965:                 %current = %{$settings->{'adhoc'}};
 4966:             }
 4967:         }
 4968:         my $count = 0;
 4969:         foreach my $key (sort(keys(%existing))) {
 4970:             if ($key=~/^rolesdef\_(\w+)$/) {
 4971:                 my $rolename = $1;
 4972:                 my (%privs,$order);
 4973:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 4974:                 $customroles{$rolename} = \%privs;
 4975:                 if (ref($current{$rolename}) eq 'HASH') {
 4976:                     $order = $current{$rolename}{'order'};
 4977:                 }
 4978:                 if ($order eq '') {
 4979:                     $order = $count;
 4980:                 }
 4981:                 $ordered{$order} = $rolename;
 4982:                 $count++;
 4983:             }
 4984:         }
 4985:         my $maxnum = scalar(keys(%ordered));
 4986:         my @roles_by_num = ();
 4987:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4988:             push(@roles_by_num,$item);
 4989:         }
 4990:         my $context = 'domprefs';
 4991:         my $crstype = 'Course';
 4992:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4993:         my @accesstypes = ('all','dh','da','none');
 4994:         my ($numstatustypes,@jsarray);
 4995:         if (ref($types) eq 'ARRAY') {
 4996:             if (@{$types} > 0) {
 4997:                 $numstatustypes = scalar(@{$types});
 4998:                 push(@accesstypes,'status');
 4999:                 @jsarray = ('bystatus');
 5000:             }
 5001:         }
 5002:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 5003:         if (keys(%domhelpdesk)) {
 5004:             push(@accesstypes,('inc','exc'));
 5005:             push(@jsarray,('notinc','notexc'));
 5006:         }
 5007:         my $hiddenstr = join("','",@jsarray);
 5008:         my $context = 'domprefs';
 5009:         my $crstype = 'Course';
 5010:         my $prefix = 'helproles_';
 5011:         my $add_class = 'LC_hidden';
 5012:         foreach my $num (@roles_by_num) {
 5013:             my $role = $ordered{$num};
 5014:             my ($desc,$access,@statuses);
 5015:             if (ref($current{$role}) eq 'HASH') {
 5016:                 $desc = $current{$role}{'desc'};
 5017:                 $access = $current{$role}{'access'};
 5018:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 5019:                     @statuses = @{$current{$role}{'insttypes'}};
 5020:                 }
 5021:             }
 5022:             if ($desc eq '') {
 5023:                 $desc = $role;
 5024:             }
 5025:             my $identifier = 'custhelp'.$num;
 5026:             my %full=();
 5027:             my %levels= (
 5028:                          course => {},
 5029:                          domain => {},
 5030:                          system => {},
 5031:                         );
 5032:             my %levelscurrent=(
 5033:                                course => {},
 5034:                                domain => {},
 5035:                                system => {},
 5036:                               );
 5037:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 5038:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5039:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5040:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 5041:             $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><b>'.$role.'</b><br />'.
 5042:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 5043:             for (my $k=0; $k<=$maxnum; $k++) {
 5044:                 my $vpos = $k+1;
 5045:                 my $selstr;
 5046:                 if ($k == $num) {
 5047:                     $selstr = ' selected="selected" ';
 5048:                 }
 5049:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5050:             }
 5051:             $datatable .= '</select>'.('&nbsp;'x2).
 5052:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 5053:                           '</td>'.
 5054:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 5055:                           &mt('Name shown to users:').
 5056:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 5057:                           '</fieldset>'.
 5058:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 5059:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 5060:                           '<fieldset>'.
 5061:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 5062:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 5063:                                                                    \%levelscurrent,$identifier,
 5064:                                                                    'LC_hidden',$prefix.$num.'_privs').
 5065:                           '</fieldset></td>';
 5066:             $itemcount ++;
 5067:         }
 5068:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5069:         my $newcust = 'custhelp'.$count;
 5070:         my (%privs,%levelscurrent);
 5071:         my %full=();
 5072:         my %levels= (
 5073:                      course => {},
 5074:                      domain => {},
 5075:                      system => {},
 5076:                     );
 5077:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 5078:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5079:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 5080:         $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><span class="LC_nobreak"><label>'.
 5081:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 5082:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 5083:         for (my $k=0; $k<$maxnum+1; $k++) {
 5084:             my $vpos = $k+1;
 5085:             my $selstr;
 5086:             if ($k == $maxnum) {
 5087:                 $selstr = ' selected="selected" ';
 5088:             }
 5089:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5090:         }
 5091:         $datatable .= '</select>&nbsp;'."\n".
 5092:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 5093:                       '</label></span></td>'.
 5094:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 5095:                       '<span class="LC_nobreak">'.
 5096:                       &mt('Internal name:').
 5097:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 5098:                       '</span>'.('&nbsp;'x4).
 5099:                       '<span class="LC_nobreak">'.
 5100:                       &mt('Name shown to users:').
 5101:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 5102:                       '</span></fieldset>'.
 5103:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 5104:                                              $usertypes,$types,\%domhelpdesk).
 5105:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 5106:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 5107:                                                                 \@templateroles,$newcust).
 5108:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 5109:                                                                \%levelscurrent,$newcust).
 5110:                       '</fieldset>'.
 5111:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 5112:                       '</td></tr>';
 5113:         $count ++;
 5114:         $$rowtotal += $count;
 5115:     }
 5116:     return $datatable;
 5117: }
 5118: 
 5119: sub adhocbutton {
 5120:     my ($prefix,$num,$field,$visibility) = @_;
 5121:     my %lt = &Apache::lonlocal::texthash(
 5122:                                           show => 'Show details',
 5123:                                           hide => 'Hide details',
 5124:                                         );
 5125:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 5126:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 5127:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 5128:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 5129: }
 5130: 
 5131: sub helpsettings_javascript {
 5132:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 5133:     return unless(ref($roles_by_num) eq 'ARRAY');
 5134:     my %html_js_lt = &Apache::lonlocal::texthash(
 5135:                                           show => 'Show details',
 5136:                                           hide => 'Hide details',
 5137:                                         );
 5138:     &html_escape(\%html_js_lt);
 5139:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 5140:     return <<"ENDSCRIPT";
 5141: <script type="text/javascript">
 5142: // <![CDATA[
 5143: 
 5144: function reorderHelpRoles(form,item) {
 5145:     var changedVal;
 5146: $jstext
 5147:     var newpos = 'helproles_${total}_pos';
 5148:     var maxh = 1 + $total;
 5149:     var current = new Array();
 5150:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 5151:     if (item == newpos) {
 5152:         changedVal = newitemVal;
 5153:     } else {
 5154:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 5155:         current[newitemVal] = newpos;
 5156:     }
 5157:     for (var i=0; i<helproles.length; i++) {
 5158:         var elementName = 'helproles_'+helproles[i]+'_pos';
 5159:         if (elementName != item) {
 5160:             if (form.elements[elementName]) {
 5161:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 5162:                 current[currVal] = elementName;
 5163:             }
 5164:         }
 5165:     }
 5166:     var oldVal;
 5167:     for (var j=0; j<maxh; j++) {
 5168:         if (current[j] == undefined) {
 5169:             oldVal = j;
 5170:         }
 5171:     }
 5172:     if (oldVal < changedVal) {
 5173:         for (var k=oldVal+1; k<=changedVal ; k++) {
 5174:            var elementName = current[k];
 5175:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 5176:         }
 5177:     } else {
 5178:         for (var k=changedVal; k<oldVal; k++) {
 5179:             var elementName = current[k];
 5180:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 5181:         }
 5182:     }
 5183:     return;
 5184: }
 5185: 
 5186: function helpdeskAccess(num) {
 5187:     var curraccess = null;
 5188:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 5189:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 5190:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 5191:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 5192:             }
 5193:         }
 5194:     }
 5195:     var shown = Array();
 5196:     var hidden = Array();
 5197:     if (curraccess == 'none') {
 5198:         hidden = Array('$hiddenstr');
 5199:     } else {
 5200:         if (curraccess == 'status') {
 5201:             shown = Array('bystatus');
 5202:             hidden = Array('notinc','notexc');
 5203:         } else {
 5204:             if (curraccess == 'exc') {
 5205:                 shown = Array('notexc');
 5206:                 hidden = Array('notinc','bystatus');
 5207:             }
 5208:             if (curraccess == 'inc') {
 5209:                 shown = Array('notinc');
 5210:                 hidden = Array('notexc','bystatus');
 5211:             }
 5212:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 5213:                 hidden = Array('notinc','notexc','bystatus');
 5214:             }
 5215:         }
 5216:     }
 5217:     if (hidden.length > 0) {
 5218:         for (var i=0; i<hidden.length; i++) {
 5219:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 5220:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 5221:             }
 5222:         }
 5223:     }
 5224:     if (shown.length > 0) {
 5225:         for (var i=0; i<shown.length; i++) {
 5226:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 5227:                 if (shown[i] == 'privs') {
 5228:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 5229:                 } else {
 5230:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 5231:                 }
 5232:             }
 5233:         }
 5234:     }
 5235:     return;
 5236: }
 5237: 
 5238: function toggleHelpdeskItem(num,field) {
 5239:     if (document.getElementById('helproles_'+num+'_'+field)) {
 5240:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 5241:             document.getElementById('helproles_'+num+'_'+field).className =
 5242:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 5243:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 5244:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 5245:             }
 5246:         } else {
 5247:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 5248:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 5249:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 5250:             }
 5251:         }
 5252:     }
 5253:     return;
 5254: }
 5255: 
 5256: // ]]>
 5257: </script>
 5258: 
 5259: ENDSCRIPT
 5260: }
 5261: 
 5262: sub helpdeskroles_access {
 5263:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 5264:         $usertypes,$types,$domhelpdesk) = @_;
 5265:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 5266:     my %lt = &Apache::lonlocal::texthash(
 5267:                     'rou'    => 'Role usage',
 5268:                     'whi'    => 'Which helpdesk personnel may use this role?',
 5269:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 5270:                     'dh'     => 'All with domain helpdesk role',
 5271:                     'da'     => 'All with domain helpdesk assistant role',
 5272:                     'none'   => 'None',
 5273:                     'status' => 'Determined based on institutional status',
 5274:                     'inc'    => 'Include all, but exclude specific personnel',
 5275:                     'exc'    => 'Exclude all, but include specific personnel',
 5276:                   );
 5277:     my %usecheck = (
 5278:                      all => ' checked="checked"',
 5279:                    );
 5280:     my %displaydiv = (
 5281:                       status => 'none',
 5282:                       inc    => 'none',
 5283:                       exc    => 'none',
 5284:                       priv   => 'block',
 5285:                      );
 5286:     my $output;
 5287:     if (ref($current) eq 'HASH') {
 5288:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 5289:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 5290:                 $usecheck{$current->{access}} = $usecheck{'all'};
 5291:                 delete($usecheck{'all'});
 5292:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 5293:                     my $access = $1;
 5294:                     $displaydiv{$access} = 'inline';
 5295:                 } elsif ($current->{access} eq 'none') {
 5296:                     $displaydiv{'priv'} = 'none';
 5297:                 }
 5298:             }
 5299:         }
 5300:     }
 5301:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 5302:               '<p>'.$lt{'whi'}.'</p>';
 5303:     foreach my $access (@{$accesstypes}) {
 5304:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 5305:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 5306:                    $lt{$access}.'</label>';
 5307:         if ($access eq 'status') {
 5308:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 5309:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 5310:                                                                  $othertitle,$usertypes,$types).
 5311:                        '</div>';
 5312:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 5313:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 5314:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 5315:                        '</div>';
 5316:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 5317:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 5318:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 5319:                        '</div>';
 5320:         }
 5321:         $output .= '</p>';
 5322:     }
 5323:     $output .= '</fieldset>';
 5324:     return $output;
 5325: }
 5326: 
 5327: sub radiobutton_prefs {
 5328:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 5329:         $additional,$align,$firstval) = @_;
 5330:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 5331:                    (ref($choices) eq 'HASH'));
 5332: 
 5333:     my (%checkedon,%checkedoff,$datatable,$css_class);
 5334: 
 5335:     foreach my $item (@{$toggles}) {
 5336:         if ($defaultchecked->{$item} eq 'on') {
 5337:             $checkedon{$item} = ' checked="checked" ';
 5338:             $checkedoff{$item} = ' ';
 5339:         } elsif ($defaultchecked->{$item} eq 'off') {
 5340:             $checkedoff{$item} = ' checked="checked" ';
 5341:             $checkedon{$item} = ' ';
 5342:         }
 5343:     }
 5344:     if (ref($settings) eq 'HASH') {
 5345:         foreach my $item (@{$toggles}) {
 5346:             if ($settings->{$item} eq '1') {
 5347:                 $checkedon{$item} =  ' checked="checked" ';
 5348:                 $checkedoff{$item} = ' ';
 5349:             } elsif ($settings->{$item} eq '0') {
 5350:                 $checkedoff{$item} =  ' checked="checked" ';
 5351:                 $checkedon{$item} = ' ';
 5352:             }
 5353:         }
 5354:     }
 5355:     if ($onclick) {
 5356:         $onclick = ' onclick="'.$onclick.'"';
 5357:     }
 5358:     foreach my $item (@{$toggles}) {
 5359:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5360:         $datatable .=
 5361:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 5362:             '<span class="LC_nobreak">'.$choices->{$item}.
 5363:             '</span></td>';
 5364:         if ($align eq 'left') {
 5365:             $datatable .= '<td class="LC_left_item">';
 5366:         } else {
 5367:             $datatable .= '<td class="LC_right_item">';
 5368:         }
 5369:         $datatable .= '<span class="LC_nobreak">';
 5370:         if ($firstval eq 'no') {
 5371:             $datatable .=
 5372:                 '<label><input type="radio" name="'.
 5373:                 $item.'" '.$checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').
 5374:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 5375:                 $checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').'</label>';
 5376:         } else {
 5377:             $datatable .=
 5378:                 '<label><input type="radio" name="'.
 5379:                 $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 5380:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 5381:                 $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>';
 5382:         }
 5383:         $datatable .= '</span>'.$additional.'</td></tr>';
 5384:         $itemcount ++;
 5385:     }
 5386:     return ($datatable,$itemcount);
 5387: }
 5388: 
 5389: sub print_ltitools {
 5390:     my ($dom,$settings,$rowtotal) = @_;
 5391:     my $rownum = 0;
 5392:     my $css_class;
 5393:     my $itemcount = 1;
 5394:     my $maxnum = 0;
 5395:     my %ordered;
 5396:     if (ref($settings) eq 'HASH') {
 5397:         foreach my $item (keys(%{$settings})) {
 5398:             if (ref($settings->{$item}) eq 'HASH') {
 5399:                 my $num = $settings->{$item}{'order'};
 5400:                 $ordered{$num} = $item;
 5401:             }
 5402:         }
 5403:     }
 5404:     my $confname = $dom.'-domainconfig';
 5405:     my $switchserver = &check_switchserver($dom,$confname);
 5406:     my $maxnum = scalar(keys(%ordered));
 5407:     my $datatable;
 5408:     my %lt = &ltitools_names();
 5409:     my @courseroles = ('cc','in','ta','ep','st');
 5410:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
 5411:     my @fields = ('fullname','firstname','lastname','email','roles','user');
 5412:     if (keys(%ordered)) {
 5413:         my @items = sort { $a <=> $b } keys(%ordered);
 5414:         for (my $i=0; $i<@items; $i++) {
 5415:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5416:             my $item = $ordered{$items[$i]};
 5417:             my ($title,$key,$secret,$url,$lifetime,$imgsrc,%sigsel);
 5418:             if (ref($settings->{$item}) eq 'HASH') {
 5419:                 $title = $settings->{$item}->{'title'};
 5420:                 $url = $settings->{$item}->{'url'};
 5421:                 $key = $settings->{$item}->{'key'};
 5422:                 $secret = $settings->{$item}->{'secret'};
 5423:                 $lifetime = $settings->{$item}->{'lifetime'};
 5424:                 my $image = $settings->{$item}->{'image'};
 5425:                 if ($image ne '') {
 5426:                     $imgsrc = '<img src="'.$image.'" alt="'.&mt('Tool Provider icon').'" />';
 5427:                 }
 5428:                 if ($settings->{$item}->{'sigmethod'} eq 'HMAC-256') {
 5429:                     $sigsel{'HMAC-256'} = ' selected="selected"';
 5430:                 } else {
 5431:                     $sigsel{'HMAC-SHA1'} = ' selected="selected"';
 5432:                 }
 5433:             }
 5434:             my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_".$item."'".');"';
 5435:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5436:                          .'<select name="ltitools_'.$item.'"'.$chgstr.'>';
 5437:             for (my $k=0; $k<=$maxnum; $k++) {
 5438:                 my $vpos = $k+1;
 5439:                 my $selstr;
 5440:                 if ($k == $i) {
 5441:                     $selstr = ' selected="selected" ';
 5442:                 }
 5443:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5444:             }
 5445:             $datatable .= '</select>'.('&nbsp;'x2).
 5446:                 '<label><input type="checkbox" name="ltitools_del" value="'.$item.'" />'.
 5447:                 &mt('Delete?').'</label></span></td>'.
 5448:                 '<td colspan="2">'.
 5449:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5450:                 '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_title_'.$i.'" value="'.$title.'" /></span> '.
 5451:                 ('&nbsp;'x2).
 5452:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_version_'.$i.'">'.
 5453:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 5454:                 ('&nbsp;'x2).
 5455:                 '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_msgtype_'.$i.'">'.
 5456:                 '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 5457:                 ('&nbsp;'x2).
 5458:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_sigmethod_'.$i.'">'.
 5459:                 '<option value="HMAC-SHA1"'.$sigsel{'HMAC-SHA1'}.'>HMAC-SHA1</option>'.
 5460:                 '<option value="HMAC-SHA256"'.$sigsel{'HMAC-SHA256'}.'>HMAC-SHA256</option></select></span>'.
 5461:                 '<br /><br />'.
 5462:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_url_'.$i.'"'.
 5463:                 ' value="'.$url.'" /></span>'.
 5464:                 ('&nbsp;'x2).
 5465:                 '<span class="LC_nobreak">'.$lt{'key'}.':'.
 5466:                 '<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" /></span> '.
 5467:                 ('&nbsp;'x2).
 5468:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':'.
 5469:                 '<input type="text" size="5" name="ltitools_lifetime_'.$i.'" value="'.$lifetime.'" /></span> '.
 5470:                 ('&nbsp;'x2).
 5471:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 5472:                 '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="'.$secret.'" />'.
 5473:                 '<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>'.
 5474:                 '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span>'.
 5475:                 '</fieldset>'.
 5476:                 '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 5477:                 '<span class="LC_nobreak">'.&mt('Display target:');
 5478:             my %currdisp;
 5479:             if (ref($settings->{$item}->{'display'}) eq 'HASH') {
 5480:                 if ($settings->{$item}->{'display'}->{'target'} eq 'window') {
 5481:                     $currdisp{'window'} = ' checked="checked"';
 5482:                 } elsif ($settings->{$item}->{'display'}->{'target'} eq 'tab') {
 5483:                     $currdisp{'tab'} = ' checked="checked"';
 5484:                 } else {
 5485:                     $currdisp{'iframe'} = ' checked="checked"';
 5486:                 }
 5487:                 if ($settings->{$item}->{'display'}->{'width'} =~ /^(\d+)$/) {
 5488:                     $currdisp{'width'} = $1;
 5489:                 }
 5490:                 if ($settings->{$item}->{'display'}->{'height'} =~ /^(\d+)$/) {
 5491:                      $currdisp{'height'} = $1;
 5492:                 }
 5493:                 $currdisp{'linktext'} = $settings->{$item}->{'display'}->{'linktext'};
 5494:                 $currdisp{'explanation'} = $settings->{$item}->{'display'}->{'explanation'};
 5495:             } else {
 5496:                 $currdisp{'iframe'} = ' checked="checked"';
 5497:             }
 5498:             foreach my $disp ('iframe','tab','window') {
 5499:                 $datatable .= '<label><input type="radio" name="ltitools_target_'.$i.'" value="'.$disp.'"'.$currdisp{$disp}.' />'.
 5500:                               $lt{$disp}.'</label>'.('&nbsp;'x2);
 5501:             }
 5502:             $datatable .= ('&nbsp;'x4);
 5503:             foreach my $dimen ('width','height') {
 5504:                 $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 5505:                               '<input type="text" name="ltitools_'.$dimen.'_'.$i.'" size="5" value="'.$currdisp{$dimen}.'" /></label>'.
 5506:                               ('&nbsp;'x2);
 5507:             }
 5508:             $datatable .= '</span><br />'.
 5509:                           '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 5510:                           '<input type="text" name="ltitools_linktext_'.$i.'" size="25" value="'.$currdisp{'linktext'}.'" /></div>'.
 5511:                           '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 5512:                           '<textarea name="ltitools_explanation_'.$i.'" rows="5" cols="40">'.$currdisp{'explanation'}.
 5513:                           '</textarea></div><div style=""></div><br />';
 5514:             my %units = (
 5515:                           'passback' => 'days',
 5516:                           'roster'   => 'seconds',
 5517:                         );
 5518:             foreach my $extra ('passback','roster') {
 5519:                 my $validsty = 'none';
 5520:                 my $currvalid;
 5521:                 my $checkedon = '';
 5522:                 my $checkedoff = ' checked="checked"';
 5523:                 if ($settings->{$item}->{$extra}) {
 5524:                     $checkedon = $checkedoff;
 5525:                     $checkedoff = '';
 5526:                     $validsty = 'inline-block';
 5527:                     if ($settings->{$item}->{$extra.'valid'} =~ /^\d+\.?\d*$/) {
 5528:                         $currvalid = $settings->{$item}->{$extra.'valid'};
 5529:                     }
 5530:                 }
 5531:                 my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','$i'".');"';
 5532:                 $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 5533:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="0"'.$checkedoff.$onclick.' />'.
 5534:                               &mt('No').'</label>'.('&nbsp;'x2).
 5535:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="1"'.$checkedon.$onclick.' />'.
 5536:                               &mt('Yes').'</label></span></div>'.
 5537:                               '<div class="LC_floatleft" style="display:'.$validsty.';" id="ltitools_'.$extra.'time_'.$i.'">'.
 5538:                               '<span class="LC_nobreak">'.
 5539:                               &mt("at least [_1] $units{$extra} after launch",
 5540:                                   '<input type="text" name="ltitools_'.$extra.'valid_'.$i.'" value="'.$currvalid.'" />').
 5541:                               '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 5542:             }
 5543:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 5544:             if ($imgsrc) {
 5545:                 $datatable .= $imgsrc.
 5546:                               '<label><input type="checkbox" name="ltitools_image_del"'.
 5547:                               ' value="'.$item.'" />'.&mt('Delete?').'</label></span> '.
 5548:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 5549:             } else {
 5550:                 $datatable .= '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 5551:             }
 5552:             if ($switchserver) {
 5553:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5554:             } else {
 5555:                 $datatable .= '<input type="file" name="ltitools_image_'.$i.'" value="" />';
 5556:             }
 5557:             $datatable .= '</span></fieldset>';
 5558:             my (%checkedfields,%rolemaps,$userincdom);
 5559:             if (ref($settings->{$item}) eq 'HASH') {
 5560:                 if (ref($settings->{$item}->{'fields'}) eq 'HASH') {
 5561:                     %checkedfields = %{$settings->{$item}->{'fields'}};
 5562:                 }
 5563:                 $userincdom = $settings->{$item}->{'incdom'};
 5564:                 if (ref($settings->{$item}->{'roles'}) eq 'HASH') {
 5565:                     %rolemaps = %{$settings->{$item}->{'roles'}};
 5566:                     $checkedfields{'roles'} = 1;
 5567:                 }
 5568:             }
 5569:             $datatable .= '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 5570:                           '<span class="LC_nobreak">';
 5571:             my $userfieldstyle = 'display:none;';
 5572:             my $seluserdom = '';
 5573:             my $unseluserdom = ' selected="selected"';
 5574:             foreach my $field (@fields) {
 5575:                 my ($checked,$onclick,$id,$spacer);
 5576:                 if ($checkedfields{$field}) {
 5577:                     $checked = ' checked="checked"';
 5578:                 }
 5579:                 if ($field eq 'user') {
 5580:                     $id = ' id="ltitools_user_field_'.$i.'"';
 5581:                     $onclick = ' onclick="toggleLTITools(this.form,'."'$field','$i'".')"';
 5582:                     if ($checked) {
 5583:                         $userfieldstyle = 'display:inline-block';
 5584:                         if ($userincdom) {
 5585:                             $seluserdom = $unseluserdom;
 5586:                             $unseluserdom = '';
 5587:                         }
 5588:                     }
 5589:                 } else {
 5590:                     $spacer = ('&nbsp;' x2);
 5591:                 }
 5592:                 $datatable .= '<label>'.
 5593:                               '<input type="checkbox" name="ltitools_fields_'.$i.'" value="'.$field.'"'.$id.$checked.$onclick.' />'.
 5594:                               $lt{$field}.'</label>'.$spacer;
 5595:             }
 5596:             $datatable .= '</span>';
 5597:             $datatable .= '<div style="'.$userfieldstyle.'" id="ltitools_user_div_'.$i.'">'.
 5598:                           '<span class="LC_nobreak"> : '.
 5599:                           '<select name="ltitools_userincdom_'.$i.'">'.
 5600:                           '<option value="">'.&mt('Select').'</option>'.
 5601:                           '<option value="0"'.$unseluserdom.'>'.&mt('username').'</option>'.
 5602:                           '<option value="1"'.$seluserdom.'>'.&mt('username:domain').'</option>'.
 5603:                           '</select></span></div>';
 5604:             $datatable .= '</fieldset>'.
 5605:                           '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 5606:             foreach my $role (@courseroles) {
 5607:                 my ($selected,$selectnone);
 5608:                 if (!$rolemaps{$role}) {
 5609:                     $selectnone = ' selected="selected"';
 5610:                 }
 5611:                 $datatable .= '<td style="text-align: center">'. 
 5612:                               &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5613:                               '<select name="ltitools_roles_'.$role.'_'.$i.'">'.
 5614:                               '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 5615:                 foreach my $ltirole (@ltiroles) {
 5616:                     unless ($selectnone) {
 5617:                         if ($rolemaps{$role} eq $ltirole) {
 5618:                             $selected = ' selected="selected"';
 5619:                         } else {
 5620:                             $selected = '';
 5621:                         }
 5622:                     }
 5623:                     $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 5624:                 }
 5625:                 $datatable .= '</select></td>';
 5626:             }
 5627:             $datatable .= '</tr></table></fieldset>';
 5628:             my %courseconfig;
 5629:             if (ref($settings->{$item}) eq 'HASH') {
 5630:                 if (ref($settings->{$item}->{'crsconf'}) eq 'HASH') {
 5631:                     %courseconfig = %{$settings->{$item}->{'crsconf'}};
 5632:                 }
 5633:             }
 5634:             $datatable .= '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 5635:             foreach my $item ('label','title','target','linktext','explanation','append') {
 5636:                 my $checked;
 5637:                 if ($courseconfig{$item}) {
 5638:                     $checked = ' checked="checked"';
 5639:                 }
 5640:                 $datatable .= '<label>'.
 5641:                        '<input type="checkbox" name="ltitools_courseconfig_'.$i.'" value="'.$item.'"'.$checked.' />'.
 5642:                        $lt{'crs'.$item}.'</label>&nbsp; '."\n";
 5643:             }
 5644:             $datatable .= '</span></fieldset>'.
 5645:                           '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 5646:                           '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>';
 5647:             if (ref($settings->{$item}->{'custom'}) eq 'HASH') {
 5648:                 my %custom = %{$settings->{$item}->{'custom'}};
 5649:                 if (keys(%custom) > 0) {
 5650:                     foreach my $key (sort(keys(%custom))) {
 5651:                         $datatable .= '<tr><td><span class="LC_nobreak">'.
 5652:                                       '<label><input type="checkbox" name="ltitools_customdel_'.$i.'" value="'.
 5653:                                       $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 5654:                                       '<td><input type="text" name="ltitools_customval_'.$key.'_'.$i.'"'.
 5655:                                       ' value="'.$custom{$key}.'" /></td></tr>';
 5656:                     }
 5657:                 }
 5658:             }
 5659:             $datatable .= '<tr><td><span class="LC_nobreak">'.
 5660:                           '<label><input type="checkbox" name="ltitools_customadd" value="'.$i.'" />'.
 5661:                           &mt('Add').'</label></span></td><td><input type="text" name="ltitools_custom_name_'.$i.'" />'.
 5662:                           '</td><td><input type="text" name="ltitools_custom_value_'.$i.'" /></td></tr>';
 5663:             $datatable .= '</table></fieldset></td></tr>'."\n";
 5664:             $itemcount ++;
 5665:         }
 5666:     }
 5667:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5668:     my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_add_pos'".');"';
 5669:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 5670:                   '<input type="hidden" name="ltitools_maxnum" value="'.$maxnum.'" />'."\n".
 5671:                   '<select name="ltitools_add_pos"'.$chgstr.'>';
 5672:     for (my $k=0; $k<$maxnum+1; $k++) {
 5673:         my $vpos = $k+1;
 5674:         my $selstr;
 5675:         if ($k == $maxnum) {
 5676:             $selstr = ' selected="selected" ';
 5677:         }
 5678:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5679:     }
 5680:     $datatable .= '</select>&nbsp;'."\n".
 5681:                   '<input type="checkbox" name="ltitools_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 5682:                   '<td colspan="2">'.
 5683:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5684:                   '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_add_title" value="" /></span> '."\n".
 5685:                   ('&nbsp;'x2).
 5686:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_add_version">'.
 5687:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 5688:                   ('&nbsp;'x2).
 5689:                   '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_add_msgtype">'.
 5690:                   '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 5691:                   '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_add_sigmethod">'.
 5692:                   '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 5693:                   '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 5694:                   '<br />'.
 5695:                   '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_add_url" value="" /></span> '."\n".
 5696:                   ('&nbsp;'x2).
 5697:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="ltitools_add_key" value="" /></span> '."\n".
 5698:                   ('&nbsp;'x2).
 5699:                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="ltitools_add_lifetime" value="300" /></span> '."\n".
 5700:                   ('&nbsp;'x2).
 5701:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="ltitools_add_secret" value="" />'.
 5702:                   '<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".
 5703:                   '</fieldset>'.
 5704:                   '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 5705:                   '<span class="LC_nobreak">'.&mt('Display target:');
 5706:     my %defaultdisp;
 5707:     $defaultdisp{'iframe'} = ' checked="checked"';
 5708:     foreach my $disp ('iframe','tab','window') {
 5709:         $datatable .= '<label><input type="radio" name="ltitools_add_target" value="'.$disp.'"'.$defaultdisp{$disp}.' />'.
 5710:                       $lt{$disp}.'</label>'.('&nbsp;'x2);
 5711:     }
 5712:     $datatable .= ('&nbsp;'x4);
 5713:     foreach my $dimen ('width','height') {
 5714:         $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 5715:                       '<input type="text" name="ltitools_add_'.$dimen.'" size="5" /></label>'.
 5716:                       ('&nbsp;'x2);
 5717:     }
 5718:     $datatable .= '</span><br />'.
 5719:                   '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 5720:                   '<input type="text" name="ltitools_add_linktext" size="5" /></div>'.
 5721:                   '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 5722:                   '<textarea name="ltitools_add_explanation" rows="5" cols="40"></textarea>'.
 5723:                   '</div><div style=""></div><br />';
 5724:     my %units = (
 5725:                   'passback' => 'days',
 5726:                   'roster'   => 'seconds',
 5727:                 );
 5728:     my %defaulttimes = (
 5729:                      'passback' => '7',
 5730:                      'roster'   => '300',
 5731:                    );
 5732:     foreach my $extra ('passback','roster') {
 5733:         my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','add'".');"';
 5734:         $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 5735:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="0" checked="checked"'.$onclick.' />'.
 5736:                       &mt('No').'</label></span>'.('&nbsp;'x2).'<span class="LC_nobreak">'.
 5737:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="1"'.$onclick.' />'.
 5738:                       &mt('Yes').'</label></span></div>'.
 5739:                       '<div class="LC_floatleft" style="display:none;" id="ltitools_'.$extra.'time_add">'.
 5740:                       '<span class="LC_nobreak">'.
 5741:                       &mt("at least [_1] $units{$extra} after launch",
 5742:                           '<input type="text" name="ltitools_'.$extra.'valid_add" value="'.$defaulttimes{$extra}.'" />').
 5743:                       '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 5744:     }
 5745:     $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;'.
 5746:                   '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 5747:     if ($switchserver) {
 5748:         $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5749:     } else {
 5750:         $datatable .= '<input type="file" name="ltitools_add_image" value="" />';
 5751:     }
 5752:     $datatable .= '</span></fieldset>'.
 5753:                   '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 5754:                   '<span class="LC_nobreak">';
 5755:     foreach my $field (@fields) {
 5756:         my ($id,$onclick,$spacer);
 5757:         if ($field eq 'user') {
 5758:             $id = ' id="ltitools_user_field_add"';
 5759:             $onclick = ' onclick="toggleLTITools(this.form,'."'$field','add'".')"';
 5760:         } else {
 5761:             $spacer = ('&nbsp;' x2);
 5762:         }
 5763:         $datatable .= '<label>'.
 5764:                       '<input type="checkbox" name="ltitools_add_fields" value="'.$field.'"'.$id.$onclick.' />'.
 5765:                       $lt{$field}.'</label>'.$spacer;
 5766:     }
 5767:     $datatable .= '</span>'.
 5768:                   '<div style="display:none;" id="ltitools_user_div_add">'.
 5769:                   '<span class="LC_nobreak"> : '.
 5770:                   '<select name="ltitools_userincdom_add">'.
 5771:                   '<option value="" selected="selected">'.&mt('Select').'</option>'.
 5772:                   '<option value="0">'.&mt('username').'</option>'.
 5773:                   '<option value="1">'.&mt('username:domain').'</option>'.
 5774:                   '</select></span></div></fieldset>';
 5775:     $datatable .= '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 5776:     foreach my $role (@courseroles) {
 5777:         my ($checked,$checkednone);
 5778:         $datatable .= '<td style="text-align: center">'.
 5779:                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5780:                       '<select name="ltitools_add_roles_'.$role.'">'.
 5781:                       '<option value="" selected="selected">'.&mt('Select').'</option>';
 5782:         foreach my $ltirole (@ltiroles) {
 5783:             $datatable .= '<option value="'.$ltirole.'">'.$ltirole.'</option>';
 5784:         }
 5785:         $datatable .= '</select></td>';
 5786:     }
 5787:     $datatable .= '</tr></table></fieldset>'.
 5788:                   '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 5789:     foreach my $item ('label','title','target','linktext','explanation','append') {
 5790:         $datatable .= '<label>'.
 5791:                       '<input type="checkbox" name="ltitools_courseconfig" value="'.$item.'" checked="checked" />'.
 5792:                       $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 5793:     }
 5794:     $datatable .= '</span></fieldset>'.
 5795:                   '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 5796:                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 5797:                   '<tr><td><span class="LC_nobreak">'.
 5798:                   '<label><input type="checkbox" name="ltitools_add_custom" value="1" />'.
 5799:                   &mt('Add').'</label></span></td><td><input type="text" name="ltitools_add_custom_name" />'.
 5800:                   '</td><td><input type="text" name="ltitools_add_custom_value" /></td></tr>'.
 5801:                   '</table></fieldset>'."\n".
 5802:                   '</td>'."\n".
 5803:                   '</tr>'."\n";
 5804:     $itemcount ++;
 5805:     return $datatable;
 5806: }
 5807: 
 5808: sub ltitools_names {
 5809:     my %lt = &Apache::lonlocal::texthash(
 5810:                                           'title'          => 'Title',
 5811:                                           'version'        => 'Version',
 5812:                                           'msgtype'        => 'Message Type',
 5813:                                           'sigmethod'      => 'Signature Method',
 5814:                                           'url'            => 'URL',
 5815:                                           'key'            => 'Key',
 5816:                                           'lifetime'       => 'Nonce lifetime (s)',
 5817:                                           'secret'         => 'Secret',
 5818:                                           'icon'           => 'Icon',   
 5819:                                           'user'           => 'User',
 5820:                                           'fullname'       => 'Full Name',
 5821:                                           'firstname'      => 'First Name',
 5822:                                           'lastname'       => 'Last Name',
 5823:                                           'email'          => 'E-mail',
 5824:                                           'roles'          => 'Role',
 5825:                                           'window'         => 'Window',
 5826:                                           'tab'            => 'Tab',
 5827:                                           'iframe'         => 'iFrame',
 5828:                                           'height'         => 'Height',
 5829:                                           'width'          => 'Width',
 5830:                                           'linktext'       => 'Default Link Text',
 5831:                                           'explanation'    => 'Default Explanation',
 5832:                                           'passback'       => 'Tool can return grades:',
 5833:                                           'roster'         => 'Tool can retrieve roster:',
 5834:                                           'crstarget'      => 'Display target',
 5835:                                           'crslabel'       => 'Course label',
 5836:                                           'crstitle'       => 'Course title', 
 5837:                                           'crslinktext'    => 'Link Text',
 5838:                                           'crsexplanation' => 'Explanation',
 5839:                                           'crsappend'      => 'Provider URL',
 5840:                                         );
 5841:     return %lt;
 5842: }
 5843: 
 5844: sub print_proctoring {
 5845:     my ($dom,$settings,$rowtotal) = @_;
 5846:     my $itemcount = 1;
 5847:     my (%ordered,%providernames,%current,%currentdef);
 5848:     my $confname = $dom.'-domainconfig';
 5849:     my $switchserver = &check_switchserver($dom,$confname);
 5850:     if (ref($settings) eq 'HASH') {
 5851:         foreach my $item (keys(%{$settings})) {
 5852:             if (ref($settings->{$item}) eq 'HASH') {
 5853:                 my $num = $settings->{$item}{'order'};
 5854:                 $ordered{$num} = $item;
 5855:             }
 5856:         }
 5857:     } else {
 5858:         %ordered = (
 5859:                      1 => 'proctorio',
 5860:                      2 => 'examity',
 5861:                    );
 5862:     }
 5863:     %providernames = &proctoring_providernames();
 5864:     my $maxnum = scalar(keys(%ordered));
 5865:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
 5866:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
 5867:     if (ref($requref) eq 'HASH') {
 5868:         %requserfields = %{$requref};
 5869:     }
 5870:     if (ref($opturef) eq 'HASH') {
 5871:         %optuserfields = %{$opturef};
 5872:     }
 5873:     if (ref($defref) eq 'HASH') {
 5874:         %defaults = %{$defref};
 5875:     }
 5876:     if (ref($extref) eq 'HASH') {
 5877:         %extended = %{$extref};
 5878:     }
 5879:     if (ref($crsref) eq 'HASH') {
 5880:         %crsconf = %{$crsref};
 5881:     }
 5882:     if (ref($rolesref) eq 'ARRAY') {
 5883:         @courseroles = @{$rolesref};
 5884:     }
 5885:     if (ref($ltiref) eq 'ARRAY') {
 5886:         @ltiroles = @{$ltiref};
 5887:     }
 5888:     my $datatable;
 5889:     my $css_class;
 5890:     if (keys(%ordered)) {
 5891:         my @items = sort { $a <=> $b } keys(%ordered);
 5892:         for (my $i=0; $i<@items; $i++) {
 5893:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5894:             my $provider = $ordered{$items[$i]};
 5895:             my $optionsty = 'none';
 5896:             my ($available,$version,$lifetime,$imgsrc,$userincdom,$showroles,
 5897:                 %checkedfields,%rolemaps,%inuse,%crsconfig,%current);
 5898:             if (ref($settings) eq 'HASH') {
 5899:                 if (ref($settings->{$provider}) eq 'HASH') {
 5900:                     %current = %{$settings->{$provider}};
 5901:                     if ($current{'available'}) {
 5902:                         $optionsty = 'block';
 5903:                         $available = 1;
 5904:                     }
 5905:                     if ($current{'lifetime'} =~ /^\d+$/) {
 5906:                         $lifetime = $current{'lifetime'};
 5907:                     }
 5908:                     if ($current{'version'} =~ /^\d+\.\d+$/) {
 5909:                         $version = $current{'version'};
 5910:                     }
 5911:                     if ($current{'image'} ne '') {
 5912:                         $imgsrc = '<img src="'.$current{'image'}.'" alt="'.&mt('Proctoring service icon').'" />';
 5913:                     }
 5914:                     if (ref($current{'fields'}) eq 'ARRAY') {
 5915:                         map { $checkedfields{$_} = 1; } @{$current{'fields'}};
 5916:                     }
 5917:                     $userincdom = $current{'incdom'};
 5918:                     if (ref($current{'roles'}) eq 'HASH') {
 5919:                         %rolemaps = %{$current{'roles'}};
 5920:                         $checkedfields{'roles'} = 1;
 5921:                     }
 5922:                     if (ref($current{'defaults'}) eq 'ARRAY') {
 5923:                         foreach my $val (@{$current{'defaults'}}) {
 5924:                             if (grep(/^\Q$val\E$/,@{$defaults{$provider}})) {
 5925:                                 $inuse{$val} = 1;
 5926:                             } else {
 5927:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5928:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5929:                                         if (grep(/^\Q$val\E$/,@{$extended{$provider}{$poss}})) {
 5930:                                             $inuse{$poss} = $val;
 5931:                                             last;
 5932:                                         }
 5933:                                     }
 5934:                                 }
 5935:                             }
 5936:                         }
 5937:                     } elsif (ref($current{'defaults'}) eq 'HASH') {
 5938:                         foreach my $key (keys(%{$current{'defaults'}})) {
 5939:                             my $currval = $current{'defaults'}{$key}; 
 5940:                             if (grep(/^\Q$key\E$/,@{$defaults{$provider}})) {
 5941:                                 $inuse{$key} = 1;
 5942:                             } else {
 5943:                                 my $match;
 5944:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5945:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5946:                                         if (grep(/^\Q$key\E$/,@{$extended{$provider}{$poss}})) {
 5947:                                             $inuse{$poss} = $key;
 5948:                                             last;
 5949:                                         }
 5950:                                     } elsif (ref($extended{$provider}{$poss}) eq 'HASH') {
 5951:                                         foreach my $inner (sort(keys(%{$extended{$provider}{$poss}}))) {
 5952:                                             if (ref($extended{$provider}{$poss}{$inner}) eq 'ARRAY') {
 5953:                                                 if (grep(/^\Q$currval\E$/,@{$extended{$provider}{$poss}{$inner}})) {
 5954:                                                     $currentdef{$inner} = $currval;
 5955:                                                     $match = 1;
 5956:                                                     last;
 5957:                                                 }
 5958:                                             } elsif ($inner eq $key) {
 5959:                                                 $currentdef{$key} = $currval;
 5960:                                                 $match = 1;
 5961:                                                 last;
 5962:                                             }
 5963:                                         }
 5964:                                     }
 5965:                                     last if ($match);
 5966:                                 }
 5967:                             }
 5968:                         }
 5969:                     }
 5970:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
 5971:                         map { $crsconfig{$_} = 1; } @{$current{'crsconf'}};
 5972:                     }
 5973:                 }
 5974:             }
 5975:             my %lt = &proctoring_titles($provider);
 5976:             my %fieldtitles = &proctoring_fieldtitles($provider);
 5977:             my $onclickavailable = ' onclick="toggleProctoring(this.form,'."'$provider'".');"';
 5978:             my %checkedavailable = (
 5979:                                    yes => '',
 5980:                                    no  => ' checked="checked"',
 5981:                                  );
 5982:             if ($available) {
 5983:                 $checkedavailable{'yes'} = $checkedavailable{'no'};
 5984:                 $checkedavailable{'no'} = '';
 5985:             }
 5986:             my $chgstr = ' onchange="javascript:reorderProctoring(this.form,'."'proctoring_pos_".$provider."'".');"';
 5987:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5988:                          .'<select name="proctoring_pos_'.$provider.'"'.$chgstr.'>';
 5989:             for (my $k=0; $k<$maxnum; $k++) {
 5990:                 my $vpos = $k+1;
 5991:                 my $selstr;
 5992:                 if ($k == $i) {
 5993:                     $selstr = ' selected="selected" ';
 5994:                 }
 5995:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5996:             }
 5997:             if ($version eq '') {
 5998:                 if ($provider eq 'proctorio') {
 5999:                     $version = '1.0';
 6000:                 } elsif ($provider eq 'examity') {
 6001:                     $version = '1.1';
 6002:                 }
 6003:             }
 6004:             if ($lifetime eq '') {
 6005:                 $lifetime = '300';
 6006:             }
 6007:             $datatable .=
 6008:                 '</select>'.('&nbsp;'x2).'<b>'.$providernames{$provider}.'</b></span><br />'.
 6009:                 '<span class="LC_nobreak">'.$lt{'avai'}.'&nbsp;'.
 6010:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="1"'.$onclickavailable.$checkedavailable{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 6011:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="0"'.$onclickavailable.$checkedavailable{no}.' />'.&mt('No').'</label></span>'."\n".
 6012:                 '</td>'.
 6013:                 '<td colspan="2">'.
 6014:                 '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'base'}.'</legend>'.
 6015:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="proctoring_'.$provider.'_version">'.
 6016:                 '<option value="'.$version.'" selected="selected">'.$version.'</option></select></span> '."\n".
 6017:                 ('&nbsp;'x2).
 6018:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="proctoring_'.$provider.'_sigmethod">'.
 6019:                 '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 6020:                 '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 6021:                 ('&nbsp;'x2).
 6022:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="proctoring_'.$provider.'_lifetime" value="'.$lifetime.'" /></span> '."\n".
 6023:                 '<br />'.
 6024:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="proctoring_'.$provider.'_url" value="'.$current{'url'}.'" /></span> '."\n".
 6025:                 '<br />'.
 6026:                 '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="proctoring_'.$provider.'_key" value="'.$current{'key'}.'" /></span> '."\n".
 6027:                 ('&nbsp;'x2).
 6028:                 '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="proctoring_'.$provider.'_secret" value="'.$current{'secret'}.'" />'.
 6029:                 '<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";
 6030:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 6031:             if ($imgsrc) {
 6032:                 $datatable .= $imgsrc.
 6033:                               '<label><input type="checkbox" name="proctoring_image_del"'.
 6034:                               ' value="'.$provider.'" />'.&mt('Delete?').'</label></span> '.
 6035:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:');
 6036:             }
 6037:             $datatable .= '&nbsp;';
 6038:             if ($switchserver) {
 6039:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 6040:             } else {
 6041:                 $datatable .= '<input type="file" name="proctoring_image_'.$provider.'" value="" />';
 6042:             }
 6043:             unless ($imgsrc) {
 6044:                 $datatable .= '<br />('.&mt('if larger than 21x21 pixels, image will be scaled').')';
 6045:             }
 6046:             $datatable .= '</fieldset>'."\n";
 6047:             if (ref($requserfields{$provider}) eq 'ARRAY') {
 6048:                 if (@{$requserfields{$provider}} > 0) {
 6049:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'requ'}.'</legend>';
 6050:                     foreach my $field (@{$requserfields{$provider}}) {
 6051:                         $datatable .= '<span class="LC_nobreak">'.
 6052:                                       '<label><input type="checkbox" name="proctoring_reqd_'.$provider.'" value="'.$field.'" checked="checked" disabled="disabled" />'.
 6053:                                       $lt{$field}.'</label>';
 6054:                         if ($field eq 'user') {
 6055:                             my $seluserdom = '';
 6056:                             my $unseluserdom = ' selected="selected"';
 6057:                             if ($userincdom) {
 6058:                                 $seluserdom = $unseluserdom;
 6059:                                 $unseluserdom = '';
 6060:                             }
 6061:                             $datatable .= ':&nbsp;'.
 6062:                                 '<select name="proctoring_userincdom_'.$provider.'">'.
 6063:                                 '<option value="0"'.$unseluserdom.'>'.$lt{'username'}.'</option>'.
 6064:                                 '<option value="1"'.$seluserdom.'>'.$lt{'uname:dom'}.'</option>'.
 6065:                                 '</select>&nbsp;';
 6066:                         } else {
 6067:                             $datatable .= '&nbsp;';
 6068:                             if ($field eq 'roles') {
 6069:                                 $showroles = 1; 
 6070:                             } 
 6071:                         }
 6072:                         $datatable .= '</span> ';
 6073:                     }
 6074:                 }
 6075:                 $datatable .= '</fieldset>'."\n";
 6076:             }
 6077:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
 6078:                 if (@{$optuserfields{$provider}} > 0) {
 6079:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'optu'}.'</legend>'; 
 6080:                     foreach my $field (@{$optuserfields{$provider}}) {
 6081:                         my $checked;
 6082:                         if ($checkedfields{$field}) {
 6083:                             $checked = ' checked="checked"';
 6084:                         }
 6085:                         $datatable .= '<span class="LC_nobreak">'.
 6086:                                       '<label><input type="checkbox" name="proctoring_optional_'.$provider.'" value="'.$field.'"'.$checked.' />'.$lt{$field}.'</label></span>&nbsp; ';
 6087:                     }
 6088:                     $datatable .= '</fieldset>'."\n";
 6089:                 }
 6090:             }
 6091:             if (ref($defaults{$provider}) eq 'ARRAY') {
 6092:                 if (@{$defaults{$provider}}) {
 6093:                     my (%options,@selectboxes);
 6094:                     if (ref($extended{$provider}) eq 'HASH') {
 6095:                         %options = %{$extended{$provider}};
 6096:                     }
 6097:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'defa'}.'</legend>';
 6098:                     my ($rem,$numinrow,$dropdowns);
 6099:                     if ($provider eq 'proctorio') { 
 6100:                         $datatable .= '<table>';
 6101:                         $numinrow = 4;
 6102:                     }
 6103:                     my $i = 0;
 6104:                     foreach my $field (@{$defaults{$provider}}) {
 6105:                         my $checked;
 6106:                         if ($inuse{$field}) {
 6107:                             $checked = ' checked="checked"';
 6108:                         }
 6109:                         if ($provider eq 'examity') {
 6110:                             if ($field eq 'display') {
 6111:                                 $datatable .= '<span class="LC_nobreak">'.&mt('Display target:');
 6112:                                 foreach my $option ('iframe','tab','window') {
 6113:                                     my $checkdisp;
 6114:                                     if ($currentdef{'target'} eq $option) {
 6115:                                         $checkdisp = ' checked="checked"';
 6116:                                     }
 6117:                                     $datatable .= '<label><input type="radio" name="proctoring_target_'.$provider.'" value="'.$option.'"'.$checkdisp.' />'.
 6118:                                     $fieldtitles{$option}.'</label>'.('&nbsp;'x2);
 6119:                                 }
 6120:                                 $datatable .= ('&nbsp;'x4);
 6121:                                 foreach my $dimen ('width','height') {
 6122:                                     $datatable .= '<label>'.$fieldtitles{$dimen}.'&nbsp;'.
 6123:                                                   '<input type="text" name="proctoring_'.$dimen.'_'.$provider.'" size="5" '.
 6124:                                                   'value="'.$currentdef{$dimen}.'" /></label>'.
 6125:                                                   ('&nbsp;'x2);
 6126:                                 }
 6127:                                 $datatable .= '</span><br />'.
 6128:                                               '<div class="LC_left_float">'.$fieldtitles{'linktext'}.'<br />'.
 6129:                                               '<input type="text" name="proctoring_linktext_'.$provider.'" '.
 6130:                                               'size="25" value="'.$currentdef{'linktext'}.'" /></div>'.
 6131:                                               '<div class="LC_left_float">'.$fieldtitles{'explanation'}.'<br />'.
 6132:                                               '<textarea name="proctoring_explanation_'.$provider.'" rows="5" cols="40">'.
 6133:                                               $currentdef{'explanation'}.
 6134:                                               '</textarea></div><div style=""></div><br />';
 6135:                             }
 6136:                         } else {
 6137:                             if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
 6138:                                 my ($output,$selnone);
 6139:                                 unless ($checked) {
 6140:                                     $selnone = ' selected="selected"';
 6141:                                 }
 6142:                                 $output .= '<span class="LC_nobreak">'.$fieldtitles{$field}.': '.
 6143:                                            '<select name="proctoring_defaults_'.$field.'_'.$provider.'">'.
 6144:                                            '<option value=""'.$selnone.'>'.&mt('Not in use').'</option>'; 
 6145:                                 foreach my $option (@{$options{$field}}) {
 6146:                                     my $sel; 
 6147:                                     if ($inuse{$field} eq $option) {
 6148:                                         $sel = ' selected="selected"';
 6149:                                     }
 6150:                                     $output .= '<option value="'.$option.'"'.$sel.'>'.$fieldtitles{$option}.'</option>';
 6151:                                 }
 6152:                                 $output .= '</select></span>';
 6153:                                 push(@selectboxes,$output);
 6154:                             } else {
 6155:                                 $rem = $i%($numinrow);
 6156:                                 if ($rem == 0) {
 6157:                                     if ($i > 0) {
 6158:                                         $datatable .= '</tr>';
 6159:                                     }
 6160:                                     $datatable .= '<tr>';
 6161:                                 }
 6162:                                 $datatable .= '<td class="LC_left_item">'.
 6163:                                               '<span class="LC_nobreak">'.
 6164:                                               '<label><input type="checkbox" name="proctoring_defaults_'.$provider.'" value="'.$field.'"'.$checked.' />'.
 6165:                                               $fieldtitles{$field}.'</label></span></td>';
 6166:                                 $i++;
 6167:                             }
 6168:                         }
 6169:                     }
 6170:                     if ($provider eq 'proctorio') {
 6171:                         if ($numinrow) {
 6172:                             $rem = $i%$numinrow;
 6173:                         }
 6174:                         my $colsleft = $numinrow - $rem;
 6175:                         if ($colsleft > 1) {
 6176:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6177:                         } else {
 6178:                             $datatable .= '<td class="LC_left_item">';
 6179:                         }
 6180:                         $datatable .= '&nbsp;'.
 6181:                                       '</td></tr></table>';
 6182:                         if (@selectboxes) {
 6183:                             $datatable .= '<hr /><table>';
 6184:                             $numinrow = 2;
 6185:                             for (my $i=0; $i<@selectboxes; $i++) {
 6186:                                 $rem = $i%($numinrow);
 6187:                                 if ($rem == 0) {
 6188:                                     if ($i > 0) {
 6189:                                         $datatable .= '</tr>';
 6190:                                     }
 6191:                                     $datatable .= '<tr>';
 6192:                                 }
 6193:                                 $datatable .= '<td class="LC_left_item">'.
 6194:                                               $selectboxes[$i].'</td>';
 6195:                             }
 6196:                             if ($numinrow) {
 6197:                                 $rem = $i%$numinrow;
 6198:                             }
 6199:                             $colsleft = $numinrow - $rem;
 6200:                             if ($colsleft > 1) {
 6201:                                 $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6202:                             } else {
 6203:                                 $datatable .= '<td class="LC_left_item">';
 6204:                             }
 6205:                             $datatable .= '&nbsp;'.
 6206:                                           '</td></tr></table>';
 6207:                         }
 6208:                     }
 6209:                     $datatable .= '</fieldset>';
 6210:                 }
 6211:                 if (ref($crsconf{$provider}) eq 'ARRAY') {
 6212:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 6213:                                   '<legend>'.&mt('Configurable in course').'</legend>';
 6214:                     my ($rem,$numinrow);
 6215:                     if ($provider eq 'proctorio') {
 6216:                         $datatable .= '<table>';
 6217:                         $numinrow = 4;
 6218:                     }
 6219:                     my $i = 0;
 6220:                     foreach my $item (@{$crsconf{$provider}}) {
 6221:                         my $name;
 6222:                         if ($provider eq 'examity') {
 6223:                             $name = $lt{'crs'.$item};
 6224:                         } elsif ($provider eq 'proctorio') {
 6225:                             $name = $fieldtitles{$item};
 6226:                             $rem = $i%($numinrow);
 6227:                             if ($rem == 0) {
 6228:                                 if ($i > 0) {
 6229:                                     $datatable .= '</tr>';
 6230:                                 }
 6231:                                 $datatable .= '<tr>';
 6232:                             }
 6233:                             $datatable .= '<td class="LC_left_item>';
 6234:                         }
 6235:                         my $checked;
 6236:                         if ($crsconfig{$item}) {
 6237:                             $checked = ' checked="checked"';
 6238:                         }
 6239:                         $datatable .= '<span class="LC_nobreak"><label>'.
 6240:                                       '<input type="checkbox" name="proctoring_crsconf_'.$provider.'" value="'.$item.'"'.$checked.' />'.
 6241:                                       $name.'</label></span>';
 6242:                         if ($provider eq 'examity') {
 6243:                             $datatable .= '&nbsp; ';
 6244:                         }
 6245:                         $datatable .= "\n";
 6246:                         $i++;
 6247:                     }
 6248:                     if ($provider eq 'proctorio') {
 6249:                         if ($numinrow) {
 6250:                             $rem = $i%$numinrow;
 6251:                         }
 6252:                         my $colsleft = $numinrow - $rem;
 6253:                         if ($colsleft > 1) {
 6254:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6255:                         } else {
 6256:                             $datatable .= '<td class="LC_left_item">';
 6257:                         }
 6258:                         $datatable .= '&nbsp;'.
 6259:                                       '</td></tr></table>';
 6260:                     }
 6261:                     $datatable .= '</fieldset>';
 6262:                 }
 6263:                 if ($showroles) {
 6264:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 6265:                                   '<legend>'.&mt('Role mapping').'</legend><table><tr>';
 6266:                     foreach my $role (@courseroles) {
 6267:                         my ($selected,$selectnone);
 6268:                         if (!$rolemaps{$role}) {
 6269:                             $selectnone = ' selected="selected"';
 6270:                         }
 6271:                         $datatable .= '<td style="text-align: center">'.
 6272:                                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 6273:                                       '<select name="proctoring_roles_'.$role.'_'.$provider.'">'.
 6274:                                       '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 6275:                         foreach my $ltirole (@ltiroles) {
 6276:                             unless ($selectnone) {
 6277:                                 if ($rolemaps{$role} eq $ltirole) {
 6278:                                     $selected = ' selected="selected"';
 6279:                                 } else {
 6280:                                     $selected = '';
 6281:                                 }
 6282:                             }
 6283:                             $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 6284:                         }
 6285:                         $datatable .= '</select></td>';
 6286:                     }
 6287:                     $datatable .= '</tr></table></fieldset>'.
 6288:                                   '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 6289:                                   '<legend>'.&mt('Custom items sent on launch').'</legend>'.
 6290:                                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 6291:                                   '<tr><td></td><td>lms</td>'.
 6292:                                   '<td><input type="text" name="proctoring_customval_lms_'.$provider.'"'.
 6293:                                   ' value="Loncapa" disabled="disabled"/></td></tr>';
 6294:                     if ((ref($settings) eq 'HASH') && (ref($settings->{$provider}) eq 'HASH') &&
 6295:                         (ref($settings->{$provider}->{'custom'}) eq 'HASH')) {
 6296:                         my %custom = %{$settings->{$provider}->{'custom'}};
 6297:                         if (keys(%custom) > 0) {
 6298:                             foreach my $key (sort(keys(%custom))) {
 6299:                                 next if ($key eq 'lms');
 6300:                                 $datatable .= '<tr><td><span class="LC_nobreak">'.
 6301:                                               '<label><input type="checkbox" name="proctoring_customdel_'.$provider.'" value="'.
 6302:                                               $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 6303:                                               '<td><input type="text" name="proctoring_customval_'.$key.'_'.$provider.'"'.
 6304:                                               ' value="'.$custom{$key}.'" /></td></tr>';
 6305:                             }
 6306:                         }
 6307:                     }
 6308:                     $datatable .= '<tr><td><span class="LC_nobreak">'.
 6309:                                   '<label><input type="checkbox" name="proctoring_customadd" value="'.$provider.'" />'.
 6310:                                   &mt('Add more').'</label></span></td><td><input type="text" name="proctoring_custom_name_'.$provider.'" />'.
 6311:                                   '</td><td><input type="text" name="proctoring_custom_value_'.$provider.'" /></td></tr>'.
 6312:                                   '</table></fieldset></td></tr>'."\n";
 6313:                 }
 6314:                 $datatable .= '</td></tr>';
 6315:             }
 6316:             $itemcount ++;
 6317:         }
 6318:     }
 6319:     return $datatable;
 6320: }
 6321: 
 6322: sub proctoring_data {
 6323:     my $requserfields = {
 6324:                       proctorio => ['user'],
 6325:                       examity   => ['roles','user'],
 6326:                      };
 6327:     my $optuserfields = {
 6328:                         proctorio => ['fullname'],
 6329:                         examity   => ['fullname','firstname','lastname','email'],
 6330:                      };
 6331:     my $defaults = {
 6332:                   proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 6333:                                 'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 6334:                                 'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 6335:                                 'closetabs','onescreen','print','downloads','cache','rightclick',
 6336:                                 'reentry','calculator','whiteboard'],
 6337:                   examity   => ['display'],
 6338:                 };
 6339:     my $extended = { 
 6340:                   proctorio => {
 6341:                                  verifyid => ['verifyidauto','verifyidlive'],
 6342:                                  fullscreen => ['fullscreenlenient','fullscreenmoderate','fullscreensever'],
 6343:                                  tabslinks => ['notabs','linksonly'],
 6344:                                  reentry => ['noreentry','agentreentry'],
 6345:                                  calculator => ['calculatorbasic','calculatorsci'],
 6346:                                },
 6347:                   examity => {
 6348:                                display => {
 6349:                                            target      => ['iframe','tab','window'],
 6350:                                            width       => '',
 6351:                                            height      => '',
 6352:                                            linktext    => '',
 6353:                                            explanation => '',
 6354:                                           },
 6355:                              },
 6356:                 };
 6357:     my $crsconf = {
 6358:                  proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 6359:                                'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 6360:                                'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 6361:                                'closetabs','onescreen','print','downloads','cache','rightclick',
 6362:                                'reentry','calculator','whiteboard'],
 6363:                  examity => ['label','title','target','linktext','explanation','append'],
 6364:                };
 6365:     my $courseroles = ['cc','in','ta','ep','st'];
 6366:     my $ltiroles = ['Instructor','ContentDeveloper','TeachingAssistant','Learner'];
 6367:     return ($requserfields,$optuserfields,$defaults,$extended,$crsconf,$courseroles,$ltiroles);
 6368: }
 6369: 
 6370: sub proctoring_titles {
 6371:     my ($item) = @_;
 6372:     my (%common_lt,%custom_lt);
 6373:     %common_lt = &Apache::lonlocal::texthash (
 6374:                      'avai'      => 'Available?',
 6375:                      'base'      => 'Basic Settings',
 6376:                      'requ'      => 'User data required to be sent on launch',
 6377:                      'optu'      => 'User data optionally sent on launch',
 6378:                      'udsl'      => 'User data sent on launch',
 6379:                      'defa'      => 'Defaults for items configurable in course',
 6380:                      'sigmethod' => 'Signature Method',
 6381:                      'key'       => 'Key',
 6382:                      'lifetime'  => 'Nonce lifetime (s)',
 6383:                      'secret'    => 'Secret',
 6384:                      'icon'      => 'Icon',
 6385:                      'fullname'  => 'Full Name',
 6386:                      'visible'   => 'Visible input',
 6387:                      'username'  => 'username',
 6388:                      'user'      => 'User',
 6389:                  );
 6390:     if ($item eq 'proctorio') {
 6391:         %custom_lt = &Apache::lonlocal::texthash (
 6392:                          'version'        => 'OAuth version',
 6393:                          'url'            => 'API URL',
 6394:                          'uname:dom'      => 'username-domain',
 6395:         );
 6396:     } elsif ($item eq 'examity') {
 6397:         %custom_lt = &Apache::lonlocal::texthash (
 6398:                          'version'        => 'LTI Version',
 6399:                          'url'            => 'URL',
 6400:                          'uname:dom'      => 'username:domain',
 6401:                          'msgtype'        => 'Message Type',
 6402:                          'firstname'      => 'First Name',
 6403:                          'lastname'       => 'Last Name',
 6404:                          'email'          => 'E-mail',
 6405:                          'roles'          => 'Role',
 6406:                          'crstarget'      => 'Display target',
 6407:                          'crslabel'       => 'Course label',
 6408:                          'crstitle'       => 'Course title', 
 6409:                          'crslinktext'    => 'Link Text',
 6410:                          'crsexplanation' => 'Explanation',
 6411:                          'crsappend'      => 'Provider URL',
 6412:         );
 6413:     }
 6414:     my %lt = (%common_lt,%custom_lt);
 6415:     return %lt;
 6416: }
 6417: 
 6418: sub proctoring_fieldtitles {
 6419:     my ($item) = @_;
 6420:     if ($item eq 'proctorio') {
 6421:         return &Apache::lonlocal::texthash (
 6422:                   'recordvideo' => 'Record video',
 6423:                   'recordaudio' => 'Record audio',
 6424:                   'recordscreen' => 'Record screen',
 6425:                   'recordwebtraffic' => 'Record web traffic',
 6426:                   'recordroomstart' => 'Record room scan',
 6427:                   'verifyvideo' => 'Verify webcam',
 6428:                   'verifyaudio' => 'Verify microphone',
 6429:                   'verifydesktop' => 'Verify desktop recording',
 6430:                   'verifyid' => 'Photo ID verification',
 6431:                   'verifysignature' => 'Require signature',
 6432:                   'fullscreen' => 'Fullscreen',
 6433:                   'clipboard' => 'Disable copy/paste',
 6434:                   'tabslinks' => 'New tabs/windows',
 6435:                   'closetabs' => 'Close other tabs',
 6436:                   'onescreen' => 'Limit to single screen',
 6437:                   'print' => 'Disable Printing',
 6438:                   'downloads' => 'Disable Downloads',
 6439:                   'cache' => 'Empty cache after exam',
 6440:                   'rightclick' => 'Disable right click',
 6441:                   'reentry' => 'Re-entry to exam',
 6442:                   'calculator' => 'Onscreen calculator',
 6443:                   'whiteboard' => 'Onscreen whiteboard',
 6444:                   'verifyidauto' => 'Automated verification',
 6445:                   'verifyidlive' => 'Live agent verification',
 6446:                   'fullscreenlenient' => 'Forced, but can navigate away for up to 30s',
 6447:                   'fullscreenmoderate' => 'Forced, but can navigate away for up to 15s',
 6448:                   'fullscreensever' => 'Forced, navigation away ends exam',
 6449:                   'notabs' => 'Disaallowed',
 6450:                   'linksonly' => 'Allowed from links in exam',
 6451:                   'noreentry' => 'Disallowed',
 6452:                   'agentreentry' => 'Agent required for re-entry',
 6453:                   'calculatorbasic' => 'Basic',
 6454:                   'calculatorsci' => 'Scientific',
 6455:         );
 6456:     } elsif ($item eq 'examity') {
 6457:         return &Apache::lonlocal::texthash (
 6458:                 'target'         => 'Display target',   
 6459:                 'window'         => 'Window',
 6460:                 'tab'            => 'Tab',
 6461:                 'iframe'         => 'iFrame',
 6462:                 'height'         => 'Height (pixels)',
 6463:                 'width'          => 'Width (pixels)',
 6464:                 'linktext'       => 'Default Link Text',
 6465:                 'explanation'    => 'Default Explanation',
 6466:                 'append'         => 'Provider URL',
 6467:         );
 6468:     }
 6469: }
 6470: 
 6471: sub proctoring_providernames {
 6472:     return (
 6473:              proctorio => 'Proctorio',
 6474:              examity   => 'Examity',
 6475:            );
 6476: }
 6477: 
 6478: sub print_lti {
 6479:     my ($position,$dom,$settings,$rowtotal) = @_;
 6480:     my $itemcount = 1;
 6481:     my ($datatable,$css_class);
 6482:     my (%rules,%encrypt,%privkeys,%linkprot);
 6483:     if (ref($settings) eq 'HASH') {
 6484:         if ($position eq 'top') {
 6485:             if (exists($settings->{'encrypt'})) {
 6486:                 if (ref($settings->{'encrypt'}) eq 'HASH') {
 6487:                     foreach my $key (keys(%{$settings->{'encrypt'}})) {
 6488:                         if ($key eq 'consumers') {
 6489:                             $encrypt{'ltisec_'.$key} = $settings->{'encrypt'}{$key};
 6490:                         } else {
 6491:                             $encrypt{'ltisec_'.$key.'linkprot'} = $settings->{'encrypt'}{$key};
 6492:                         }
 6493:                     }
 6494:                 }
 6495:             }
 6496:             if (exists($settings->{'private'})) {
 6497:                 if (ref($settings->{'private'}) eq 'HASH') {
 6498:                     if (ref($settings->{'private'}) eq 'HASH') {
 6499:                         if (ref($settings->{'private'}{'keys'}) eq 'ARRAY') {
 6500:                             map { $privkeys{$_} = 1; } (@{$settings->{'private'}{'keys'}});
 6501:                         }
 6502:                     }
 6503:                 }
 6504:             }
 6505:         } elsif ($position eq 'middle') {
 6506:             if (exists($settings->{'rules'})) {
 6507:                 if (ref($settings->{'rules'}) eq 'HASH') {
 6508:                     %rules = %{$settings->{'rules'}};
 6509:                 }
 6510:             }
 6511:         } elsif ($position eq 'lower') {
 6512:             if (exists($settings->{'linkprot'})) {
 6513:                 if (ref($settings->{'linkprot'}) eq 'HASH') {
 6514:                     %linkprot = %{$settings->{'linkprot'}};
 6515:                     if ($linkprot{'lock'}) {
 6516:                         delete($linkprot{'lock'});
 6517:                     }
 6518:                 }
 6519:             }
 6520:         } else {
 6521:             foreach my $key ('encrypt','private','rules','linkprot') {
 6522:                 if (exists($settings->{$key})) {
 6523:                     delete($settings->{$key});
 6524:                 }
 6525:             }
 6526:         }
 6527:     }
 6528:     if ($position eq 'top') {
 6529:         my @ids=&Apache::lonnet::current_machine_ids();
 6530:         my %servers = &Apache::lonnet::get_servers($dom,'library');
 6531:         my $primary = &Apache::lonnet::domain($dom,'primary');
 6532:         my ($extra,$numshown);
 6533:         foreach my $hostid (sort(keys(%servers))) {
 6534:             my ($showextra,$divsty,$switch);
 6535:             if ($hostid eq $primary) {
 6536:                 if (($encrypt{'ltisec_consumers'}) || ($encrypt{'ltisec_domlinkprot'})) {
 6537:                     $showextra = 1;
 6538:                 }
 6539:             }
 6540:             if ($encrypt{'ltisec_crslinkprot'}) {
 6541:                 $showextra = 1;
 6542:             }
 6543:             unless (grep(/^\Q$hostid\E$/,@ids)) {
 6544:                 $switch = 1;
 6545:             }
 6546:             if ($showextra) {
 6547:                 $numshown ++;
 6548:                 $divsty = 'display:inline-block'; 
 6549:             } else {
 6550:                 $divsty = 'display:none';
 6551:             } 
 6552:             $extra .= '<fieldset id="ltisec_info_'.$hostid.'" style="'.$divsty.'">'.
 6553:                       '<legend>'.$hostid.'</legend>';
 6554:             if ($switch) {
 6555:                 my $switchserver = '<a href="/adm/switchserver?otherserver='.$hostid.'&amp;role='.
 6556:                                    &HTML::Entities::encode($env{'request.role'},'\'<>"&').
 6557:                                    '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 6558:                 if (exists($privkeys{$hostid})) {
 6559:                     $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" />'.
 6560:                               '<span class="LC_nobreak">'.
 6561:                               &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 6562:                               '<span class="LC_nobreak">'.&mt('Change?').
 6563:                               '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 6564:                               ('&nbsp;'x2).
 6565:                               '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
 6566:                               '</label>&nbsp;&nbsp;</span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
 6567:                               '<span class="LC_nobreak"> - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 6568:                               '</span></div>';
 6569:                 } else {
 6570:                     $extra .= '<span class="LC_nobreak">'.
 6571:                               &mt('Key required').' - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 6572:                               '</span>'."\n";
 6573:                 }
 6574:             } elsif (exists($privkeys{$hostid})) {
 6575:                 $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" /><span class="LC_nobreak">'.
 6576:                           &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 6577:                           '<span class="LC_nobreak">'.&mt('Change?').
 6578:                           '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 6579:                           ('&nbsp;'x2).
 6580:                           '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
 6581:                           '</label>&nbsp;&nbsp;</span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
 6582:                           '<span class="LC_nobreak">'.&mt('New Key').':'.
 6583:                           '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="off" />'.
 6584:                           '<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>'.
 6585:                           '</span></div>';
 6586:             } else {
 6587:                 $extra .= '<span class="LC_nobreak">'.&mt('Encryption Key').':'.
 6588:                           '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="off" />'.
 6589:                           '<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>';
 6590:             }
 6591:             $extra .= '</fieldset>';
 6592:         }
 6593:         my %choices = &Apache::lonlocal::texthash (
 6594:                                                       ltisec_crslinkprot => 'Encrypt stored link protection secrets defined in courses',
 6595:                                                       ltisec_domlinkprot => 'Encrypt stored link protection secrets defined in domain',
 6596:                                                       ltisec_consumers   => 'Encrypt stored consumer secrets defined in domain',
 6597:                                                   );
 6598:         my @toggles = qw(ltisec_crslinkprot ltisec_domlinkprot ltisec_consumers);
 6599:         my %defaultchecked = (
 6600:                                'ltisec_crslinkprot' => 'off',
 6601:                                'ltisec_domlinkprot' => 'off',
 6602:                                'ltisec_consumers'   => 'off',
 6603:                              );
 6604:         my ($onclick,$itemcount);
 6605:         $onclick = 'javascript:toggleLTIEncKey(this.form);';
 6606:         ($datatable,$itemcount) = &radiobutton_prefs(\%encrypt,\@toggles,\%defaultchecked,
 6607:                                                      \%choices,$itemcount,$onclick,'','left','no');
 6608: 
 6609:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6610:         my $noprivkeysty = 'display:inline-block';
 6611:         if ($numshown) {
 6612:             $noprivkeysty = 'display:none'; 
 6613:         }
 6614:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.&mt('Encryption Key(s)').'</td>'.
 6615:                       '<td><div id="ltisec_noprivkey" style="'.$noprivkeysty.'" >'.
 6616:                       '<span class="LC_nobreak">'.&mt('Not in use').'</span></div>'.
 6617:                       $extra.
 6618:                       '</td></tr>';
 6619:         $itemcount ++;                
 6620:         $$rowtotal += $itemcount;
 6621:     } elsif ($position eq 'middle') {
 6622:         $datatable = &password_rules('secrets',\$itemcount,\%rules);
 6623:         $$rowtotal += $itemcount;
 6624:     } elsif ($position eq 'lower') {
 6625:          $datatable .= &Apache::courseprefs::print_linkprotection($dom,'',$settings,$rowtotal,'','','domain');
 6626:     } else {
 6627:         my $maxnum = 0;
 6628:         my %ordered;
 6629:         if (ref($settings) eq 'HASH') {
 6630:             foreach my $item (keys(%{$settings})) {
 6631:                 if (ref($settings->{$item}) eq 'HASH') {
 6632:                     my $num = $settings->{$item}{'order'};
 6633:                     if ($num eq '') {
 6634:                         $num = scalar(keys(%{$settings}));
 6635:                     }
 6636:                     $ordered{$num} = $item;
 6637:                 }
 6638:             }
 6639:         }
 6640:         $maxnum = scalar(keys(%ordered));
 6641:         my %lt = &lti_names();
 6642:         if (keys(%ordered)) {
 6643:             my @items = sort { $a <=> $b } keys(%ordered);
 6644:             for (my $i=0; $i<@items; $i++) {
 6645:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6646:                 my $item = $ordered{$items[$i]};
 6647:                 my ($key,$secret,$lifetime,$consumer,$requser,$crsinc,$current);
 6648:                 if (ref($settings->{$item}) eq 'HASH') {
 6649:                     $key = $settings->{$item}->{'key'};
 6650:                     $secret = $settings->{$item}->{'secret'};
 6651:                     $lifetime = $settings->{$item}->{'lifetime'};
 6652:                     $consumer = $settings->{$item}->{'consumer'};
 6653:                     $requser = $settings->{$item}->{'requser'};
 6654:                     $crsinc = $settings->{$item}->{'crsinc'};
 6655:                     $current = $settings->{$item};
 6656:                 }
 6657:                 my $onclickrequser = ' onclick="toggleLTI(this.form,'."'requser','$i'".');"';
 6658:                 my %checkedrequser = (
 6659:                                        yes => ' checked="checked"',
 6660:                                        no  => '',
 6661:                                      );
 6662:                 if (!$requser) {
 6663:                     $checkedrequser{'no'} = $checkedrequser{'yes'};
 6664:                     $checkedrequser{'yes'} = '';
 6665:                 }
 6666:                 my $onclickcrsinc = ' onclick="toggleLTI(this.form,'."'crsinc','$i'".');"';
 6667:                 my %checkedcrsinc = (
 6668:                                       yes => ' checked="checked"',
 6669:                                       no  => '',
 6670:                                     );
 6671:                 if (!$crsinc) {
 6672:                     $checkedcrsinc{'no'} = $checkedcrsinc{'yes'};
 6673:                     $checkedcrsinc{'yes'} = '';
 6674:                 }
 6675:                 my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_".$item."'".');"';
 6676:                 $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 6677:                              .'<select name="lti_pos_'.$item.'"'.$chgstr.'>';
 6678:                 for (my $k=0; $k<=$maxnum; $k++) {
 6679:                     my $vpos = $k+1;
 6680:                     my $selstr;
 6681:                     if ($k == $i) {
 6682:                         $selstr = ' selected="selected" ';
 6683:                     }
 6684:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6685:                 }
 6686:                 $datatable .= '</select>'.('&nbsp;'x2).
 6687:                     '<label><input type="checkbox" name="lti_del" value="'.$item.'" />'.
 6688:                     &mt('Delete?').'</label></span></td>'.
 6689:                     '<td colspan="2">'.
 6690:                     '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 6691:                     '<span class="LC_nobreak">'.$lt{'consumer'}.
 6692:                     ':<input type="text" size="15" name="lti_consumer_'.$i.'" value="'.$consumer.'" /></span> '.
 6693:                     ('&nbsp;'x2).
 6694:                     '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_'.$i.'">'.
 6695:                     '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 6696:                     ('&nbsp;'x2).
 6697:                     '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" name="lti_lifetime_'.$i.'"'.
 6698:                     'value="'.$lifetime.'" size="3" /></span>'.
 6699:                     ('&nbsp;'x2).
 6700:                     '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 6701:                     '<label><input type="radio" name="lti_requser_'.$i.'" value="1"'.$onclickrequser.$checkedrequser{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 6702:                     '<label><input type="radio" name="lti_requser_'.$i.'" value="0"'.$onclickrequser.$checkedrequser{no}.' />'.&mt('No').'</label></span>'."\n".
 6703:                     '<br /><br />'.
 6704:                     '<span class="LC_nobreak">'.$lt{'crsinc'}.':'.
 6705:                     '<label><input type="radio" name="lti_crsinc_'.$i.'" value="1"'.$onclickcrsinc.$checkedcrsinc{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 6706:                     '<label><input type="radio" name="lti_crsinc_'.$i.'" value="0"'.$onclickcrsinc.$checkedcrsinc{no}.' />'.&mt('No').'</label></span>'."\n".
 6707:                     ('&nbsp;'x4).
 6708:                     '<span class="LC_nobreak">'.$lt{'key'}.
 6709:                     ':<input type="text" size="25" name="lti_key_'.$i.'" value="'.$key.'" /></span> '.
 6710:                     ('&nbsp;'x2).
 6711:                     '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 6712:                     '<input type="password" size="20" name="lti_secret_'.$i.'" value="'.$secret.'" />'.
 6713:                     '<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>'.
 6714:                     '<input type="hidden" name="lti_id_'.$i.'" value="'.$item.'" /></span>'.
 6715:                     '</fieldset>'.&lti_options($i,$current,$itemcount,%lt).'</td></tr>';
 6716:                 $itemcount ++;
 6717:             }
 6718:         }
 6719:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6720:         my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_add'".');"';
 6721:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 6722:                       '<input type="hidden" name="lti_maxnum" value="'.$maxnum.'" />'."\n".
 6723:                       '<select name="lti_pos_add"'.$chgstr.'>';
 6724:         for (my $k=0; $k<$maxnum+1; $k++) {
 6725:             my $vpos = $k+1;
 6726:             my $selstr;
 6727:             if ($k == $maxnum) {
 6728:                 $selstr = ' selected="selected" ';
 6729:             }
 6730:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6731:         }
 6732:         $datatable .= '</select>&nbsp;'."\n".
 6733:                       '<input type="checkbox" name="lti_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 6734:                       '<td colspan="2">'.
 6735:                       '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 6736:                       '<span class="LC_nobreak">'.$lt{'consumer'}.
 6737:                       ':<input type="text" size="15" name="lti_consumer_add" value="" /></span> '."\n".
 6738:                       ('&nbsp;'x2).
 6739:                       '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_add">'.
 6740:                       '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 6741:                       ('&nbsp;'x2).
 6742:                       '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="3" name="lti_lifetime_add" value="300" /></span> '."\n".
 6743:                       ('&nbsp;'x2).
 6744:                       '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 6745:                       '<label><input type="radio" name="lti_requser_add" value="1" onclick="toggleLTI(this.form,'."'requser','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 6746:                       '<label><input type="radio" name="lti_requser_add" value="0" onclick="toggleLTI(this.form,'."'requser','add'".');" />'.&mt('No').'</label></span>'."\n".
 6747:                       '<br /><br />'.
 6748:                       '<span class="LC_nobreak">'.$lt{'crsinc'}.':'.
 6749:                       '<label><input type="radio" name="lti_crsinc_add" value="1" onclick="toggleLTI(this.form,'."'crsinc','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 6750:                       '<label><input type="radio" name="lti_crsinc_add" value="0" onclick="toggleLTI(this.form,'."'crsinc','add'".');" />'.&mt('No').'</label></span>'."\n".
 6751:                       ('&nbsp;'x4).
 6752:                       '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="lti_key_add" value="" /></span> '."\n".
 6753:                       ('&nbsp;'x2).
 6754:                       '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="lti_secret_add" value="" />'.
 6755:                       '<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".
 6756:                       '</fieldset>'.&lti_options('add',undef,$itemcount,%lt).
 6757:                       '</td>'."\n".
 6758:                       '</tr>'."\n";
 6759:         $itemcount ++;
 6760:     }
 6761:     $$rowtotal += $itemcount;
 6762:     return $datatable;
 6763: }
 6764: 
 6765: sub lti_names {
 6766:     my %lt = &Apache::lonlocal::texthash(
 6767:                                           'version'   => 'LTI Version',
 6768:                                           'url'       => 'URL',
 6769:                                           'key'       => 'Key',
 6770:                                           'lifetime'  => 'Nonce lifetime (s)',
 6771:                                           'consumer'  => 'Consumer',
 6772:                                           'secret'    => 'Secret',
 6773:                                           'requser'   => "User's identity sent",
 6774:                                           'crsinc'    => "Course's identity sent",
 6775:                                           'email'     => 'Email address',
 6776:                                           'sourcedid' => 'User ID',
 6777:                                           'other'     => 'Other',
 6778:                                           'passback'  => 'Can return grades to Consumer:',
 6779:                                           'roster'    => 'Can retrieve roster from Consumer:',
 6780:                                           'topmenu'   => 'Display LON-CAPA page header',
 6781:                                           'inlinemenu'=> 'Display LON-CAPA inline menu',
 6782:                                         );
 6783:     return %lt;
 6784: }
 6785: 
 6786: sub lti_options {
 6787:     my ($num,$current,$itemcount,%lt) = @_;
 6788:     my (%checked,%rolemaps,$crssecsrc,$userfield,$cidfield,$callback);
 6789:     $checked{'mapuser'}{'sourcedid'} = ' checked="checked"';
 6790:     $checked{'mapcrs'}{'course_offering_sourcedid'} = ' checked="checked"';
 6791:     $checked{'storecrs'}{'Y'} = ' checked="checked"';
 6792:     $checked{'makecrs'}{'N'} = ' checked="checked"';
 6793:     $checked{'mapcrstype'} = {};
 6794:     $checked{'makeuser'} = {};
 6795:     $checked{'selfenroll'} = {};
 6796:     $checked{'crssec'} = {};
 6797:     $checked{'crssecsrc'} = {};
 6798:     $checked{'lcauth'} = {};
 6799:     $checked{'menuitem'} = {};
 6800:     if ($num eq 'add') {
 6801:         $checked{'lcauth'}{'lti'} = ' checked="checked"';
 6802:     }
 6803:     my $userfieldsty = 'none';
 6804:     my $crsfieldsty = 'none';
 6805:     my $crssecfieldsty = 'none';
 6806:     my $secsrcfieldsty = 'none';
 6807:     my $callbacksty = 'none';
 6808:     my $passbacksty = 'none';
 6809:     my $optionsty = 'block';
 6810:     my $crssty = 'block';
 6811:     my $lcauthparm;
 6812:     my $lcauthparmstyle = 'display:none';
 6813:     my $lcauthparmtext;
 6814:     my $menusty;
 6815:     my $numinrow = 4;
 6816:     my %menutitles = &ltimenu_titles();
 6817: 
 6818:     if (ref($current) eq 'HASH') {
 6819:         if (!$current->{'requser'}) {
 6820:             $optionsty = 'none';
 6821:             $crssty = 'none';
 6822:         } elsif (!$current->{'crsinc'}) {
 6823:             $crssty = 'none';
 6824:         }
 6825:         if (($current->{'mapuser'} ne '') && ($current->{'mapuser'} ne 'lis_person_sourcedid')) {
 6826:             $checked{'mapuser'}{'sourcedid'} = '';
 6827:             if ($current->{'mapuser'} eq 'lis_person_contact_email_primary') {
 6828:                 $checked{'mapuser'}{'email'} = ' checked="checked"'; 
 6829:             } else {
 6830:                 $checked{'mapuser'}{'other'} = ' checked="checked"';
 6831:                 $userfield = $current->{'mapuser'};
 6832:                 $userfieldsty = 'inline-block';
 6833:             }
 6834:         }
 6835:         if (($current->{'mapcrs'} ne '') && ($current->{'mapcrs'} ne 'course_offering_sourcedid')) {
 6836:             $checked{'mapcrs'}{'course_offering_sourcedid'} = '';
 6837:             if ($current->{'mapcrs'} eq 'context_id') {
 6838:                 $checked{'mapcrs'}{'context_id'} = ' checked="checked"'; 
 6839:             } else {
 6840:                 $checked{'mapcrs'}{'other'} = ' checked="checked"';
 6841:                 $cidfield = $current->{'mapcrs'};
 6842:                 $crsfieldsty = 'inline-block';
 6843:             }
 6844:         }
 6845:         if (ref($current->{'mapcrstype'}) eq 'ARRAY') {
 6846:             foreach my $type (@{$current->{'mapcrstype'}}) {
 6847:                 $checked{'mapcrstype'}{$type} = ' checked="checked"';
 6848:             }
 6849:         }
 6850:         if (!$current->{'storecrs'}) {
 6851:             $checked{'storecrs'}{'N'} = $checked{'storecrs'}{'Y'};
 6852:             $checked{'storecrs'}{'Y'} = '';
 6853:         }
 6854:         if ($current->{'makecrs'}) {
 6855:             $checked{'makecrs'}{'Y'} = '  checked="checked"';
 6856:         }
 6857:         if (ref($current->{'makeuser'}) eq 'ARRAY') {
 6858:             foreach my $role (@{$current->{'makeuser'}}) {
 6859:                 $checked{'makeuser'}{$role} = ' checked="checked"';
 6860:             }
 6861:         }
 6862:         if ($current->{'lcauth'} =~ /^(internal|localauth|krb4|krb5|lti)$/) {
 6863:             $checked{'lcauth'}{$1} = ' checked="checked"';
 6864:             unless (($current->{'lcauth'} eq 'lti') || ($current->{'lcauth'} eq 'internal')) {
 6865:                 $lcauthparm = $current->{'lcauthparm'};
 6866:                 $lcauthparmstyle = 'display:table-row'; 
 6867:                 if ($current->{'lcauth'} eq 'localauth') {
 6868:                     $lcauthparmtext = &mt('Local auth argument');
 6869:                 } else {
 6870:                     $lcauthparmtext = &mt('Kerberos domain');
 6871:                 }
 6872:             }
 6873:         }
 6874:         if (ref($current->{'selfenroll'}) eq 'ARRAY') {
 6875:             foreach my $role (@{$current->{'selfenroll'}}) {
 6876:                 $checked{'selfenroll'}{$role} = ' checked="checked"';
 6877:             }
 6878:         }
 6879:         if (ref($current->{'maproles'}) eq 'HASH') {
 6880:             %rolemaps = %{$current->{'maproles'}};
 6881:         }
 6882:         if ($current->{'section'} ne '') {
 6883:             $checked{'crssec'}{'Y'} = '  checked="checked"'; 
 6884:             $crssecfieldsty = 'inline-block';
 6885:             if ($current->{'section'} eq 'course_section_sourcedid') {
 6886:                 $checked{'crssecsrc'}{'sourcedid'} = ' checked="checked"';
 6887:             } else {
 6888:                 $checked{'crssecsrc'}{'other'} = ' checked="checked"';
 6889:                 $crssecsrc = $current->{'section'};
 6890:                 $secsrcfieldsty = 'inline-block';
 6891:             }
 6892:         } else {
 6893:             $checked{'crssec'}{'N'} = ' checked="checked"';
 6894:         }
 6895:         if ($current->{'callback'} ne '') {
 6896:             $callback = $current->{'callback'};
 6897:             $checked{'callback'}{'Y'} = ' checked="checked"';
 6898:             $callbacksty = 'inline-block';
 6899:         } else {
 6900:             $checked{'callback'}{'N'} = ' checked="checked"';
 6901:         }
 6902:         if ($current->{'topmenu'}) {
 6903:             $checked{'topmenu'}{'Y'} = ' checked="checked"';
 6904:         } else {
 6905:             $checked{'topmenu'}{'N'} = ' checked="checked"';
 6906:         }
 6907:         if ($current->{'inlinemenu'}) {
 6908:             $checked{'inlinemenu'}{'Y'} = ' checked="checked"';
 6909:         } else {
 6910:             $checked{'inlinemenu'}{'N'} = ' checked="checked"';
 6911:         }
 6912:         if (($current->{'topmenu'}) || ($current->{'inlinemenu'})) {
 6913:             $menusty = 'inline-block';
 6914:             if (ref($current->{'lcmenu'}) eq 'ARRAY') {
 6915:                 foreach my $item (@{$current->{'lcmenu'}}) {
 6916:                     if (exists($menutitles{$item})) {
 6917:                         $checked{'menuitem'}{$item} = ' checked="checked"';
 6918:                     }
 6919:                 }
 6920:             }
 6921:         } else {
 6922:             $menusty = 'none';
 6923:         }
 6924:     } else {
 6925:         $checked{'makecrs'}{'N'} = ' checked="checked"';
 6926:         $checked{'crssec'}{'N'} = ' checked="checked"';
 6927:         $checked{'callback'}{'N'} = ' checked="checked"';
 6928:         $checked{'topmenu'}{'N'} = ' checked="checked"';
 6929:         $checked{'inlinemenu'}{'Y'} = ' checked="checked"'; 
 6930:         $checked{'menuitem'}{'grades'} = ' checked="checked"';
 6931:         $menusty = 'inline-block'; 
 6932:     }
 6933:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
 6934:     my %coursetypetitles = &Apache::lonlocal::texthash (
 6935:                                official   => 'Official',
 6936:                                unofficial => 'Unofficial',
 6937:                                community  => 'Community',
 6938:                                textbook   => 'Textbook',
 6939:                                placement  => 'Placement Test',
 6940:                                lti        => 'LTI Provider',
 6941:     );
 6942:     my @authtypes = ('internal','krb4','krb5','localauth');
 6943:     my %shortauth = (
 6944:                      internal => 'int',
 6945:                      krb4 => 'krb4',
 6946:                      krb5 => 'krb5',
 6947:                      localauth  => 'loc'
 6948:                     );
 6949:     my %authnames = &authtype_names();
 6950:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
 6951:     my @lticourseroles = qw(Learner Instructor TeachingAssistant Mentor);
 6952:     my @courseroles = ('cc','in','ta','ep','st');
 6953:     my $onclickuser = ' onclick="toggleLTI(this.form,'."'user','$num'".');"';
 6954:     my $onclickcrs = ' onclick="toggleLTI(this.form,'."'crs','$num'".');"';
 6955:     my $onclicksec = ' onclick="toggleLTI(this.form,'."'sec','$num'".');"';
 6956:     my $onclickcallback = ' onclick="toggleLTI(this.form,'."'callback','$num'".');"';
 6957:     my $onclicksecsrc = ' onclick="toggleLTI(this.form,'."'secsrc','$num'".')"';
 6958:     my $onclicklcauth = ' onclick="toggleLTI(this.form,'."'lcauth','$num'".')"';
 6959:     my $onclickmenu = ' onclick="toggleLTI(this.form,'."'lcmenu','$num'".');"';
 6960:     my $output = '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Logout options').'</legend>'.
 6961:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Callback to logout LON-CAPA on log out from Consumer').':&nbsp;'.
 6962:                  '<label><input type="radio" name="lti_callback_'.$num.'" value="0"'.
 6963:                  $checked{'callback'}{'N'}.$onclickcallback.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6964:                  '<label><input type="radio" name="lti_callback_'.$num.'" value="1"'.
 6965:                  $checked{'callback'}{'Y'}.$onclickcallback.' />'.&mt('Yes').'</label></span></div>'.
 6966:                  '<div class="LC_floatleft" style="display:'.$callbacksty.';" id="lti_callbackfield_'.$num.'">'.
 6967:                  '<span class="LC_nobreak">'.&mt('Parameter').': '.
 6968:                  '<input type="text" name="lti_callbackparam_'.$num.'" value="'.$callback.'" /></span>'.
 6969:                  '</div><div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>'.
 6970:                  '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping users').'</legend>'.
 6971:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('LON-CAPA username').':&nbsp;';
 6972:     foreach my $option ('sourcedid','email','other') {
 6973:         $output .= '<label><input type="radio" name="lti_mapuser_'.$num.'" value="'.$option.'"'.
 6974:                    $checked{'mapuser'}{$option}.$onclickuser.' />'.$lt{$option}.'</label>'.
 6975:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 6976:     }
 6977:     $output .= '</span></div>'.
 6978:                '<div class="LC_floatleft" style="display:'.$userfieldsty.';" id="lti_userfield_'.$num.'">'.
 6979:                '<input type="text" name="lti_customuser_'.$num.'" '.
 6980:                'value="'.$userfield.'" /></div></fieldset>'.
 6981:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Roles which may create user accounts').'</legend>';
 6982:     foreach my $ltirole (@ltiroles) {
 6983:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_makeuser_'.$num.'" value="'.$ltirole.'"'.
 6984:                    $checked{'makeuser'}{$ltirole}.' />'.$ltirole.'</label>&nbsp;</span> ';     
 6985:     }
 6986:     $output .= '</fieldset>'.
 6987:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('New user accounts created for LTI users').'</legend>'.
 6988:                '<table>'.
 6989:                &modifiable_userdata_row('lti','instdata_'.$num,$current,$numinrow,$itemcount).
 6990:                '</table>'.
 6991:                '<table class="LC_nested"><tr><td class="LC_left_item">LON-CAPA Authentication</td>'.
 6992:                '<td class="LC_left_item">';
 6993:     foreach my $auth ('lti',@authtypes) {
 6994:         my $authtext;
 6995:         if ($auth eq 'lti') {
 6996:             $authtext = &mt('None');
 6997:         } else {
 6998:             $authtext = $authnames{$shortauth{$auth}};
 6999:         }
 7000:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="lti_lcauth_'.$num.
 7001:                    '" value="'.$auth.'"'.$checked{'lcauth'}{$auth}.$onclicklcauth.' />'.
 7002:                    $authtext.'</label></span> &nbsp;';
 7003:     }
 7004:     $output .= '</td></tr>'.
 7005:                '<tr id="lti_lcauth_parmrow_'.$num.'" style="'.$lcauthparmstyle.'">'.
 7006:                '<td class="LC_right_item" colspan="2"><span class="LC_nobreak">'.
 7007:                '<span id="lti_lcauth_parmtext_'.$num.'">'.$lcauthparmtext.'</span>'.
 7008:                '<input type="text" name="lti_lcauthparm_'.$num.'" value="" /></span></td></tr>'.
 7009:                '</table></fieldset>'.
 7010:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.
 7011:                &mt('LON-CAPA menu items (Course Coordinator can override)').'</legend>'.
 7012:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'topmenu'}.':&nbsp;'.
 7013:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="0"'.
 7014:                $checked{'topmenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7015:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="1"'.
 7016:                $checked{'topmenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>'.
 7017:                '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 7018:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'inlinemenu'}.':&nbsp;'.
 7019:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="0"'.
 7020:                $checked{'inlinemenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7021:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="1"'.
 7022:                $checked{'inlinemenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>';
 7023:      $output .='<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 7024:                '<div class="LC_floatleft" style="display:'.$menusty.';" id="lti_menufield_'.$num.'">'.
 7025:                '<span class="LC_nobreak">'.&mt('Menu items').':&nbsp;';
 7026:     foreach my $type ('fullname','coursetitle','role','logout','grades') {
 7027:         $output .= '<label><input type="checkbox" name="lti_menuitem_'.$num.'" value="'.$type.'"'.
 7028:                    $checked{'menuitem'}{$type}.' />'.$menutitles{$type}.'</label>'.
 7029:                    ('&nbsp;'x2);
 7030:     }
 7031:     $output .= '</span></div></fieldset>'.
 7032:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Mapping courses').'</legend>'.
 7033:                '<div class="LC_floatleft"><span class="LC_nobreak">'.
 7034:                &mt('Unique course identifier').':&nbsp;';
 7035:     foreach my $option ('course_offering_sourcedid','context_id','other') {
 7036:         $output .= '<label><input type="radio" name="lti_mapcrs_'.$num.'" value="'.$option.'"'.
 7037:                    $checked{'mapcrs'}{$option}.$onclickcrs.' />'.$option.'</label>'.
 7038:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 7039:     }
 7040:     $output .= '</span></div><div class="LC_floatleft" style="display:'.$crsfieldsty.';" id="lti_crsfield_'.$num.'">'.
 7041:                '<input type="text" name="lti_mapcrsfield_'.$num.'" value="'.$cidfield.'" />'.
 7042:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>'.
 7043:                '<span class="LC_nobreak">'.&mt('LON-CAPA course type(s)').':&nbsp;';
 7044:     foreach my $type (@coursetypes) {
 7045:         $output .= '<label><input type="checkbox" name="lti_mapcrstype_'.$num.'" value="'.$type.'"'.
 7046:                    $checked{'mapcrstype'}{$type}.' />'.$coursetypetitles{$type}.'</label>'.
 7047:                    ('&nbsp;'x2);
 7048:     }
 7049:     $output .= '</span><br /><br />'.
 7050:                '<span class="LC_nobreak">'.&mt('Store mapping of course identifier to LON-CAPA CourseID').':&nbsp;'.
 7051:                '<label><input type="radio" name="lti_storecrs_'.$num.'" value="0"'.
 7052:                $checked{'storecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7053:                '<label><input type="radio" name="lti_storecrs_'.$num.'" value="1"'.
 7054:                $checked{'storecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 7055:                '</fieldset>'.
 7056:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Mapping course roles').'</legend><table><tr>';
 7057:     foreach my $ltirole (@lticourseroles) {
 7058:         my ($selected,$selectnone);
 7059:         if ($rolemaps{$ltirole} eq '') {
 7060:             $selectnone = ' selected="selected"';
 7061:         }
 7062:         $output .= '<td style="text-align: center">'.$ltirole.'<br />'.
 7063:                    '<select name="lti_maprole_'.$ltirole.'_'.$num.'">'.
 7064:                    '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 7065:         foreach my $role (@courseroles) {
 7066:             unless ($selectnone) {
 7067:                 if ($rolemaps{$ltirole} eq $role) {
 7068:                     $selected = ' selected="selected"';
 7069:                 } else {
 7070:                     $selected = '';
 7071:                 }
 7072:             }
 7073:             $output .= '<option value="'.$role.'"'.$selected.'>'.
 7074:                        &Apache::lonnet::plaintext($role,'Course').
 7075:                        '</option>';
 7076:         }
 7077:         $output .= '</select></td>';
 7078:     }
 7079:     $output .= '</tr></table></fieldset>'.
 7080:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Creating courses').'</legend>'.
 7081:                '<span class="LC_nobreak">'.&mt('Course created (if absent) on Instructor access').':&nbsp;'.
 7082:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="0"'.
 7083:                $checked{'makecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7084:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="1"'.
 7085:                $checked{'makecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 7086:                '</fieldset>'.
 7087:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Roles which may self-enroll').'</legend>';
 7088:     foreach my $lticrsrole (@lticourseroles) {
 7089:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_selfenroll_'.$num.'" value="'.$lticrsrole.'"'.
 7090:                    $checked{'selfenroll'}{$lticrsrole}.' />'.$lticrsrole.'</label>&nbsp;</span> ';
 7091:     }
 7092:     $output .= '</fieldset>'.
 7093:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Course options').'</legend>'.
 7094:                '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Assign users to sections').':&nbsp;'.
 7095:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="0"'.
 7096:                $checked{'crssec'}{'N'}.$onclicksec.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7097:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="1"'.
 7098:                $checked{'crssec'}{'Y'}.$onclicksec.' />'.&mt('Yes').'</label></span></div>'.
 7099:                '<div class="LC_floatleft" style="display:'.$crssecfieldsty.';" id="lti_crssecfield_'.$num.'">'.
 7100:                '<span class="LC_nobreak">'.&mt('From').':<label>'.
 7101:                '<input type="radio" name="lti_crssecsrc_'.$num.'" value="course_section_sourcedid"'.
 7102:                $checked{'crssecsrc'}{'sourcedid'}.$onclicksecsrc.' />'.
 7103:                &mt('Standard field').'</label>'.('&nbsp;'x2).
 7104:                '<label><input type="radio" name="lti_crssecsrc_'.$num.'" value="other"'.
 7105:                $checked{'crssecsrc'}{'other'}.$onclicksecsrc.' />'.&mt('Other').
 7106:                '</label></span></div><div class="LC_floatleft" style="display:'.$secsrcfieldsty.';" id="lti_secsrcfield_'.$num.'">'.
 7107:                '<input type="text" name="lti_customsection_'.$num.'" value="'.$crssecsrc.'" />'.
 7108:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 7109:     my ($pb1p1chk,$pb1p0chk,$onclickpb);
 7110:     foreach my $extra ('roster','passback') {
 7111:         my $checkedon = '';
 7112:         my $checkedoff = ' checked="checked"';
 7113:         if ($extra eq 'passback') {
 7114:             $pb1p1chk = ' checked="checked"';
 7115:             $pb1p0chk = '';
 7116:             $onclickpb = ' onclick="toggleLTI(this.form,'."'passback','$num'".');"'; 
 7117:         } else {
 7118:             $onclickpb = ''; 
 7119:         }
 7120:         if (ref($current) eq 'HASH') {
 7121:             if (($current->{$extra})) {
 7122:                 $checkedon = $checkedoff;
 7123:                 $checkedoff = '';
 7124:                 if ($extra eq 'passback') {
 7125:                     $passbacksty = 'inline-block';
 7126:                 }
 7127:                 if ($current->{'passbackformat'} eq '1.0') {
 7128:                     $pb1p0chk =  ' checked="checked"';
 7129:                     $pb1p1chk = '';
 7130:                 }
 7131:             }
 7132:         }
 7133:         $output .= $lt{$extra}.'&nbsp;'.
 7134:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="0"'.$checkedoff.$onclickpb.' />'.
 7135:                    &mt('No').'</label>'.('&nbsp;'x2).
 7136:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="1"'.$checkedon.$onclickpb.' />'.
 7137:                    &mt('Yes').'</label><br />';
 7138:     }
 7139:     $output .= '<div class="LC_floatleft" style="display:'.$passbacksty.';" id="lti_passback_'.$num.'">'.
 7140:                '<span class="LC_nobreak">'.&mt('Grade format').
 7141:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.1"'.$pb1p1chk.' />'.
 7142:                &mt('Outcomes Service (1.1)').'</label>'.('&nbsp;'x2).
 7143:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.0"'.$pb1p0chk.'/>'.
 7144:                &mt('Outcomes Extension (1.0)').'</label></span></div>'.
 7145:                '<div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>';
 7146:     $output .= '</span></div></fieldset>';
 7147: #        '<fieldset><legend>'.&mt('Assigning author roles').'</legend>';
 7148: #
 7149: #    $output .= '</fieldset>'.
 7150: #        '<fieldset><legend>'.&mt('Assigning domain roles').'</legend>';
 7151:     return $output;
 7152: }
 7153: 
 7154: sub ltimenu_titles {
 7155:     return &Apache::lonlocal::texthash(
 7156:                                         fullname    => 'Full name',
 7157:                                         coursetitle => 'Course title',
 7158:                                         role        => 'Role',
 7159:                                         logout      => 'Logout',
 7160:                                         grades      => 'Grades',
 7161:     );
 7162: }
 7163: 
 7164: sub check_switchserver {
 7165:     my ($home) = @_;
 7166:     my $switchserver;
 7167:     if ($home ne '') {
 7168:         my $allowed;
 7169:         my @ids=&Apache::lonnet::current_machine_ids();
 7170:         foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 7171:         if (!$allowed) {
 7172:             $switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role='.
 7173:                           &HTML::Entities::encode($env{'request.role'},'\'<>"&').
 7174:                           '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 7175:         }
 7176:     }
 7177:     return $switchserver;
 7178: }
 7179: 
 7180: sub print_coursedefaults {
 7181:     my ($position,$dom,$settings,$rowtotal) = @_;
 7182:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 7183:     my $itemcount = 1;
 7184:     my %choices =  &Apache::lonlocal::texthash (
 7185:         canuse_pdfforms      => 'Course/Community users can create/upload PDF forms',
 7186:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 7187:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 7188:         coursecredits        => 'Credits can be specified for courses',
 7189:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 7190:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 7191:         inline_chem          => 'Use inline previewer for chemical reaction response in place of pop-up',
 7192:         texengine            => 'Default method to display mathematics',
 7193:         postsubmit           => 'Disable submit button/keypress following student submission',
 7194:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 7195:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 7196:         ltiauth              => 'Student username in LTI launch of deep-linked URL can be accepted without re-authentication',
 7197:     );
 7198:     my %staticdefaults = (
 7199:                            anonsurvey_threshold => 10,
 7200:                            uploadquota          => 500,
 7201:                            postsubmit           => 60,
 7202:                            mysqltables          => 172800,
 7203:                          );
 7204:     if ($position eq 'top') {
 7205:         %defaultchecked = (
 7206:                             'canuse_pdfforms' => 'off',
 7207:                             'uselcmath'       => 'on',
 7208:                             'usejsme'         => 'on',
 7209:                             'inline_chem'     => 'on',
 7210:                             'canclone'        => 'none',
 7211:                           );
 7212:         @toggles = ('canuse_pdfforms','uselcmath','usejsme','inline_chem');
 7213:         my $deftex = $Apache::lonnet::deftex;
 7214:         if (ref($settings) eq 'HASH') {
 7215:             if ($settings->{'texengine'}) {
 7216:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 7217:                     $deftex = $settings->{'texengine'};
 7218:                 }
 7219:             }
 7220:         }
 7221:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7222:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 7223:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 7224:                        '</span></td><td class="LC_right_item">'.
 7225:                        '<select name="texengine">'."\n";
 7226:         my %texoptions = (
 7227:                             MathJax  => 'MathJax',
 7228:                             mimetex  => &mt('Convert to Images'),
 7229:                             tth      => &mt('TeX to HTML'),
 7230:                          );
 7231:         foreach my $renderer ('MathJax','mimetex','tth') {
 7232:             my $selected = '';
 7233:             if ($renderer eq $deftex) {
 7234:                 $selected = ' selected="selected"';
 7235:             }
 7236:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 7237:         }
 7238:         $mathdisp .= '</select></td></tr>'."\n";
 7239:         $itemcount ++;
 7240:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 7241:                                                      \%choices,$itemcount);
 7242:         $datatable = $mathdisp.$datatable;
 7243:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7244:         $datatable .=
 7245:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 7246:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 7247:             '</span></td><td class="LC_left_item">';
 7248:         my $currcanclone = 'none';
 7249:         my $onclick;
 7250:         my @cloneoptions = ('none','domain');
 7251:         my %clonetitles = &Apache::lonlocal::texthash (
 7252:                              none     => 'No additional course requesters',
 7253:                              domain   => "Any course requester in course's domain",
 7254:                              instcode => 'Course requests for official courses ...',
 7255:                           );
 7256:         my (%codedefaults,@code_order,@posscodes);
 7257:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 7258:                                                     \@code_order) eq 'ok') {
 7259:             if (@code_order > 0) {
 7260:                 push(@cloneoptions,'instcode');
 7261:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 7262:             }
 7263:         }
 7264:         if (ref($settings) eq 'HASH') {
 7265:             if ($settings->{'canclone'}) {
 7266:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 7267:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 7268:                         if (@code_order > 0) {
 7269:                             $currcanclone = 'instcode';
 7270:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 7271:                         }
 7272:                     }
 7273:                 } elsif ($settings->{'canclone'} eq 'domain') {
 7274:                     $currcanclone = $settings->{'canclone'};
 7275:                 }
 7276:             }
 7277:         }
 7278:         foreach my $option (@cloneoptions) {
 7279:             my ($checked,$additional);
 7280:             if ($currcanclone eq $option) {
 7281:                 $checked = ' checked="checked"';
 7282:             }
 7283:             if ($option eq 'instcode') {
 7284:                 if (@code_order) {
 7285:                     my $show = 'none';
 7286:                     if ($checked) {
 7287:                         $show = 'block';
 7288:                     }
 7289:                     $additional = '<div id="cloneinstcode" style="display:'.$show.';" />'.
 7290:                                   &mt('Institutional codes for new and cloned course have identical:').
 7291:                                   '<br />';
 7292:                     foreach my $item (@code_order) {
 7293:                         my $codechk;
 7294:                         if ($checked) {
 7295:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 7296:                                 $codechk = ' checked="checked"';
 7297:                             }
 7298:                         }
 7299:                         $additional .= '<label>'.
 7300:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 7301:                                        $item.'</label>';
 7302:                     }
 7303:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 7304:                 }
 7305:             }
 7306:             $datatable .=
 7307:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 7308:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 7309:                 '</label>&nbsp;'.$additional.'</span><br />';
 7310:         }
 7311:         $datatable .= '</td>'.
 7312:                       '</tr>';
 7313:         $itemcount ++;
 7314:     } else {
 7315:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7316:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 7317:         my $currusecredits = 0;
 7318:         my $postsubmitclient = 1;
 7319:         my $ltiauth = 0;
 7320:         my @types = ('official','unofficial','community','textbook','placement');
 7321:         if (ref($settings) eq 'HASH') {
 7322:             if ($settings->{'ltiauth'}) {
 7323:                 $ltiauth = 1;
 7324:             }
 7325:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 7326:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 7327:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 7328:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 7329:                 }
 7330:             }
 7331:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 7332:                 foreach my $type (@types) {
 7333:                     next if ($type eq 'community');
 7334:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 7335:                     if ($defcredits{$type} ne '') {
 7336:                         $currusecredits = 1;
 7337:                     }
 7338:                 }
 7339:             }
 7340:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 7341:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 7342:                     $postsubmitclient = 0;
 7343:                     foreach my $type (@types) {
 7344:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7345:                     }
 7346:                 } else {
 7347:                     foreach my $type (@types) {
 7348:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 7349:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 7350:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 7351:                             } else {
 7352:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7353:                             }
 7354:                         } else {
 7355:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7356:                         }
 7357:                     }
 7358:                 }
 7359:             } else {
 7360:                 foreach my $type (@types) {
 7361:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7362:                 }
 7363:             }
 7364:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 7365:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 7366:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 7367:                 }
 7368:             } else {
 7369:                 foreach my $type (@types) {
 7370:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 7371:                 }
 7372:             }
 7373:         } else {
 7374:             foreach my $type (@types) {
 7375:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7376:             }
 7377:         }
 7378:         if (!$currdefresponder) {
 7379:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 7380:         } elsif ($currdefresponder < 1) {
 7381:             $currdefresponder = 1;
 7382:         }
 7383:         foreach my $type (@types) {
 7384:             if ($curruploadquota{$type} eq '') {
 7385:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 7386:             }
 7387:         }
 7388:         $datatable .=
 7389:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7390:                 $choices{'anonsurvey_threshold'}.
 7391:                 '</span></td>'.
 7392:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 7393:                 '<input type="text" name="anonsurvey_threshold"'.
 7394:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 7395:                 '</td></tr>'."\n";
 7396:         $itemcount ++;
 7397:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7398:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7399:                       $choices{'uploadquota'}.
 7400:                       '</span></td>'.
 7401:                       '<td style="text-align: right" class="LC_right_item">'.
 7402:                       '<table><tr>';
 7403:         foreach my $type (@types) {
 7404:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7405:                            '<input type="text" name="uploadquota_'.$type.'"'.
 7406:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 7407:         }
 7408:         $datatable .= '</tr></table></td></tr>'."\n";
 7409:         $itemcount ++;
 7410:         my $onclick = "toggleDisplay(this.form,'credits');";
 7411:         my $display = 'none';
 7412:         if ($currusecredits) {
 7413:             $display = 'block';
 7414:         }
 7415:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 7416:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 7417:         foreach my $type (@types) {
 7418:             next if ($type eq 'community');
 7419:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7420:                            '<input type="text" name="'.$type.'_credits"'.
 7421:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 7422:         }
 7423:         $additional .= '</tr></table></div>'."\n";
 7424:         %defaultchecked = ('coursecredits' => 'off');
 7425:         @toggles = ('coursecredits');
 7426:         my $current = {
 7427:                         'coursecredits' => $currusecredits,
 7428:                       };
 7429:         (my $table,$itemcount) =
 7430:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7431:                                \%choices,$itemcount,$onclick,$additional,'left');
 7432:         $datatable .= $table;
 7433:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 7434:         my $display = 'none';
 7435:         if ($postsubmitclient) {
 7436:             $display = 'block';
 7437:         }
 7438:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 7439:                       &mt('Number of seconds submit is disabled').'<br />'.
 7440:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 7441:                       '<table><tr>';
 7442:         foreach my $type (@types) {
 7443:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7444:                            '<input type="text" name="'.$type.'_timeout" value="'.
 7445:                            $deftimeout{$type}.'" size="5" /></td>';
 7446:         }
 7447:         $additional .= '</tr></table></div>'."\n";
 7448:         %defaultchecked = ('postsubmit' => 'on');
 7449:         @toggles = ('postsubmit');
 7450:         $current = {
 7451:                        'postsubmit' => $postsubmitclient,
 7452:                    };
 7453:         ($table,$itemcount) =
 7454:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7455:                                \%choices,$itemcount,$onclick,$additional,'left');
 7456:         $datatable .= $table;
 7457:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7458:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7459:                       $choices{'mysqltables'}.
 7460:                       '</span></td>'.
 7461:                       '<td style="text-align: right" class="LC_right_item">'.
 7462:                       '<table><tr>';
 7463:         foreach my $type (@types) {
 7464:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7465:                            '<input type="text" name="mysqltables_'.$type.'"'.
 7466:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 7467:         }
 7468:         $datatable .= '</tr></table></td></tr>'."\n";
 7469:         $itemcount ++;
 7470:         %defaultchecked = ('ltiauth' => 'off');
 7471:         @toggles = ('ltiauth');
 7472:         $current = {
 7473:                        'ltiauth' => $ltiauth,
 7474:                    };
 7475:         ($table,$itemcount) =
 7476:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7477:                                \%choices,$itemcount,undef,undef,'left');
 7478:         $datatable .= $table;
 7479:         $itemcount ++;
 7480:     }
 7481:     $$rowtotal += $itemcount;
 7482:     return $datatable;
 7483: }
 7484: 
 7485: sub print_selfenrollment {
 7486:     my ($position,$dom,$settings,$rowtotal) = @_;
 7487:     my ($css_class,$datatable);
 7488:     my $itemcount = 1;
 7489:     my @types = ('official','unofficial','community','textbook','placement');
 7490:     if (($position eq 'top') || ($position eq 'middle')) {
 7491:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 7492:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 7493:         my @rows;
 7494:         my $key;
 7495:         if ($position eq 'top') {
 7496:             $key = 'admin'; 
 7497:             if (ref($rowsref) eq 'ARRAY') {
 7498:                 @rows = @{$rowsref};
 7499:             }
 7500:         } elsif ($position eq 'middle') {
 7501:             $key = 'default';
 7502:             @rows = ('types','registered','approval','limit');
 7503:         }
 7504:         foreach my $row (@rows) {
 7505:             if (defined($titlesref->{$row})) {
 7506:                 $itemcount ++;
 7507:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7508:                 $datatable .= '<tr'.$css_class.'>'.
 7509:                               '<td>'.$titlesref->{$row}.'</td>'.
 7510:                               '<td class="LC_left_item">'.
 7511:                               '<table><tr>';
 7512:                 my (%current,%currentcap);
 7513:                 if (ref($settings) eq 'HASH') {
 7514:                     if (ref($settings->{$key}) eq 'HASH') {
 7515:                         foreach my $type (@types) {
 7516:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 7517:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 7518:                             }
 7519:                             if (($row eq 'limit') && ($key eq 'default')) {
 7520:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 7521:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 7522:                                 }
 7523:                             }
 7524:                         }
 7525:                     }
 7526:                 }
 7527:                 my %roles = (
 7528:                              '0' => &Apache::lonnet::plaintext('dc'),
 7529:                             ); 
 7530:             
 7531:                 foreach my $type (@types) {
 7532:                     unless (($row eq 'registered') && ($key eq 'default')) {
 7533:                         $datatable .= '<th>'.&mt($type).'</th>';
 7534:                     }
 7535:                 }
 7536:                 unless (($row eq 'registered') && ($key eq 'default')) {
 7537:                     $datatable .= '</tr><tr>';
 7538:                 }
 7539:                 foreach my $type (@types) {
 7540:                     if ($type eq 'community') {
 7541:                         $roles{'1'} = &mt('Community personnel');
 7542:                     } else {
 7543:                         $roles{'1'} = &mt('Course personnel');
 7544:                     }
 7545:                     $datatable .= '<td style="vertical-align: top">';
 7546:                     if ($position eq 'top') {
 7547:                         my %checked;
 7548:                         if ($current{$type} eq '0') {
 7549:                             $checked{'0'} = ' checked="checked"';
 7550:                         } else {
 7551:                             $checked{'1'} = ' checked="checked"';
 7552:                         }
 7553:                         foreach my $role ('1','0') {
 7554:                             $datatable .= '<span class="LC_nobreak"><label>'.
 7555:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 7556:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 7557:                                           $roles{$role}.'</label></span> ';
 7558:                         }
 7559:                     } else {
 7560:                         if ($row eq 'types') {
 7561:                             my %checked;
 7562:                             if ($current{$type} =~ /^(all|dom)$/) {
 7563:                                 $checked{$1} = ' checked="checked"';
 7564:                             } else {
 7565:                                 $checked{''} = ' checked="checked"';
 7566:                             }
 7567:                             foreach my $val ('','dom','all') {
 7568:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7569:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7570:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7571:                             }
 7572:                         } elsif ($row eq 'registered') {
 7573:                             my %checked;
 7574:                             if ($current{$type} eq '1') {
 7575:                                 $checked{'1'} = ' checked="checked"';
 7576:                             } else {
 7577:                                 $checked{'0'} = ' checked="checked"';
 7578:                             }
 7579:                             foreach my $val ('0','1') {
 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 'approval') {
 7585:                             my %checked;
 7586:                             if ($current{$type} =~ /^([12])$/) {
 7587:                                 $checked{$1} = ' checked="checked"';
 7588:                             } else {
 7589:                                 $checked{'0'} = ' checked="checked"';
 7590:                             }
 7591:                             for my $val (0..2) {
 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 'limit') {
 7597:                             my %checked;
 7598:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 7599:                                 $checked{$1} = ' checked="checked"';
 7600:                             } else {
 7601:                                 $checked{'none'} = ' checked="checked"';
 7602:                             }
 7603:                             my $cap;
 7604:                             if ($currentcap{$type} =~ /^\d+$/) {
 7605:                                 $cap = $currentcap{$type};
 7606:                             }
 7607:                             foreach my $val ('none','allstudents','selfenrolled') {
 7608:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7609:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7610:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7611:                             }
 7612:                             $datatable .= '<br />'.
 7613:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 7614:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 7615:                                           '</span>'; 
 7616:                         }
 7617:                     }
 7618:                     $datatable .= '</td>';
 7619:                 }
 7620:                 $datatable .= '</tr>';
 7621:             }
 7622:             $datatable .= '</table></td></tr>';
 7623:         }
 7624:     } elsif ($position eq 'bottom') {
 7625:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 7626:     }
 7627:     $$rowtotal += $itemcount;
 7628:     return $datatable;
 7629: }
 7630: 
 7631: sub print_validation_rows {
 7632:     my ($caller,$dom,$settings,$rowtotal) = @_;
 7633:     my ($itemsref,$namesref,$fieldsref);
 7634:     if ($caller eq 'selfenroll') { 
 7635:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 7636:     } elsif ($caller eq 'requestcourses') {
 7637:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 7638:     }
 7639:     my %currvalidation;
 7640:     if (ref($settings) eq 'HASH') {
 7641:         if (ref($settings->{'validation'}) eq 'HASH') {
 7642:             %currvalidation = %{$settings->{'validation'}};
 7643:         }
 7644:     }
 7645:     my $datatable;
 7646:     my $itemcount = 0;
 7647:     foreach my $item (@{$itemsref}) {
 7648:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7649:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7650:                       $namesref->{$item}.
 7651:                       '</span></td>'.
 7652:                       '<td class="LC_left_item">';
 7653:         if (($item eq 'url') || ($item eq 'button')) {
 7654:             $datatable .= '<span class="LC_nobreak">'.
 7655:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 7656:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 7657:         } elsif ($item eq 'fields') {
 7658:             my @currfields;
 7659:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 7660:                 @currfields = @{$currvalidation{$item}};
 7661:             }
 7662:             foreach my $field (@{$fieldsref}) {
 7663:                 my $check = '';
 7664:                 if (grep(/^\Q$field\E$/,@currfields)) {
 7665:                     $check = ' checked="checked"';
 7666:                 }
 7667:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7668:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 7669:                               ' value="'.$field.'"'.$check.' />'.$field.
 7670:                               '</label></span> ';
 7671:             }
 7672:         } elsif ($item eq 'markup') {
 7673:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 7674:                            $currvalidation{$item}.
 7675:                               '</textarea>';
 7676:         }
 7677:         $datatable .= '</td></tr>'."\n";
 7678:         if (ref($rowtotal)) {
 7679:             $itemcount ++;
 7680:         }
 7681:     }
 7682:     if ($caller eq 'requestcourses') {
 7683:         my %currhash;
 7684:         if (ref($settings) eq 'HASH') {
 7685:             if (ref($settings->{'validation'}) eq 'HASH') {
 7686:                 if ($settings->{'validation'}{'dc'} ne '') {
 7687:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 7688:                 }
 7689:             }
 7690:         }
 7691:         my $numinrow = 2;
 7692:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 7693:                                                        'validationdc',%currhash);
 7694:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7695:         $datatable .= '<tr'.$css_class.'><td>';
 7696:         if ($numdc > 1) {
 7697:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 7698:         } else {
 7699:             $datatable .=  &mt('Course creation processed as: ');
 7700:         }
 7701:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 7702:         $itemcount ++;
 7703:     }
 7704:     if (ref($rowtotal)) {
 7705:         $$rowtotal += $itemcount;
 7706:     }
 7707:     return $datatable;
 7708: }
 7709: 
 7710: sub print_privacy {
 7711:     my ($position,$dom,$settings,$rowtotal) = @_;
 7712:     my ($datatable,$css_class,$numinrow,@items,%names,$othertitle,$usertypes,$types);
 7713:     my $itemcount = 0;
 7714:     unless ($position eq 'top') {
 7715:         @items = ('domain','author','course','community');
 7716:         %names = &Apache::lonlocal::texthash (
 7717:                      domain => 'Assigned domain role(s)',
 7718:                      author => 'Assigned co-author role(s)',
 7719:                      course => 'Assigned course role(s)',
 7720:                      community => 'Assigned community role',
 7721:                  );
 7722:         $numinrow = 4;
 7723:         ($othertitle,$usertypes,$types) =
 7724:             &Apache::loncommon::sorted_inst_types($dom);
 7725:     }
 7726:     if (($position eq 'top') || ($position eq 'middle')) {
 7727:         my (%by_ip,%by_location,@intdoms,@instdoms);
 7728:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 7729:         if ($position eq 'top') {
 7730:             my %curr;
 7731:             my @options = ('none','user','domain','auto');
 7732:             my %titles = &Apache::lonlocal::texthash (
 7733:                 none   => 'Not allowed',
 7734:                 user   => 'User authorizes',
 7735:                 domain => 'DC authorizes',
 7736:                 auto   => 'Unrestricted',
 7737:                 instdom => 'Other domain shares institution/provider',
 7738:                 extdom => 'Other domain has different institution/provider',
 7739:             );
 7740:             my %names = &Apache::lonlocal::texthash (
 7741:                 domain => 'Domain role',
 7742:                 author => 'Co-author role',
 7743:                 course => 'Course role',
 7744:                 community => 'Community role',
 7745:             );
 7746:             my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7747:             my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7748:             foreach my $domtype ('instdom','extdom') {
 7749:                 my (%checked,$skip);
 7750:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7751:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$domtype}.'</td>'.
 7752:                               '<td class="LC_left_item">';
 7753:                 if ($domtype eq 'instdom') {
 7754:                     unless (@instdoms > 1) {
 7755:                         $datatable .= &mt('Nothing to set, as no domains besides [_1] are hosted by [_2]',$dom,$intdom);
 7756:                         $skip = 1;
 7757:                     }
 7758:                 } elsif ($domtype eq 'extdom') {
 7759:                     if (keys(%by_location) == 0) {
 7760:                         $datatable .= &mt('Nothing to set, as no other hosts besides [_1]',$intdom);
 7761:                         $skip = 1;
 7762:                     }
 7763:                 }
 7764:                 unless ($skip) {
 7765:                     foreach my $roletype ('domain','author','course','community') {
 7766:                         $checked{'auto'} = ' checked="checked"';
 7767:                         if (ref($settings) eq 'HASH') {
 7768:                             if (ref($settings->{approval}) eq 'HASH') {
 7769:                                 if (ref($settings->{approval}->{$domtype}) eq 'HASH') {
 7770:                                     if ($settings->{approval}->{$domtype}->{$roletype}=~ /^(none|user|domain)$/) {
 7771:                                         $checked{$1} = ' checked="checked"';
 7772:                                         $checked{'auto'} = '';
 7773:                                     }
 7774:                                 }
 7775:                             }
 7776:                         }
 7777:                         $datatable .= '<fieldset><legend>'.$names{$roletype}.'</legend>';
 7778:                         foreach my $option (@options) {
 7779:                             $datatable .= '<span class="LC_nobreak"><label>'.
 7780:                                           '<input type="radio" name="privacy_approval_'.$domtype.'_'.$roletype.'" '.
 7781:                                           'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 7782:                                           '</label></span>&nbsp; ';
 7783:                         }
 7784:                         $datatable .= '</fieldset>';
 7785:                     }
 7786:                 }
 7787:                 $datatable .= '</td></tr>';
 7788:                 $itemcount ++;
 7789:             }
 7790:         } elsif ($position eq 'middle') {
 7791:             if ((@instdoms > 1) || (keys(%by_location) > 0)) {
 7792:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7793:                     foreach my $item (@{$types}) {
 7794:                         $datatable .= &modifiable_userdata_row('privacy','othdom_'.$item,$settings,
 7795:                                                                $numinrow,$itemcount,'','','','','',
 7796:                                                                '',$usertypes->{$item});
 7797:                         $itemcount ++;
 7798:                     }
 7799:                 }
 7800:                 $datatable .= &modifiable_userdata_row('privacy','othdom_default',$settings,
 7801:                                                        $numinrow,$itemcount,'','','','','',
 7802:                                                        '',$othertitle);
 7803:                 $itemcount ++;
 7804:             } else {
 7805:                 my (@insttypes,%insttitles);
 7806:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7807:                     @insttypes = @{$types};
 7808:                     %insttitles = %{$usertypes};
 7809:                 }
 7810:                 foreach my $item (@insttypes,'default') {
 7811:                     my $title;
 7812:                     if ($item eq 'default') {
 7813:                         $title = $othertitle;
 7814:                     } else {
 7815:                         $title = $insttitles{$item};
 7816:                     }
 7817:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7818:                     $datatable .= '<tr'.$css_class.'>'.
 7819:                                   '<td class="LC_left_item">'.$title.'</td>'.
 7820:                                   '<td class="LC_left_item">'.
 7821:                                   &mt('Nothing to set here, as there are no other domains').
 7822:                                   '</td></tr>';
 7823:                     $itemcount ++;
 7824:                 }
 7825:             }
 7826:         }
 7827:     } else {
 7828:         my $prefix;
 7829:         if ($position eq 'lower') {
 7830:             $prefix = 'priv';
 7831:         } else {
 7832:             $prefix = 'unpriv';
 7833:         }
 7834:         foreach my $item (@items) {
 7835:             $datatable .= &modifiable_userdata_row('privacy',$prefix.'_'.$item,$settings,
 7836:                                                    $numinrow,$itemcount,'','','','','',
 7837:                                                    '',$names{$item});
 7838:             $itemcount ++;
 7839:         }
 7840:     }
 7841:     if (ref($rowtotal)) {
 7842:         $$rowtotal += $itemcount;
 7843:     }
 7844:     return $datatable;
 7845: }
 7846: 
 7847: sub print_passwords {
 7848:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 7849:     my ($datatable,$css_class);
 7850:     my $itemcount = 0;
 7851:     my %titles = &Apache::lonlocal::texthash (
 7852:         captcha        => '"Forgot Password" CAPTCHA validation',
 7853:         link           => 'Reset link expiration (hours)',
 7854:         case           => 'Case-sensitive usernames/e-mail',
 7855:         prelink        => 'Information required (form 1)',
 7856:         postlink       => 'Information required (form 2)',
 7857:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 7858:         customtext     => 'Domain specific text (HTML)',
 7859:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 7860:         intauth_check  => 'Check bcrypt cost if authenticated',
 7861:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 7862:         permanent      => 'Permanent e-mail address',
 7863:         critical       => 'Critical notification address',
 7864:         notify         => 'Notification address',
 7865:         min            => 'Minimum password length',
 7866:         max            => 'Maximum password length',
 7867:         chars          => 'Required characters',
 7868:         expire         => 'Password expiration (days)',
 7869:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 7870:     );
 7871:     if ($position eq 'top') {
 7872:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7873:         my $shownlinklife = 2;
 7874:         my $prelink = 'both';
 7875:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 7876:         if (ref($settings) eq 'HASH') {
 7877:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 7878:                 $shownlinklife = $settings->{resetlink};
 7879:             }
 7880:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 7881:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 7882:             }
 7883:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 7884:                 $prelink = $settings->{resetprelink};
 7885:             }
 7886:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 7887:                 %postlink = %{$settings->{resetpostlink}};
 7888:             }
 7889:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 7890:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 7891:             }
 7892:             if ($settings->{resetremove}) {
 7893:                 $nostdtext = 1;
 7894:             }
 7895:             if ($settings->{resetcustom}) {
 7896:                 $customurl = $settings->{resetcustom};
 7897:             }
 7898:         } else {
 7899:             if (ref($types) eq 'ARRAY') {
 7900:                 foreach my $item (@{$types}) {
 7901:                     $casesens{$item} = 1;
 7902:                     $postlink{$item} = ['username','email'];
 7903:                 }
 7904:             }
 7905:             $casesens{'default'} = 1;
 7906:             $postlink{'default'} = ['username','email'];
 7907:             $prelink = 'both';
 7908:             %emailsrc = (
 7909:                           permanent => 1,
 7910:                           critical  => 1,
 7911:                           notify    => 1,
 7912:             );
 7913:         }
 7914:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 7915:         $itemcount ++;
 7916:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7917:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 7918:                       '<td class="LC_left_item">'.
 7919:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 7920:                       'name="passwords_link" size="3" /></td></tr>';
 7921:         $itemcount ++;
 7922:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7923:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 7924:                       '<td class="LC_left_item">';
 7925:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7926:             foreach my $item (@{$types}) {
 7927:                 my $checkedcase;
 7928:                 if ($casesens{$item}) {
 7929:                     $checkedcase = ' checked="checked"';
 7930:                 }
 7931:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7932:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 7933:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 7934:                               '</span>&nbsp;&nbsp; ';
 7935:             }
 7936:         }
 7937:         my $checkedcase;
 7938:         if ($casesens{'default'}) {
 7939:             $checkedcase = ' checked="checked"';
 7940:         }
 7941:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 7942:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 7943:                       $othertitle.'</label></span></td>';
 7944:         $itemcount ++;
 7945:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7946:         my %checkedpre = (
 7947:                              both => ' checked="checked"',
 7948:                              either => '',
 7949:                          );
 7950:         if ($prelink eq 'either') {
 7951:             $checkedpre{either} = ' checked="checked"';
 7952:             $checkedpre{both} = '';
 7953:         }
 7954:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 7955:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7956:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 7957:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 7958:                       '<span class="LC_nobreak"><label>'.
 7959:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 7960:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 7961:         $itemcount ++;
 7962:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7963:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 7964:                       '<td class="LC_left_item">';
 7965:         my %postlinked;
 7966:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7967:             foreach my $item (@{$types}) {
 7968:                 undef(%postlinked);
 7969:                 $datatable .= '<fieldset style="display: inline-block;">'.
 7970:                               '<legend>'.$usertypes->{$item}.'</legend>';
 7971:                 if (ref($postlink{$item}) eq 'ARRAY') {
 7972:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 7973:                 }
 7974:                 foreach my $field ('email','username') {
 7975:                     my $checked;
 7976:                     if ($postlinked{$field}) {
 7977:                         $checked = ' checked="checked"';
 7978:                     }
 7979:                     $datatable .= '<span class="LC_nobreak"><label>'.
 7980:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 7981:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 7982:                                   '<span>&nbsp;&nbsp; ';
 7983:                 }
 7984:                 $datatable .= '</fieldset>';
 7985:             }
 7986:         }
 7987:         if (ref($postlink{'default'}) eq 'ARRAY') {
 7988:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 7989:         }
 7990:         $datatable .= '<fieldset style="display: inline-block;">'.
 7991:                       '<legend>'.$othertitle.'</legend>';
 7992:         foreach my $field ('email','username') {
 7993:             my $checked;
 7994:             if ($postlinked{$field}) {
 7995:                 $checked = ' checked="checked"';
 7996:             }
 7997:             $datatable .= '<span class="LC_nobreak"><label>'.
 7998:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 7999:                           $field.'"'.$checked.' />'.$field.'</label>'.
 8000:                           '<span>&nbsp;&nbsp; ';
 8001:         }
 8002:         $datatable .= '</fieldset></td></tr>';
 8003:         $itemcount ++;
 8004:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8005:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 8006:                       '<td class="LC_left_item">';
 8007:         foreach my $type ('permanent','critical','notify') {
 8008:             my $checkedemail;
 8009:             if ($emailsrc{$type}) {
 8010:                 $checkedemail = ' checked="checked"';
 8011:             }
 8012:             $datatable .= '<span class="LC_nobreak"><label>'.
 8013:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 8014:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 8015:                           '<span>&nbsp;&nbsp; ';
 8016:         }
 8017:         $datatable .= '</td></tr>';
 8018:         $itemcount ++;
 8019:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8020:         my $switchserver = &check_switchserver($dom,$confname);
 8021:         my ($showstd,$noshowstd);
 8022:         if ($nostdtext) {
 8023:             $noshowstd = ' checked="checked"';
 8024:         } else {
 8025:             $showstd = ' checked="checked"';
 8026:         }
 8027:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 8028:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8029:                       &mt('Retain standard text:').
 8030:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 8031:                       &mt('Yes').'</label>'.'&nbsp;'.
 8032:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 8033:                       &mt('No').'</label></span><br />'.
 8034:                       '<span class="LC_fontsize_small">'.
 8035:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 8036:                       &mt('Include custom text:');
 8037:         if ($customurl) {
 8038:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('custom text'),600,500,
 8039:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 8040:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 8041:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 8042:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 8043:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 8044:         }
 8045:         if ($switchserver) {
 8046:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 8047:         } else {
 8048:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 8049:                          '<input type="file" name="passwords_customfile" /></span>';
 8050:         }
 8051:         $datatable .= '</td></tr>';
 8052:     } elsif ($position eq 'middle') {
 8053:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 8054:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 8055:         my %defaults;
 8056:         if (ref($domconf{'defaults'}) eq 'HASH') {
 8057:             %defaults = %{$domconf{'defaults'}};
 8058:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 8059:                 $defaults{'intauth_cost'} = 10;
 8060:             }
 8061:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 8062:                 $defaults{'intauth_check'} = 0;
 8063:             }
 8064:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 8065:                 $defaults{'intauth_switch'} = 0;
 8066:             }
 8067:         } else {
 8068:             %defaults = (
 8069:                           'intauth_cost'   => 10,
 8070:                           'intauth_check'  => 0,
 8071:                           'intauth_switch' => 0,
 8072:                         );
 8073:         }
 8074:         foreach my $item (@items) {
 8075:             if ($itemcount%2) {
 8076:                 $css_class = '';
 8077:             } else {
 8078:                 $css_class = ' class="LC_odd_row" ';
 8079:             }
 8080:             $datatable .= '<tr'.$css_class.'>'.
 8081:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 8082:                           '</span></td><td class="LC_left_item" colspan="3">';
 8083:             if ($item eq 'intauth_switch') {
 8084:                 my @options = (0,1,2);
 8085:                 my %optiondesc = &Apache::lonlocal::texthash (
 8086:                                    0 => 'No',
 8087:                                    1 => 'Yes',
 8088:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 8089:                                  );
 8090:                 $datatable .= '<table width="100%">';
 8091:                 foreach my $option (@options) {
 8092:                     my $checked = ' ';
 8093:                     if ($defaults{$item} eq $option) {
 8094:                         $checked = ' checked="checked"';
 8095:                     }
 8096:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 8097:                                   '<label><input type="radio" name="'.$item.
 8098:                                   '" value="'.$option.'"'.$checked.' />'.
 8099:                                   $optiondesc{$option}.'</label></span></td></tr>';
 8100:                 }
 8101:                 $datatable .= '</table>';
 8102:             } elsif ($item eq 'intauth_check') {
 8103:                 my @options = (0,1,2);
 8104:                 my %optiondesc = &Apache::lonlocal::texthash (
 8105:                                    0 => 'No',
 8106:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 8107:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 8108:                                  );
 8109:                 $datatable .= '<table width="100%">';
 8110:                 foreach my $option (@options) {
 8111:                     my $checked = ' ';
 8112:                     my $onclick;
 8113:                     if ($defaults{$item} eq $option) {
 8114:                         $checked = ' checked="checked"';
 8115:                     }
 8116:                     if ($option == 2) {
 8117:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 8118:                     }
 8119:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 8120:                                   '<label><input type="radio" name="'.$item.
 8121:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 8122:                                   $optiondesc{$option}.'</label></span></td></tr>';
 8123:                 }
 8124:                 $datatable .= '</table>';
 8125:             } else {
 8126:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 8127:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 8128:             }
 8129:             $datatable .= '</td></tr>';
 8130:             $itemcount ++;
 8131:         }
 8132:     } elsif ($position eq 'lower') {
 8133:         $datatable .= &password_rules('passwords',\$itemcount,$settings);
 8134:     } else {
 8135:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 8136:         my %ownerchg = (
 8137:                           by  => {},
 8138:                           for => {},
 8139:                        );
 8140:         my %ownertitles = &Apache::lonlocal::texthash (
 8141:                             by  => 'Course owner status(es) allowed',
 8142:                             for => 'Student status(es) allowed',
 8143:                           );
 8144:         if (ref($settings) eq 'HASH') {
 8145:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 8146:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 8147:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 8148:                 }
 8149:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 8150:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 8151:                 }
 8152:             }
 8153:         }
 8154:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8155:         $datatable .= '<tr '.$css_class.'>'.
 8156:                       '<td>'.
 8157:                       &mt('Requirements').'<ul>'.
 8158:                       '<li>'.&mt("Course 'type' is not a Community or Placement Test").'</li>'.
 8159:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 8160:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 8161:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 8162:                       '</ul>'.
 8163:                       '</td>'.
 8164:                       '<td class="LC_left_item">';
 8165:         foreach my $item ('by','for') {
 8166:             $datatable .= '<fieldset style="display: inline-block;">'.
 8167:                           '<legend>'.$ownertitles{$item}.'</legend>';
 8168:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 8169:                 foreach my $type (@{$types}) {
 8170:                     my $checked;
 8171:                     if ($ownerchg{$item}{$type}) {
 8172:                         $checked = ' checked="checked"';
 8173:                     }
 8174:                     $datatable .= '<span class="LC_nobreak"><label>'.
 8175:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 8176:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 8177:                                   '</span>&nbsp;&nbsp; ';
 8178:                 }
 8179:             }
 8180:             my $checked;
 8181:             if ($ownerchg{$item}{'default'}) {
 8182:                 $checked = ' checked="checked"';
 8183:             }
 8184:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 8185:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 8186:                           $othertitle.'</label></span></fieldset>';
 8187:         }
 8188:         $datatable .= '</td></tr>';
 8189:     }
 8190:     return $datatable;
 8191: }
 8192: 
 8193: sub password_rules {
 8194:     my ($prefix,$itemcountref,$settings) = @_;
 8195:     my ($min,$max,%chars,$expire,$numsaved,$numinrow);
 8196:     my %titles;
 8197:     if ($prefix eq 'passwords') {
 8198:         %titles = &Apache::lonlocal::texthash (
 8199:             min            => 'Minimum password length',
 8200:             max            => 'Maximum password length',
 8201:             chars          => 'Required characters',
 8202:         );
 8203:     } elsif ($prefix eq 'secrets') {
 8204:         %titles = &Apache::lonlocal::texthash (
 8205:             min            => 'Minimum secret length',
 8206:             max            => 'Maximum secret length',
 8207:             chars          => 'Required characters',
 8208:         );
 8209:     }
 8210:     $min = $Apache::lonnet::passwdmin;
 8211:     my $datatable;
 8212:     my $itemcount;
 8213:     if (ref($itemcountref)) {
 8214:         $itemcount = $$itemcountref;
 8215:     }
 8216:     if (ref($settings) eq 'HASH') {
 8217:         if ($settings->{min}) {
 8218:             $min = $settings->{min};
 8219:         }
 8220:         if ($settings->{max}) {
 8221:             $max = $settings->{max};
 8222:         }
 8223:         if (ref($settings->{chars}) eq 'ARRAY') {
 8224:             map { $chars{$_} = 1; } (@{$settings->{chars}});
 8225:         }
 8226:         if ($prefix eq 'passwords') { 
 8227:             if ($settings->{expire}) {
 8228:                 $expire = $settings->{expire};
 8229:             }
 8230:             if ($settings->{numsaved}) {
 8231:                 $numsaved = $settings->{numsaved};
 8232:             }
 8233:         }
 8234:     }
 8235:     my %rulenames = &Apache::lonlocal::texthash(
 8236:                                                  uc => 'At least one upper case letter',
 8237:                                                  lc => 'At least one lower case letter',
 8238:                                                  num => 'At least one number',
 8239:                                                  spec => 'At least one non-alphanumeric',
 8240:                                                );
 8241:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8242:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 8243:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 8244:                   '<input type="text" name="'.$prefix.'_min" value="'.$min.'" size="3" '.
 8245:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8246:                   '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
 8247:                   '</span></td></tr>';
 8248:     $itemcount ++;
 8249:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8250:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 8251:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 8252:                   '<input type="text" name="'.$prefix.'_max" value="'.$max.'" size="3" '.
 8253:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8254:                   '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 8255:                   '</span></td></tr>';
 8256:     $itemcount ++;
 8257:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8258:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 8259:                   '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 8260:                   '</span></td>';
 8261:     my $numinrow = 2;
 8262:     my @possrules = ('uc','lc','num','spec');
 8263:     $datatable .= '<td class="LC_left_item"><table>';
 8264:     for (my $i=0; $i<@possrules; $i++) {
 8265:         my ($rem,$checked);
 8266:         if ($chars{$possrules[$i]}) {
 8267:             $checked = ' checked="checked"';
 8268:         }
 8269:         $rem = $i%($numinrow);
 8270:         if ($rem == 0) {
 8271:             if ($i > 0) {
 8272:                 $datatable .= '</tr>';
 8273:             }
 8274:             $datatable .= '<tr>';
 8275:         }
 8276:         $datatable .= '<td><span class="LC_nobreak"><label>'.
 8277:                       '<input type="checkbox" name="'.$prefix.'_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 8278:                       $rulenames{$possrules[$i]}.'</label></span></td>';
 8279:     }
 8280:     my $rem = @possrules%($numinrow);
 8281:     my $colsleft = $numinrow - $rem;
 8282:     if ($colsleft > 1 ) {
 8283:         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8284:                       '&nbsp;</td>';
 8285:     } elsif ($colsleft == 1) {
 8286:         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 8287:     }
 8288:     $datatable .='</table></td></tr>';
 8289:     $itemcount ++;
 8290:     if ($prefix eq 'passwords') {
 8291:         $titles{'expire'} = &mt('Password expiration (days)');
 8292:         $titles{'numsaved'} = &mt('Number of previous passwords to save and disallow reuse');
 8293:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8294:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'expire'}.'</td>'.
 8295:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8296:                       '<input type="text" name="'.$prefix.'_expire" value="'.$expire.'" size="4" '.
 8297:                       'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8298:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no expiration)').'</span>'.
 8299:                       '</span></td></tr>';
 8300:         $itemcount ++;
 8301:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8302:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 8303:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8304:                       '<input type="text" name="'.$prefix.'_numsaved" value="'.$numsaved.'" size="3" '.
 8305:                       'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8306:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 8307:                       '</span></td></tr>';
 8308:         $itemcount ++;
 8309:     }
 8310:     if (ref($itemcountref)) {
 8311:         $$itemcountref += $itemcount;
 8312:     }
 8313:     return $datatable;
 8314: }
 8315: 
 8316: sub print_wafproxy {
 8317:     my ($position,$dom,$settings,$rowtotal) = @_;
 8318:     my $css_class;
 8319:     my $itemcount = 0;
 8320:     my $datatable;
 8321:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8322:     my (%othercontrol,%otherdoms,%aliases,%saml,%values,$setdom,$showdom);
 8323:     my %lt = &wafproxy_titles();
 8324:     foreach my $server (sort(keys(%servers))) {
 8325:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
 8326:         next if ($serverhome eq '');
 8327:         my $serverdom;
 8328:         if ($serverhome ne $server) {
 8329:             $serverdom = &Apache::lonnet::host_domain($serverhome);
 8330:             if (($serverdom ne '') && (&Apache::lonnet::domain($serverdom) ne '')) {
 8331:                 $othercontrol{$server} = $serverdom;
 8332:             }
 8333:         } else {
 8334:             $serverdom = &Apache::lonnet::host_domain($server);
 8335:             next if (($serverdom eq '') || (&Apache::lonnet::domain($serverdom) eq ''));
 8336:             if ($serverdom ne $dom) {
 8337:                 $othercontrol{$server} = $serverdom;
 8338:             } else {
 8339:                 $setdom = 1;
 8340:                 if (ref($settings) eq 'HASH') {
 8341:                     if (ref($settings->{'alias'}) eq 'HASH') {
 8342:                         $aliases{$dom} = $settings->{'alias'};
 8343:                         if ($aliases{$dom} ne '') {
 8344:                             $showdom = 1;
 8345:                         }
 8346:                     }
 8347:                     if (ref($settings->{'saml'}) eq 'HASH') {
 8348:                         $saml{$dom} = $settings->{'saml'};
 8349:                     }
 8350:                 }
 8351:             }
 8352:         }
 8353:     }
 8354:     if ($setdom) {
 8355:         %{$values{$dom}} = ();
 8356:         if (ref($settings) eq 'HASH') {
 8357:             foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 8358:                 $values{$dom}{$item} = $settings->{$item};
 8359:             }
 8360:         }
 8361:     }
 8362:     if (keys(%othercontrol)) {
 8363:         %otherdoms = reverse(%othercontrol);
 8364:         foreach my $domain (keys(%otherdoms)) {
 8365:             %{$values{$domain}} = ();
 8366:             my %config = &Apache::lonnet::get_dom('configuration',['wafproxy'],$domain);
 8367:             if (ref($config{'wafproxy'}) eq 'HASH') {
 8368:                 $aliases{$domain} = $config{'wafproxy'}{'alias'};
 8369:                 if (exists($config{'wafproxy'}{'saml'})) { 
 8370:                     $saml{$domain} = $config{'wafproxy'}{'saml'};
 8371:                 }
 8372:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 8373:                     $values{$domain}{$item} = $config{'wafproxy'}{$item};
 8374:                 }
 8375:             }
 8376:         }
 8377:     }
 8378:     if ($position eq 'top') {
 8379:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8380:         my %aliasinfo;
 8381:         foreach my $server (sort(keys(%servers))) {
 8382:             $itemcount ++;
 8383:             my $dom_in_effect;
 8384:             my $aliasrows = '<tr>'.
 8385:                             '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8386:                             &mt('Hostname').':&nbsp;'.
 8387:                             '<i>'.&Apache::lonnet::hostname($server).'</i></td><td>&nbsp;</td>';
 8388:             if ($othercontrol{$server}) {
 8389:                 $dom_in_effect = $othercontrol{$server};
 8390:                 my ($current,$forsaml);
 8391:                 if (ref($aliases{$dom_in_effect}) eq 'HASH') {
 8392:                     $current = $aliases{$dom_in_effect}{$server};
 8393:                 }
 8394:                 if (ref($saml{$dom_in_effect}) eq 'HASH') {
 8395:                     if ($saml{$dom_in_effect}{$server}) {
 8396:                         $forsaml = 1;
 8397:                     }
 8398:                 }
 8399:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8400:                               &mt('Alias').':&nbsp';
 8401:                 if ($current) {
 8402:                     $aliasrows .= $current;
 8403:                     if ($forsaml) {
 8404:                          $aliasrows .= '&nbsp;('.&mt('also for SSO Auth').')';
 8405:                     }
 8406:                 } else {
 8407:                     $aliasrows .= &mt('None');
 8408:                 }
 8409:                 $aliasrows .= '&nbsp;<span class="LC_small">('.
 8410:                               &mt('controlled by domain: [_1]',
 8411:                                   '<b>'.$dom_in_effect.'</b>').')</span></td>';
 8412:             } else {
 8413:                 $dom_in_effect = $dom;
 8414:                 my ($current,$samlon,$samloff);
 8415:                 $samloff = ' checked="checked"';
 8416:                 if (ref($aliases{$dom}) eq 'HASH') {
 8417:                     if ($aliases{$dom}{$server}) {
 8418:                         $current = $aliases{$dom}{$server};
 8419:                     }
 8420:                 }
 8421:                 if (ref($saml{$dom}) eq 'HASH') {
 8422:                     if ($saml{$dom}{$server}) {
 8423:                         $samlon = $samloff;
 8424:                         undef($samloff);
 8425:                     }
 8426:                 }
 8427:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8428:                               &mt('Alias').':&nbsp;'.
 8429:                               '<input type="text" name="wafproxy_alias_'.$server.'" '.
 8430:                               'value="'.$current.'" size="30" />'.
 8431:                               ('&nbsp;'x2).'<span class="LC_nobreak">'.
 8432:                               &mt('Alias used for SSO Auth').':&nbsp;<label>'.
 8433:                               '<input type="radio" value="0"'.$samloff.' name="wafproxy_alias_saml_'.$server.'" />'.
 8434:                               &mt('No').'</label>&nbsp;<label>'. 
 8435:                               '<input type="radio" value="1"'.$samlon.' name="wafproxy_alias_saml_'.$server.'" />'.
 8436:                               &mt('Yes').'</label></span>'.
 8437:                               '</td>'; 
 8438:             }
 8439:             $aliasrows .= '</tr>';
 8440:             $aliasinfo{$dom_in_effect} .= $aliasrows;
 8441:         }
 8442:         if ($aliasinfo{$dom}) {
 8443:             my ($onclick,$wafon,$wafoff,$showtable);
 8444:             $onclick = ' onclick="javascript:toggleWAF();"';
 8445:             $wafoff = ' checked="checked"';
 8446:             $showtable = ' style="display:none";';
 8447:             if ($showdom) {
 8448:                 $wafon = $wafoff;
 8449:                 $wafoff = '';
 8450:                 $showtable = ' style="display:inline;"';
 8451:             }
 8452:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8453:             $datatable = '<tr'.$css_class.'>'.
 8454:                          '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
 8455:                          '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
 8456:                          '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
 8457:                          &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
 8458:                          '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
 8459:                          &mt('No').'</label></span></td>'.
 8460:                          '<td class="LC_left_item">'.
 8461:                          '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
 8462:                          '</table></td></tr>';
 8463:             $itemcount++;
 8464:         }
 8465:         if (keys(%otherdoms)) {
 8466:             foreach my $key (sort(keys(%otherdoms))) {
 8467:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8468:                 $datatable .= '<tr'.$css_class.'>'.
 8469:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
 8470:                               '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
 8471:                               '</table></td></tr>';
 8472:                 $itemcount++;
 8473:             }
 8474:         }
 8475:     } else {
 8476:         my %ip_methods = &remoteip_methods();
 8477:         if ($setdom) {
 8478:             $itemcount ++;
 8479:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8480:             my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
 8481:                 $currwafvpn,$wafrangestyle,$alltossl,$ssltossl);
 8482:             $wafstyle = ' style="display:none;"';
 8483:             $nowafstyle = ' style="display:table-row;"';
 8484:             $currwafdisplay = ' style="display: none"';
 8485:             $wafrangestyle = ' style="display: none"';
 8486:             $curr_remotip = 'n';
 8487:             $ssltossl = ' checked="checked"';
 8488:             if ($showdom) {
 8489:                 $wafstyle = ' style="display:table-row;"';
 8490:                 $nowafstyle =  ' style="display:none;"';
 8491:                 if (keys(%{$values{$dom}})) {
 8492:                     if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
 8493:                         $curr_remotip = $values{$dom}{remoteip};
 8494:                     }
 8495:                     if ($curr_remotip eq 'h') {
 8496:                         $currwafdisplay = ' style="display:table-row"';
 8497:                         $wafrangestyle = ' style="display:inline-block;"';
 8498:                     }
 8499:                     if ($values{$dom}{'sslopt'}) {
 8500:                         $alltossl = ' checked="checked"';
 8501:                         $ssltossl = '';
 8502:                     }
 8503:                 }
 8504:                 if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
 8505:                     $vpndircheck = ' checked="checked"';
 8506:                     $currwafvpn = ' style="display:table-row;"';
 8507:                     $wafrangestyle = ' style="display:inline-block;"';
 8508:                 } else {
 8509:                     $vpnaliascheck = ' checked="checked"';
 8510:                     $currwafvpn = ' style="display:none;"';
 8511:                 }
 8512:             }
 8513:             $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 8514:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
 8515:                           '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
 8516:                           '</tr>'.
 8517:                           '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 8518:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
 8519:                           '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
 8520:                           &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 8521:                           &mt('Range(s) stored in CIDR notation').'</div></td>'.
 8522:                           '<td class="LC_left_item"><table>'.
 8523:                           '<tr>'.
 8524:                           '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
 8525:                           '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
 8526:             foreach my $option ('m','h','n') {
 8527:                 my $sel;
 8528:                 if ($option eq $curr_remotip) {
 8529:                    $sel = ' selected="selected"';
 8530:                 }
 8531:                 $datatable .= '<option value="'.$option.'"'.$sel.'>'.
 8532:                               $ip_methods{$option}.'</option>';
 8533:             }
 8534:             $datatable .= '</select></td></tr>'."\n".
 8535:                           '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
 8536:                           $lt{'ipheader'}.':&nbsp;'.
 8537:                           '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
 8538:                           'name="wafproxy_ipheader" />'.
 8539:                           '</td></tr>'."\n".
 8540:                           '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
 8541:                           $lt{'trusted'}.':<br />'.
 8542:                           '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
 8543:                           $values{$dom}{'trusted'}.'</textarea>'.
 8544:                           '</td></tr>'."\n".
 8545:                           '<tr><td><hr /></td></tr>'."\n".
 8546:                           '<tr>'.
 8547:                           '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
 8548:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
 8549:                           $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
 8550:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
 8551:                           $lt{'vpnaliased'}.'</label></span></td></tr>';
 8552:             foreach my $item ('vpnint','vpnext') {
 8553:                 $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
 8554:                               '<td valign="top">'.$lt{$item}.':<br />'.
 8555:                               '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
 8556:                               $values{$dom}{$item}.'</textarea>'.
 8557:                               '</td></tr>'."\n";
 8558:             }
 8559:             $datatable .= '<tr><td><hr /></td></tr>'."\n".
 8560:                           '<tr>'.
 8561:                           '<td valign="top">'.$lt{'sslopt'}.':<br /><span class="LC_nobreak">'.
 8562:                           '<label><input type="radio" name="wafproxy_sslopt"'.$alltossl.' value="1" />'.
 8563:                           $lt{'alltossl'}.'</label>'.('&nbsp;'x2).
 8564:                           '<label><input type="radio" name="wafproxy_sslopt"'.$ssltossl.' value="0" />'.
 8565:                           $lt{'ssltossl'}.'</label></span></td></tr>'."\n".
 8566:                           '</table></td></tr>';
 8567:         }
 8568:         if (keys(%otherdoms)) {
 8569:             foreach my $domain (sort(keys(%otherdoms))) {
 8570:                 $itemcount ++;
 8571:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8572:                 $datatable .= '<tr'.$css_class.'>'.
 8573:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$domain.'</b>').'</td>'.
 8574:                               '<td class="LC_left_item"><table>';
 8575:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
 8576:                     my $showval = &mt('None');
 8577:                     if ($item eq 'ssl') {
 8578:                         $showval = $lt{'ssltossl'};
 8579:                     }
 8580:                     if ($values{$domain}{$item}) {
 8581:                         $showval = $values{$domain}{$item};
 8582:                         if ($item eq 'ssl') {
 8583:                             $showval = $lt{'alltossl'};
 8584:                         } elsif ($item eq 'remoteip') {
 8585:                             $showval = $ip_methods{$values{$domain}{$item}};
 8586:                         }
 8587:                     }
 8588:                     $datatable .= '<tr>'.
 8589:                                   '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
 8590:                 }
 8591:                 $datatable .= '</table></td></tr>';
 8592:             }
 8593:         }
 8594:     }
 8595:     $$rowtotal += $itemcount;
 8596:     return $datatable;
 8597: }
 8598: 
 8599: sub wafproxy_titles {
 8600:     return &Apache::lonlocal::texthash(
 8601:                remoteip   => "Method for determining user's IP",
 8602:                ipheader   => 'Request header containing remote IP',
 8603:                trusted    => 'Trusted IP range(s)',
 8604:                vpnaccess  => 'Access from institutional VPN',
 8605:                vpndirect  => 'via regular hostname (no WAF)',
 8606:                vpnaliased => 'via aliased hostname (WAF)',
 8607:                vpnint     => 'Internal IP Range(s) for VPN sessions',
 8608:                vpnext     => 'IP Range(s) for backend WAF connections',
 8609:                sslopt     => 'Forwarding http/https',
 8610:                alltossl   => 'WAF forwards both http and https requests to https',
 8611:                ssltossl   => 'WAF forwards http requests to http and https to https',
 8612:            );
 8613: }
 8614: 
 8615: sub remoteip_methods {
 8616:     return &Apache::lonlocal::texthash(
 8617:               m => 'Use Apache mod_remoteip',
 8618:               h => 'Use headers parsed by LON-CAPA',
 8619:               n => 'Not in use',
 8620:            );
 8621: }
 8622: 
 8623: sub print_usersessions {
 8624:     my ($position,$dom,$settings,$rowtotal) = @_;
 8625:     my ($css_class,$datatable,$itemcount,%checked,%choices);
 8626:     my (%by_ip,%by_location,@intdoms,@instdoms);
 8627:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8628: 
 8629:     my @alldoms = &Apache::lonnet::all_domains();
 8630:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 8631:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8632:     my %altids = &id_for_thisdom(%servers);
 8633:     if ($position eq 'top') {
 8634:         if (keys(%serverhomes) > 1) {
 8635:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 8636:             my ($curroffloadnow,$curroffloadoth);
 8637:             if (ref($settings) eq 'HASH') {
 8638:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 8639:                     $curroffloadnow = $settings->{'offloadnow'};
 8640:                 }
 8641:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 8642:                     $curroffloadoth = $settings->{'offloadoth'};
 8643:                 }
 8644:             }
 8645:             my $other_insts = scalar(keys(%by_location));
 8646:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 8647:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 8648:         } else {
 8649:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 8650:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.').
 8651:                           '</td></tr>';
 8652:         }
 8653:     } else {
 8654:         my %titles = &usersession_titles();
 8655:         my ($prefix,@types);
 8656:         if ($position eq 'bottom') {
 8657:             $prefix = 'remote';
 8658:             @types = ('version','excludedomain','includedomain');
 8659:         } else {
 8660:             $prefix = 'hosted';
 8661:             @types = ('excludedomain','includedomain');
 8662:         }
 8663:         ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8664:     }
 8665:     $$rowtotal += $itemcount;
 8666:     return $datatable;
 8667: }
 8668: 
 8669: sub rules_by_location {
 8670:     my ($settings,$prefix,$by_location,$by_ip,$types,$titles) = @_; 
 8671:     my ($datatable,$itemcount,$css_class);
 8672:     if (keys(%{$by_location}) == 0) {
 8673:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8674:         $datatable = '<tr'.$css_class.'><td colspan="2">'.
 8675:                      &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.').
 8676:                      '</td></tr>';
 8677:         $itemcount = 1;
 8678:     } else {
 8679:         $itemcount = 0;
 8680:         my $numinrow = 5;
 8681:         my (%current,%checkedon,%checkedoff);
 8682:         my @locations = sort(keys(%{$by_location}));
 8683:         foreach my $type (@{$types}) {
 8684:             $checkedon{$type} = '';
 8685:             $checkedoff{$type} = ' checked="checked"';
 8686:         }
 8687:         if (ref($settings) eq 'HASH') {
 8688:             if (ref($settings->{$prefix}) eq 'HASH') {
 8689:                 foreach my $key (keys(%{$settings->{$prefix}})) {
 8690:                     $current{$key} = $settings->{$prefix}{$key};
 8691:                     if ($key eq 'version') {
 8692:                         if ($current{$key} ne '') {
 8693:                             $checkedon{$key} = ' checked="checked"';
 8694:                             $checkedoff{$key} = '';
 8695:                         }
 8696:                     } elsif (ref($current{$key}) eq 'ARRAY') {
 8697:                         $checkedon{$key} = ' checked="checked"';
 8698:                         $checkedoff{$key} = '';
 8699:                     }
 8700:                 }
 8701:             }
 8702:         }
 8703:         foreach my $type (@{$types}) {
 8704:             next if ($type ne 'version' && !@locations);
 8705:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8706:             $datatable .= '<tr'.$css_class.'>
 8707:                            <td><span class="LC_nobreak">'.$titles->{$type}.'</span><br />
 8708:                            <span class="LC_nobreak">&nbsp;
 8709:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 8710:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 8711:             if ($type eq 'version') {
 8712:                 my @lcversions = &Apache::lonnet::all_loncaparevs();
 8713:                 my $selector = '<select name="'.$prefix.'_version">';
 8714:                 foreach my $version (@lcversions) {
 8715:                     my $selected = '';
 8716:                     if ($current{'version'} eq $version) {
 8717:                         $selected = ' selected="selected"';
 8718:                     }
 8719:                     $selector .= ' <option value="'.$version.'"'.
 8720:                                  $selected.'>'.$version.'</option>';
 8721:                 }
 8722:                 $selector .= '</select> ';
 8723:                 $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 8724:             } else {
 8725:                 $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 8726:                              'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 8727:                              ' />'.('&nbsp;'x2).
 8728:                              '<input type="button" value="'.&mt('uncheck all').'" '.
 8729:                              'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 8730:                              "\n".
 8731:                              '</div><div><table>';
 8732:                 my $rem;
 8733:                 for (my $i=0; $i<@locations; $i++) {
 8734:                     my ($showloc,$value,$checkedtype);
 8735:                     if (ref($by_location->{$locations[$i]}) eq 'ARRAY') {
 8736:                         my $ip = $by_location->{$locations[$i]}->[0];
 8737:                         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8738:                             $value = join(':',@{$by_ip->{$ip}});
 8739:                             $showloc = join(', ',@{$by_ip->{$ip}});
 8740:                             if (ref($current{$type}) eq 'ARRAY') {
 8741:                                 foreach my $loc (@{$by_ip->{$ip}}) {
 8742:                                     if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 8743:                                         $checkedtype = ' checked="checked"';
 8744:                                         last;
 8745:                                     }
 8746:                                 }
 8747:                             }
 8748:                         }
 8749:                     }
 8750:                     $rem = $i%($numinrow);
 8751:                     if ($rem == 0) {
 8752:                         if ($i > 0) {
 8753:                             $datatable .= '</tr>';
 8754:                         }
 8755:                         $datatable .= '<tr>';
 8756:                     }
 8757:                     $datatable .= '<td class="LC_left_item">'.
 8758:                                   '<span class="LC_nobreak"><label>'.
 8759:                                   '<input type="checkbox" name="'.$prefix.'_'.$type.
 8760:                                   '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 8761:                                   '</label></span></td>';
 8762:                 }
 8763:                 $rem = @locations%($numinrow);
 8764:                 my $colsleft = $numinrow - $rem;
 8765:                 if ($colsleft > 1 ) {
 8766:                     $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8767:                                   '&nbsp;</td>';
 8768:                 } elsif ($colsleft == 1) {
 8769:                     $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 8770:                 }
 8771:                 $datatable .= '</tr></table>';
 8772:             }
 8773:             $datatable .= '</td></tr>';
 8774:             $itemcount ++;
 8775:         }
 8776:     }
 8777:     return ($datatable,$itemcount);
 8778: }
 8779: 
 8780: sub print_ssl {
 8781:     my ($position,$dom,$settings,$rowtotal) = @_;
 8782:     my ($css_class,$datatable);
 8783:     my $itemcount = 1;
 8784:     if ($position eq 'top') {
 8785:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 8786:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 8787:         my $same_institution;
 8788:         if ($intdom ne '') {
 8789:             my $internet_names = &Apache::lonnet::get_internet_names($Apache::lonnet::perlvar{'lonHostID'});
 8790:             if (ref($internet_names) eq 'ARRAY') {
 8791:                 if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 8792:                     $same_institution = 1;
 8793:                 }
 8794:             }
 8795:         }
 8796:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8797:         $datatable = '<tr'.$css_class.'><td colspan="2">';
 8798:         if ($same_institution) {
 8799:             my %domservers = &Apache::lonnet::get_servers($dom);
 8800:             $datatable .= &LONCAPA::SSL::print_certstatus(\%domservers,'web','domprefs');
 8801:         } else {
 8802:             $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.");
 8803:         }
 8804:         $datatable .= '</td></tr>';
 8805:         $itemcount ++;
 8806:     } else {
 8807:         my %titles = &ssl_titles();
 8808:         my (%by_ip,%by_location,@intdoms,@instdoms);
 8809:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8810:         my @alldoms = &Apache::lonnet::all_domains();
 8811:         my %serverhomes = %Apache::lonnet::serverhomeIDs;
 8812:         my @domservers = &Apache::lonnet::get_servers($dom);
 8813:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8814:         my %altids = &id_for_thisdom(%servers);
 8815:         if (($position eq 'connto') || ($position eq 'connfrom')) {
 8816:             my $legacy;
 8817:             unless (ref($settings) eq 'HASH') {
 8818:                 my $name;
 8819:                 if ($position eq 'connto') {
 8820:                     $name = 'loncAllowInsecure';
 8821:                 } else {
 8822:                     $name = 'londAllowInsecure';
 8823:                 }
 8824:                 my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
 8825:                 my @ids=&Apache::lonnet::current_machine_ids();
 8826:                 if (($primarylibserv ne '') && (!grep(/^\Q$primarylibserv\E$/,@ids))) {
 8827:                     my %what = (
 8828:                                    $name => 1,
 8829:                                );
 8830:                     my ($result,$returnhash) =
 8831:                         &Apache::lonnet::get_remote_globals($primarylibserv,\%what);
 8832:                     if ($result eq 'ok') {
 8833:                         if (ref($returnhash) eq 'HASH') {
 8834:                             $legacy = $returnhash->{$name};
 8835:                         }
 8836:                     }
 8837:                 } else {
 8838:                     $legacy = $Apache::lonnet::perlvar{$name};
 8839:                 }
 8840:             }
 8841:             foreach my $type ('dom','intdom','other') {
 8842:                 my %checked;
 8843:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8844:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$type}.'</td>'.
 8845:                               '<td class="LC_right_item">';
 8846:                 my $skip; 
 8847:                 if ($type eq 'dom') {
 8848:                     unless (keys(%servers) > 1) {
 8849:                         $datatable .= &mt('Nothing to set here, as there are no other servers/VMs');    
 8850:                         $skip = 1;
 8851:                     }
 8852:                 }
 8853:                 if ($type eq 'intdom') {
 8854:                     unless (@instdoms > 1) {
 8855:                         $datatable .= &mt('Nothing to set here, as there are no other domains for this institution');
 8856:                         $skip = 1;
 8857:                     } 
 8858:                 } elsif ($type eq 'other') {
 8859:                     if (keys(%by_location) == 0) {
 8860:                         $datatable .= &mt('Nothing to set here, as there are no other institutions');
 8861:                         $skip = 1;
 8862:                     }
 8863:                 }
 8864:                 unless ($skip) {
 8865:                     $checked{'yes'} = ' checked="checked"'; 
 8866:                     if (ref($settings) eq 'HASH') {
 8867:                         if (ref($settings->{$position}) eq 'HASH') {
 8868:                             if ($settings->{$position}->{$type} =~ /^(no|req)$/) {
 8869:                                 $checked{$1} = $checked{'yes'};
 8870:                                 delete($checked{'yes'}); 
 8871:                             }
 8872:                         }
 8873:                     } else {
 8874:                         if ($legacy == 0) {
 8875:                             $checked{'req'} = $checked{'yes'};
 8876:                             delete($checked{'yes'});    
 8877:                         }
 8878:                     }
 8879:                     foreach my $option ('no','yes','req') {
 8880:                         $datatable .= '<span class="LC_nobreak"><label>'.
 8881:                                       '<input type="radio" name="'.$position.'_'.$type.'" '.
 8882:                                       'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 8883:                                       '</label></span>'.('&nbsp;'x2);
 8884:                     }
 8885:                 }
 8886:                 $datatable .= '</td></tr>';
 8887:                 $itemcount ++; 
 8888:             }
 8889:         } else {
 8890:             my $prefix = 'replication';
 8891:             my @types = ('certreq','nocertreq');
 8892:             if (keys(%by_location) == 0) {
 8893:                 $datatable .= '<tr'.$css_class.'><td>'.
 8894:                               &mt('Nothing to set here, as there are no other institutions').
 8895:                               '</td></tr>';
 8896:                 $itemcount ++;
 8897:             } else {
 8898:                 ($datatable,$itemcount) = 
 8899:                     &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8900:             }
 8901:         }
 8902:     }
 8903:     $$rowtotal += $itemcount;
 8904:     return $datatable;
 8905: }
 8906: 
 8907: sub ssl_titles {
 8908:     return &Apache::lonlocal::texthash (
 8909:                dom           => 'LON-CAPA servers/VMs from same domain',
 8910:                intdom        => 'LON-CAPA servers/VMs from same "internet" domain',
 8911:                other         => 'External LON-CAPA servers/VMs',
 8912:                connto        => 'Connections to other servers',
 8913:                connfrom      => 'Connections from other servers',
 8914:                replication   => 'Replicating content to other institutions',
 8915:                certreq       => 'Client certificate required, but specific domains exempt',
 8916:                nocertreq     => 'No client certificate required, except for specific domains',
 8917:                no            => 'SSL not used',
 8918:                yes           => 'SSL Optional (used if available)',
 8919:                req           => 'SSL Required',
 8920:     );
 8921: }
 8922: 
 8923: sub print_trust {
 8924:     my ($prefix,$dom,$settings,$rowtotal) = @_;
 8925:     my ($css_class,$datatable,%checked,%choices);
 8926:     my (%by_ip,%by_location,@intdoms,@instdoms);
 8927:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8928:     my $itemcount = 1;
 8929:     my %titles = &trust_titles();
 8930:     my @types = ('exc','inc');
 8931:     if ($prefix eq 'top') {
 8932:         $prefix = 'content';
 8933:     } elsif ($prefix eq 'bottom') {
 8934:         $prefix = 'msg';
 8935:     }
 8936:     ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8937:     $$rowtotal += $itemcount;
 8938:     return $datatable;
 8939: }
 8940: 
 8941: sub trust_titles {
 8942:     return &Apache::lonlocal::texthash(
 8943:                content  => "Access to this domain's content by others",
 8944:                shared   => "Access to other domain's content by this domain",
 8945:                enroll   => "Enrollment in this domain's courses by others", 
 8946:                othcoau  => "Co-author roles in this domain for others",
 8947:                coaurem  => "Co-author roles for this domain's users elsewhere", 
 8948:                domroles => "Domain roles in this domain assignable to others",
 8949:                catalog  => "Course Catalog for this domain displayed elsewhere",
 8950:                reqcrs   => "Requests for creation of courses in this domain by others",
 8951:                msg      => "Users in other domains can send messages to this domain",
 8952:                exc      => "Allow all, but exclude specific domains",
 8953:                inc      => "Deny all, but include specific domains",
 8954:            );
 8955: } 
 8956: 
 8957: sub build_location_hashes {
 8958:     my ($intdoms,$by_ip,$by_location,$instdoms) = @_;
 8959:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 8960:                   (ref($by_location) eq 'HASH') && (ref($instdoms) eq 'ARRAY'));
 8961:     my %iphost = &Apache::lonnet::get_iphost();
 8962:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 8963:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 8964:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 8965:         foreach my $id (@{$iphost{$primary_ip}}) {
 8966:             my $intdom = &Apache::lonnet::internet_dom($id);
 8967:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 8968:                 push(@{$intdoms},$intdom);
 8969:             }
 8970:         }
 8971:     }
 8972:     foreach my $ip (keys(%iphost)) {
 8973:         if (ref($iphost{$ip}) eq 'ARRAY') {
 8974:             foreach my $id (@{$iphost{$ip}}) {
 8975:                 my $location = &Apache::lonnet::internet_dom($id);
 8976:                 if ($location) {
 8977:                     if (grep(/^\Q$location\E$/,@{$intdoms})) {
 8978:                         my $dom = &Apache::lonnet::host_domain($id);
 8979:                         unless (grep(/^\Q$dom\E/,@{$instdoms})) {
 8980:                             push(@{$instdoms},$dom);
 8981:                         }
 8982:                         next;
 8983:                     }
 8984:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8985:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 8986:                             push(@{$by_ip->{$ip}},$location);
 8987:                         }
 8988:                     } else {
 8989:                         $by_ip->{$ip} = [$location];
 8990:                     }
 8991:                 }
 8992:             }
 8993:         }
 8994:     }
 8995:     foreach my $ip (sort(keys(%{$by_ip}))) {
 8996:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8997:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 8998:             my $first = $by_ip->{$ip}->[0];
 8999:             if (ref($by_location->{$first}) eq 'ARRAY') {
 9000:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 9001:                     push(@{$by_location->{$first}},$ip);
 9002:                 }
 9003:             } else {
 9004:                 $by_location->{$first} = [$ip];
 9005:             }
 9006:         }
 9007:     }
 9008:     return;
 9009: }
 9010: 
 9011: sub current_offloads_to {
 9012:     my ($dom,$settings,$servers) = @_;
 9013:     my (%spareid,%otherdomconfigs);
 9014:     if (ref($servers) eq 'HASH') {
 9015:         foreach my $lonhost (sort(keys(%{$servers}))) {
 9016:             my $gotspares;
 9017:             if (ref($settings) eq 'HASH') {
 9018:                 if (ref($settings->{'spares'}) eq 'HASH') {
 9019:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 9020:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 9021:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 9022:                         $gotspares = 1;
 9023:                     }
 9024:                 }
 9025:             }
 9026:             unless ($gotspares) {
 9027:                 my $gotspares;
 9028:                 my $serverhomeID =
 9029:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 9030:                 my $serverhomedom =
 9031:                     &Apache::lonnet::host_domain($serverhomeID);
 9032:                 if ($serverhomedom ne $dom) {
 9033:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 9034:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 9035:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 9036:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 9037:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 9038:                                 $gotspares = 1;
 9039:                             }
 9040:                         }
 9041:                     } else {
 9042:                         $otherdomconfigs{$serverhomedom} =
 9043:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 9044:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 9045:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 9046:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 9047:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 9048:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 9049:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 9050:                                         $gotspares = 1;
 9051:                                     }
 9052:                                 }
 9053:                             }
 9054:                         }
 9055:                     }
 9056:                 }
 9057:             }
 9058:             unless ($gotspares) {
 9059:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 9060:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 9061:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 9062:                } else {
 9063:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 9064:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 9065:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 9066:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 9067:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 9068:                     } else {
 9069:                         my %what = (
 9070:                              spareid => 1,
 9071:                         );
 9072:                         my ($result,$returnhash) = 
 9073:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 9074:                         if ($result eq 'ok') { 
 9075:                             if (ref($returnhash) eq 'HASH') {
 9076:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 9077:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 9078:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 9079:                                 }
 9080:                             }
 9081:                         }
 9082:                     }
 9083:                 }
 9084:             }
 9085:         }
 9086:     }
 9087:     return %spareid;
 9088: }
 9089: 
 9090: sub spares_row {
 9091:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 9092:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 9093:     my $css_class;
 9094:     my $numinrow = 4;
 9095:     my $itemcount = 1;
 9096:     my $datatable;
 9097:     my %typetitles = &sparestype_titles();
 9098:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 9099:         foreach my $server (sort(keys(%{$servers}))) {
 9100:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 9101:             my ($othercontrol,$serverdom);
 9102:             if ($serverhome ne $server) {
 9103:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 9104:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 9105:             } else {
 9106:                 $serverdom = &Apache::lonnet::host_domain($server);
 9107:                 if ($serverdom ne $dom) {
 9108:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 9109:                 }
 9110:             }
 9111:             next unless (ref($spareid->{$server}) eq 'HASH');
 9112:             my ($checkednow,$checkedoth);
 9113:             if (ref($curroffloadnow) eq 'HASH') {
 9114:                 if ($curroffloadnow->{$server}) {
 9115:                     $checkednow = ' checked="checked"';
 9116:                 }
 9117:             }
 9118:             if (ref($curroffloadoth) eq 'HASH') {
 9119:                 if ($curroffloadoth->{$server}) {
 9120:                     $checkedoth = ' checked="checked"';
 9121:                 }
 9122:             }
 9123:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 9124:             $datatable .= '<tr'.$css_class.'>
 9125:                            <td rowspan="2">
 9126:                             <span class="LC_nobreak">'.
 9127:                           &mt('[_1] when busy, offloads to:'
 9128:                               ,'<b>'.$server.'</b>').'</span><br />'.
 9129:                           '<span class="LC_nobreak">'."\n".
 9130:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 9131:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 9132:                           "\n";
 9133:             if ($other_insts) {
 9134:                 $datatable .= '<br />'.
 9135:                               '<span class="LC_nobreak">'."\n".
 9136:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 9137:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 9138:                           "\n";
 9139:             }
 9140:             my (%current,%canselect);
 9141:             my @choices = 
 9142:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 9143:             foreach my $type ('primary','default') {
 9144:                 if (ref($spareid->{$server}) eq 'HASH') {
 9145:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 9146:                         my @spares = @{$spareid->{$server}{$type}};
 9147:                         if (@spares > 0) {
 9148:                             if ($othercontrol) {
 9149:                                 $current{$type} = join(', ',@spares);
 9150:                             } else {
 9151:                                 $current{$type} .= '<table>';
 9152:                                 my $numspares = scalar(@spares);
 9153:                                 for (my $i=0;  $i<@spares; $i++) {
 9154:                                     my $rem = $i%($numinrow);
 9155:                                     if ($rem == 0) {
 9156:                                         if ($i > 0) {
 9157:                                             $current{$type} .= '</tr>';
 9158:                                         }
 9159:                                         $current{$type} .= '<tr>';
 9160:                                     }
 9161:                                     $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;'.
 9162:                                                        $spareid->{$server}{$type}[$i].
 9163:                                                        '</label></td>'."\n";
 9164:                                 }
 9165:                                 my $rem = @spares%($numinrow);
 9166:                                 my $colsleft = $numinrow - $rem;
 9167:                                 if ($colsleft > 1 ) {
 9168:                                     $current{$type} .= '<td colspan="'.$colsleft.
 9169:                                                        '" class="LC_left_item">'.
 9170:                                                        '&nbsp;</td>';
 9171:                                 } elsif ($colsleft == 1) {
 9172:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 9173:                                 }
 9174:                                 $current{$type} .= '</tr></table>';
 9175:                             }
 9176:                         }
 9177:                     }
 9178:                     if ($current{$type} eq '') {
 9179:                         $current{$type} = &mt('None specified');
 9180:                     }
 9181:                     if ($othercontrol) {
 9182:                         if ($type eq 'primary') {
 9183:                             $canselect{$type} = $othercontrol;
 9184:                         }
 9185:                     } else {
 9186:                         $canselect{$type} = 
 9187:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 9188:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 9189:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 9190:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 9191:                         if (@choices > 0) {
 9192:                             foreach my $lonhost (@choices) {
 9193:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 9194:                             }
 9195:                         }
 9196:                         $canselect{$type} .= '</select>'."\n";
 9197:                     }
 9198:                 } else {
 9199:                     $current{$type} = &mt('Could not be determined');
 9200:                     if ($type eq 'primary') {
 9201:                         $canselect{$type} =  $othercontrol;
 9202:                     }
 9203:                 }
 9204:                 if ($type eq 'default') {
 9205:                     $datatable .= '<tr'.$css_class.'>';
 9206:                 }
 9207:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 9208:                               '<td>'.$current{$type}.'</td>'."\n".
 9209:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 9210:             }
 9211:             $itemcount ++;
 9212:         }
 9213:     }
 9214:     $$rowtotal += $itemcount;
 9215:     return $datatable;
 9216: }
 9217: 
 9218: sub possible_newspares {
 9219:     my ($server,$currspares,$serverhomes,$altids) = @_;
 9220:     my $serverhostname = &Apache::lonnet::hostname($server);
 9221:     my %excluded;
 9222:     if ($serverhostname ne '') {
 9223:         %excluded = (
 9224:                        $serverhostname => 1,
 9225:                     );
 9226:     }
 9227:     if (ref($currspares) eq 'HASH') {
 9228:         foreach my $type (keys(%{$currspares})) {
 9229:             if (ref($currspares->{$type}) eq 'ARRAY') {
 9230:                 if (@{$currspares->{$type}} > 0) {
 9231:                     foreach my $curr (@{$currspares->{$type}}) {
 9232:                         my $hostname = &Apache::lonnet::hostname($curr);
 9233:                         $excluded{$hostname} = 1;
 9234:                     }
 9235:                 }
 9236:             }
 9237:         }
 9238:     }
 9239:     my @choices;
 9240:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 9241:         if (keys(%{$serverhomes}) > 1) {
 9242:             foreach my $name (sort(keys(%{$serverhomes}))) {
 9243:                 unless ($excluded{$name}) {
 9244:                     if (exists($altids->{$serverhomes->{$name}})) {
 9245:                         push(@choices,$altids->{$serverhomes->{$name}});
 9246:                     } else {
 9247:                         push(@choices,$serverhomes->{$name});
 9248:                     }
 9249:                 }
 9250:             }
 9251:         }
 9252:     }
 9253:     return sort(@choices);
 9254: }
 9255: 
 9256: sub print_loadbalancing {
 9257:     my ($dom,$settings,$rowtotal) = @_;
 9258:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 9259:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 9260:     my $numinrow = 1;
 9261:     my $datatable;
 9262:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 9263:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 9264:     if (ref($settings) eq 'HASH') {
 9265:         %existing = %{$settings};
 9266:     }
 9267:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 9268:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 9269:                                   \%currtargets,\%currrules,\%currcookies);
 9270:     } else {
 9271:         return;
 9272:     }
 9273:     my ($othertitle,$usertypes,$types) =
 9274:         &Apache::loncommon::sorted_inst_types($dom);
 9275:     my $rownum = 8;
 9276:     if (ref($types) eq 'ARRAY') {
 9277:         $rownum += scalar(@{$types});
 9278:     }
 9279:     my @css_class = ('LC_odd_row','LC_even_row');
 9280:     my $balnum = 0;
 9281:     my $islast;
 9282:     my (@toshow,$disabledtext);
 9283:     if (keys(%currbalancer) > 0) {
 9284:         @toshow = sort(keys(%currbalancer));
 9285:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 9286:             push(@toshow,'');
 9287:         }
 9288:     } else {
 9289:         @toshow = ('');
 9290:         $disabledtext = &mt('No existing load balancer');
 9291:     }
 9292:     foreach my $lonhost (@toshow) {
 9293:         if ($balnum == scalar(@toshow)-1) {
 9294:             $islast = 1;
 9295:         } else {
 9296:             $islast = 0;
 9297:         }
 9298:         my $cssidx = $balnum%2;
 9299:         my $targets_div_style = 'display: none';
 9300:         my $disabled_div_style = 'display: block';
 9301:         my $homedom_div_style = 'display: none';
 9302:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 9303:                       '<td rowspan="'.$rownum.'" style="vertical-align: top">'.
 9304:                       '<p>';
 9305:         if ($lonhost eq '') {
 9306:             $datatable .= '<span class="LC_nobreak">';
 9307:             if (keys(%currbalancer) > 0) {
 9308:                 $datatable .= &mt('Add balancer:');
 9309:             } else {
 9310:                 $datatable .= &mt('Enable balancer:');
 9311:             }
 9312:             $datatable .= '&nbsp;'.
 9313:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 9314:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 9315:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 9316:                           '<option value="" selected="selected">'.&mt('None').
 9317:                           '</option>'."\n";
 9318:             foreach my $server (sort(keys(%servers))) {
 9319:                 next if ($currbalancer{$server});
 9320:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 9321:             }
 9322:             $datatable .=
 9323:                 '</select>'."\n".
 9324:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 9325:         } else {
 9326:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 9327:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 9328:                            &mt('Stop balancing').'</label>'.
 9329:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 9330:             $targets_div_style = 'display: block';
 9331:             $disabled_div_style = 'display: none';
 9332:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 9333:                 $homedom_div_style = 'display: block';
 9334:             }
 9335:         }
 9336:         $datatable .= '</p></td><td rowspan="'.$rownum.'" style="vertical-align: top">'.
 9337:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 9338:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 9339:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 9340:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 9341:         my @sparestypes = ('primary','default');
 9342:         my %typetitles = &sparestype_titles();
 9343:         my %hostherechecked = (
 9344:                                   no => ' checked="checked"',
 9345:                               );
 9346:         my %balcookiechecked = (
 9347:                                   no => ' checked="checked"', 
 9348:                                );
 9349:         foreach my $sparetype (@sparestypes) {
 9350:             my $targettable;
 9351:             for (my $i=0; $i<$numspares; $i++) {
 9352:                 my $checked;
 9353:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 9354:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 9355:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 9356:                             $checked = ' checked="checked"';
 9357:                         }
 9358:                     }
 9359:                 }
 9360:                 my ($chkboxval,$disabled);
 9361:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 9362:                     $chkboxval = $spares[$i];
 9363:                 }
 9364:                 if (exists($currbalancer{$spares[$i]})) {
 9365:                     $disabled = ' disabled="disabled"';
 9366:                 }
 9367:                 $targettable .=
 9368:                     '<td><span class="LC_nobreak"><label>'.
 9369:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 9370:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 9371:                     '</span></label></span></td>';
 9372:                 my $rem = $i%($numinrow);
 9373:                 if ($rem == 0) {
 9374:                     if (($i > 0) && ($i < $numspares-1)) {
 9375:                         $targettable .= '</tr>';
 9376:                     }
 9377:                     if ($i < $numspares-1) {
 9378:                         $targettable .= '<tr>';
 9379:                     }
 9380:                 }
 9381:             }
 9382:             if ($targettable ne '') {
 9383:                 my $rem = $numspares%($numinrow);
 9384:                 my $colsleft = $numinrow - $rem;
 9385:                 if ($colsleft > 1 ) {
 9386:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9387:                                     '&nbsp;</td>';
 9388:                 } elsif ($colsleft == 1) {
 9389:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 9390:                 }
 9391:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 9392:                                '<table><tr>'.$targettable.'</tr></table><br />';
 9393:             }
 9394:             $hostherechecked{$sparetype} = '';
 9395:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 9396:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 9397:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 9398:                         $hostherechecked{$sparetype} = ' checked="checked"';
 9399:                         $hostherechecked{'no'} = '';
 9400:                     }
 9401:                 }
 9402:             }
 9403:         }
 9404:         if ($currcookies{$lonhost}) {
 9405:             %balcookiechecked = (
 9406:                                     yes => ' checked="checked"',
 9407:                                 );
 9408:         }
 9409:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 9410:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 9411:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 9412:         foreach my $sparetype (@sparestypes) {
 9413:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 9414:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 9415:                           '</i></label><br />';
 9416:         }
 9417:         $datatable .= &mt('Use balancer cookie').'<br />'.
 9418:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 9419:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 9420:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 9421:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 9422:                       '</div></td></tr>'.
 9423:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 9424:                                            $othertitle,$usertypes,$types,\%servers,
 9425:                                            \%currbalancer,$lonhost,
 9426:                                            $targets_div_style,$homedom_div_style,
 9427:                                            $css_class[$cssidx],$balnum,$islast);
 9428:         $$rowtotal += $rownum;
 9429:         $balnum ++;
 9430:     }
 9431:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 9432:     return $datatable;
 9433: }
 9434: 
 9435: sub get_loadbalancers_config {
 9436:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 9437:     return unless ((ref($servers) eq 'HASH') &&
 9438:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 9439:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 9440:                    (ref($currcookies) eq 'HASH'));
 9441:     if (keys(%{$existing}) > 0) {
 9442:         my $oldlonhost;
 9443:         foreach my $key (sort(keys(%{$existing}))) {
 9444:             if ($key eq 'lonhost') {
 9445:                 $oldlonhost = $existing->{'lonhost'};
 9446:                 $currbalancer->{$oldlonhost} = 1;
 9447:             } elsif ($key eq 'targets') {
 9448:                 if ($oldlonhost) {
 9449:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 9450:                 }
 9451:             } elsif ($key eq 'rules') {
 9452:                 if ($oldlonhost) {
 9453:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 9454:                 }
 9455:             } elsif (ref($existing->{$key}) eq 'HASH') {
 9456:                 $currbalancer->{$key} = 1;
 9457:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 9458:                 $currrules->{$key} = $existing->{$key}{'rules'};
 9459:                 if ($existing->{$key}{'cookie'}) {
 9460:                     $currcookies->{$key} = 1;
 9461:                 }
 9462:             }
 9463:         }
 9464:     } else {
 9465:         my ($balancerref,$targetsref) =
 9466:                 &Apache::lonnet::get_lonbalancer_config($servers);
 9467:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 9468:             foreach my $server (sort(keys(%{$balancerref}))) {
 9469:                 $currbalancer->{$server} = 1;
 9470:                 $currtargets->{$server} = $targetsref->{$server};
 9471:             }
 9472:         }
 9473:     }
 9474:     return;
 9475: }
 9476: 
 9477: sub loadbalancing_rules {
 9478:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 9479:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 9480:         $css_class,$balnum,$islast) = @_;
 9481:     my $output;
 9482:     my $num = 0;
 9483:     my ($alltypes,$othertypes,$titles) =
 9484:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 9485:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 9486:         foreach my $type (@{$alltypes}) {
 9487:             $num ++;
 9488:             my $current;
 9489:             if (ref($currrules) eq 'HASH') {
 9490:                 $current = $currrules->{$type};
 9491:             }
 9492:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 9493:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 9494:                     $current = '';
 9495:                 }
 9496:             }
 9497:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 9498:                                              $servers,$currbalancer,$lonhost,$dom,
 9499:                                              $targets_div_style,$homedom_div_style,
 9500:                                              $css_class,$balnum,$num,$islast);
 9501:         }
 9502:     }
 9503:     return $output;
 9504: }
 9505: 
 9506: sub loadbalancing_titles {
 9507:     my ($dom,$intdom,$usertypes,$types) = @_;
 9508:     my %othertypes = (
 9509:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 9510:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 9511:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 9512:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 9513:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 9514:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 9515:                      );
 9516:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 9517:     my @available;
 9518:     if (ref($types) eq 'ARRAY') {
 9519:         @available = @{$types};
 9520:     }
 9521:     unless (grep(/^default$/,@available)) {
 9522:         push(@available,'default');
 9523:     }
 9524:     unshift(@alltypes,@available);
 9525:     my %titles;
 9526:     foreach my $type (@alltypes) {
 9527:         if ($type =~ /^_LC_/) {
 9528:             $titles{$type} = $othertypes{$type};
 9529:         } elsif ($type eq 'default') {
 9530:             $titles{$type} = &mt('All users from [_1]',$dom);
 9531:             if (ref($types) eq 'ARRAY') {
 9532:                 if (@{$types} > 0) {
 9533:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 9534:                 }
 9535:             }
 9536:         } elsif (ref($usertypes) eq 'HASH') {
 9537:             $titles{$type} = $usertypes->{$type};
 9538:         }
 9539:     }
 9540:     return (\@alltypes,\%othertypes,\%titles);
 9541: }
 9542: 
 9543: sub loadbalance_rule_row {
 9544:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 9545:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 9546:     my @rulenames;
 9547:     my %ruletitles = &offloadtype_text();
 9548:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 9549:         @rulenames = ('balancer','offloadedto','specific');
 9550:     } else {
 9551:         @rulenames = ('default','homeserver');
 9552:         if ($type eq '_LC_external') {
 9553:             push(@rulenames,'externalbalancer');
 9554:         } else {
 9555:             push(@rulenames,'specific');
 9556:         }
 9557:         push(@rulenames,'none');
 9558:     }
 9559:     my $style = $targets_div_style;
 9560:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 9561:         $style = $homedom_div_style;
 9562:     }
 9563:     my $space;
 9564:     if ($islast && $num == 1) {
 9565:         $space = '<div style="display:inline-block;">&nbsp;</div>';
 9566:     }
 9567:     my $output =
 9568:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td style="vertical-align: top">'.$space.
 9569:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 9570:         '<td valaign="top">'.$space.
 9571:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 9572:     for (my $i=0; $i<@rulenames; $i++) {
 9573:         my $rule = $rulenames[$i];
 9574:         my ($checked,$extra);
 9575:         if ($rulenames[$i] eq 'default') {
 9576:             $rule = '';
 9577:         }
 9578:         if ($rulenames[$i] eq 'specific') {
 9579:             if (ref($servers) eq 'HASH') {
 9580:                 my $default;
 9581:                 if (($current ne '') && (exists($servers->{$current}))) {
 9582:                     $checked = ' checked="checked"';
 9583:                 }
 9584:                 unless ($checked) {
 9585:                     $default = ' selected="selected"';
 9586:                 }
 9587:                 $extra =
 9588:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 9589:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 9590:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 9591:                     '<option value=""'.$default.'></option>'."\n";
 9592:                 foreach my $server (sort(keys(%{$servers}))) {
 9593:                     if (ref($currbalancer) eq 'HASH') {
 9594:                         next if (exists($currbalancer->{$server}));
 9595:                     }
 9596:                     my $selected;
 9597:                     if ($server eq $current) {
 9598:                         $selected = ' selected="selected"';
 9599:                     }
 9600:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 9601:                 }
 9602:                 $extra .= '</select>';
 9603:             }
 9604:         } elsif ($rule eq $current) {
 9605:             $checked = ' checked="checked"';
 9606:         }
 9607:         $output .= '<span class="LC_nobreak"><label>'.
 9608:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 9609:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 9610:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 9611:                    ')"'.$checked.' />&nbsp;';
 9612:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 9613:             $output .= $ruletitles{'particular'};
 9614:         } else {
 9615:             $output .= $ruletitles{$rulenames[$i]};
 9616:         }
 9617:         $output .= '</label>'.$extra.'</span><br />'."\n";
 9618:     }
 9619:     $output .= '</div></td></tr>'."\n";
 9620:     return $output;
 9621: }
 9622: 
 9623: sub offloadtype_text {
 9624:     my %ruletitles = &Apache::lonlocal::texthash (
 9625:            'default'          => 'Offloads to default destinations',
 9626:            'homeserver'       => "Offloads to user's home server",
 9627:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 9628:            'specific'         => 'Offloads to specific server',
 9629:            'none'             => 'No offload',
 9630:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 9631:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 9632:            'particular'       => 'Session hosted (after re-auth) on server:',
 9633:     );
 9634:     return %ruletitles;
 9635: }
 9636: 
 9637: sub sparestype_titles {
 9638:     my %typestitles = &Apache::lonlocal::texthash (
 9639:                           'primary' => 'primary',
 9640:                           'default' => 'default',
 9641:                       );
 9642:     return %typestitles;
 9643: }
 9644: 
 9645: sub contact_titles {
 9646:     my %titles = &Apache::lonlocal::texthash (
 9647:                    'supportemail'    => 'Support E-mail address',
 9648:                    'adminemail'      => 'Default Server Admin E-mail address',
 9649:                    'errormail'       => 'Error reports to be e-mailed to',
 9650:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 9651:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 9652:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 9653:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 9654:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 9655:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 9656:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 9657:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 9658:                    'errorthreshold'  => 'Error count threshold for status e-mail to admin(s)',
 9659:                    'errorsysmail'    => 'Error count threshold for e-mail to developer group',
 9660:                    'errorweights'    => 'Weights used to compute error count',
 9661:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 9662:                  );
 9663:     my %short_titles = &Apache::lonlocal::texthash (
 9664:                            adminemail   => 'Admin E-mail address',
 9665:                            supportemail => 'Support E-mail',
 9666:                        );   
 9667:     return (\%titles,\%short_titles);
 9668: }
 9669: 
 9670: sub helpform_fields {
 9671:     my %titles =  &Apache::lonlocal::texthash (
 9672:                        'username'   => 'Name',
 9673:                        'user'       => 'Username/domain',
 9674:                        'phone'      => 'Phone',
 9675:                        'cc'         => 'Cc e-mail',
 9676:                        'course'     => 'Course Details',
 9677:                        'section'    => 'Sections',
 9678:                        'screenshot' => 'File upload',
 9679:     );
 9680:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 9681:     my %possoptions = (
 9682:                         username     => ['yes','no','req'],
 9683:                         phone        => ['yes','no','req'],
 9684:                         user         => ['yes','no'],
 9685:                         cc           => ['yes','no'],
 9686:                         course       => ['yes','no'],
 9687:                         section      => ['yes','no'],
 9688:                         screenshot   => ['yes','no'],
 9689:                       );
 9690:     my %fieldoptions = &Apache::lonlocal::texthash (
 9691:                          'yes'  => 'Optional',
 9692:                          'req'  => 'Required',
 9693:                          'no'   => "Not shown",
 9694:     );
 9695:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 9696: }
 9697: 
 9698: sub tool_titles {
 9699:     my %titles = &Apache::lonlocal::texthash (
 9700:                      aboutme    => 'Personal web page',
 9701:                      blog       => 'Blog',
 9702:                      webdav     => 'WebDAV',
 9703:                      portfolio  => 'Portfolio',
 9704:                      official   => 'Official courses (with institutional codes)',
 9705:                      unofficial => 'Unofficial courses',
 9706:                      community  => 'Communities',
 9707:                      textbook   => 'Textbook courses',
 9708:                      placement  => 'Placement tests',
 9709:                  );
 9710:     return %titles;
 9711: }
 9712: 
 9713: sub courserequest_titles {
 9714:     my %titles = &Apache::lonlocal::texthash (
 9715:                                    official   => 'Official',
 9716:                                    unofficial => 'Unofficial',
 9717:                                    community  => 'Communities',
 9718:                                    textbook   => 'Textbook',
 9719:                                    placement  => 'Placement tests',
 9720:                                    lti        => 'LTI Provider',
 9721:                                    norequest  => 'Not allowed',
 9722:                                    approval   => 'Approval by DC',
 9723:                                    validate   => 'With validation',
 9724:                                    autolimit  => 'Numerical limit',
 9725:                                    unlimited  => '(blank for unlimited)',
 9726:                  );
 9727:     return %titles;
 9728: }
 9729: 
 9730: sub authorrequest_titles {
 9731:     my %titles = &Apache::lonlocal::texthash (
 9732:                                    norequest  => 'Not allowed',
 9733:                                    approval   => 'Approval by Dom. Coord.',
 9734:                                    automatic  => 'Automatic approval',
 9735:                  );
 9736:     return %titles;
 9737: }
 9738: 
 9739: sub courserequest_conditions {
 9740:     my %conditions = &Apache::lonlocal::texthash (
 9741:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 9742:        validate   => '(Processing of request subject to institutional validation).',
 9743:                  );
 9744:     return %conditions;
 9745: }
 9746: 
 9747: 
 9748: sub print_usercreation {
 9749:     my ($position,$dom,$settings,$rowtotal) = @_;
 9750:     my $numinrow = 4;
 9751:     my $datatable;
 9752:     if ($position eq 'top') {
 9753:         $$rowtotal ++;
 9754:         my $rowcount = 0;
 9755:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 9756:         if (ref($rules) eq 'HASH') {
 9757:             if (keys(%{$rules}) > 0) {
 9758:                 $datatable .= &user_formats_row('username',$settings,$rules,
 9759:                                                 $ruleorder,$numinrow,$rowcount);
 9760:                 $$rowtotal ++;
 9761:                 $rowcount ++;
 9762:             }
 9763:         }
 9764:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 9765:         if (ref($idrules) eq 'HASH') {
 9766:             if (keys(%{$idrules}) > 0) {
 9767:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 9768:                                                 $idruleorder,$numinrow,$rowcount);
 9769:                 $$rowtotal ++;
 9770:                 $rowcount ++;
 9771:             }
 9772:         }
 9773:         if ($rowcount == 0) {
 9774:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 9775:             $$rowtotal ++;
 9776:             $rowcount ++;
 9777:         }
 9778:     } elsif ($position eq 'middle') {
 9779:         my @creators = ('author','course','requestcrs');
 9780:         my ($rules,$ruleorder) =
 9781:             &Apache::lonnet::inst_userrules($dom,'username');
 9782:         my %lt = &usercreation_types();
 9783:         my %checked;
 9784:         if (ref($settings) eq 'HASH') {
 9785:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 9786:                 foreach my $item (@creators) {
 9787:                     $checked{$item} = $settings->{'cancreate'}{$item};
 9788:                 }
 9789:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 9790:                 foreach my $item (@creators) {
 9791:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 9792:                         $checked{$item} = 'none';
 9793:                     }
 9794:                 }
 9795:             }
 9796:         }
 9797:         my $rownum = 0;
 9798:         foreach my $item (@creators) {
 9799:             $rownum ++;
 9800:             if ($checked{$item} eq '') {
 9801:                 $checked{$item} = 'any';
 9802:             }
 9803:             my $css_class;
 9804:             if ($rownum%2) {
 9805:                 $css_class = '';
 9806:             } else {
 9807:                 $css_class = ' class="LC_odd_row" ';
 9808:             }
 9809:             $datatable .= '<tr'.$css_class.'>'.
 9810:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 9811:                          '</span></td><td style="text-align: right">';
 9812:             my @options = ('any');
 9813:             if (ref($rules) eq 'HASH') {
 9814:                 if (keys(%{$rules}) > 0) {
 9815:                     push(@options,('official','unofficial'));
 9816:                 }
 9817:             }
 9818:             push(@options,'none');
 9819:             foreach my $option (@options) {
 9820:                 my $type = 'radio';
 9821:                 my $check = ' ';
 9822:                 if ($checked{$item} eq $option) {
 9823:                     $check = ' checked="checked" ';
 9824:                 } 
 9825:                 $datatable .= '<span class="LC_nobreak"><label>'.
 9826:                               '<input type="'.$type.'" name="can_createuser_'.
 9827:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 9828:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 9829:             }
 9830:             $datatable .= '</td></tr>';
 9831:         }
 9832:     } else {
 9833:         my @contexts = ('author','course','domain');
 9834:         my @authtypes = ('int','krb4','krb5','loc','lti');
 9835:         my %checked;
 9836:         if (ref($settings) eq 'HASH') {
 9837:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 9838:                 foreach my $item (@contexts) {
 9839:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 9840:                         foreach my $auth (@authtypes) {
 9841:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 9842:                                 $checked{$item}{$auth} = ' checked="checked" ';
 9843:                             }
 9844:                         }
 9845:                     }
 9846:                 }
 9847:             }
 9848:         } else {
 9849:             foreach my $item (@contexts) {
 9850:                 foreach my $auth (@authtypes) {
 9851:                     $checked{$item}{$auth} = ' checked="checked" ';
 9852:                 }
 9853:             }
 9854:         }
 9855:         my %title = &context_names();
 9856:         my %authname = &authtype_names();
 9857:         my $rownum = 0;
 9858:         my $css_class; 
 9859:         foreach my $item (@contexts) {
 9860:             if ($rownum%2) {
 9861:                 $css_class = '';
 9862:             } else {
 9863:                 $css_class = ' class="LC_odd_row" ';
 9864:             }
 9865:             $datatable .=   '<tr'.$css_class.'>'.
 9866:                             '<td>'.$title{$item}.
 9867:                             '</td><td class="LC_left_item">'.
 9868:                             '<span class="LC_nobreak">';
 9869:             foreach my $auth (@authtypes) {
 9870:                 $datatable .= '<label>'. 
 9871:                               '<input type="checkbox" name="'.$item.'_auth" '.
 9872:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 9873:                               $authname{$auth}.'</label>&nbsp;';
 9874:             }
 9875:             $datatable .= '</span></td></tr>';
 9876:             $rownum ++;
 9877:         }
 9878:         $$rowtotal += $rownum;
 9879:     }
 9880:     return $datatable;
 9881: }
 9882: 
 9883: sub print_selfcreation {
 9884:     my ($position,$dom,$settings,$rowtotal) = @_;
 9885:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 9886:         $emaildomain,$datatable);
 9887:     if (ref($settings) eq 'HASH') {
 9888:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 9889:             $createsettings = $settings->{'cancreate'};
 9890:             if (ref($createsettings) eq 'HASH') {
 9891:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 9892:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 9893:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 9894:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 9895:                         @selfcreate = ('email','login','sso');
 9896:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 9897:                         @selfcreate = ($createsettings->{'selfcreate'});
 9898:                     }
 9899:                 }
 9900:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 9901:                     $processing = $createsettings->{'selfcreateprocessing'};
 9902:                 }
 9903:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 9904:                     $emailoptions = $createsettings->{'emailoptions'};
 9905:                 }
 9906:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 9907:                     $emailverified = $createsettings->{'emailverified'};
 9908:                 }
 9909:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 9910:                     $emaildomain = $createsettings->{'emaildomain'};
 9911:                 }
 9912:             }
 9913:         }
 9914:     }
 9915:     my %radiohash;
 9916:     my $numinrow = 4;
 9917:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 9918:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 9919:     if ($position eq 'top') {
 9920:         my %choices = &Apache::lonlocal::texthash (
 9921:                                                       cancreate_login      => 'Institutional Login',
 9922:                                                       cancreate_sso        => 'Institutional Single Sign On',
 9923:                                                   );
 9924:         my @toggles = sort(keys(%choices));
 9925:         my %defaultchecked = (
 9926:                                'cancreate_login' => 'off',
 9927:                                'cancreate_sso'   => 'off',
 9928:                              );
 9929:         my ($onclick,$itemcount);
 9930:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 9931:                                                      \%choices,$itemcount,$onclick);
 9932:         $$rowtotal += $itemcount;
 9933:         
 9934:         if (ref($usertypes) eq 'HASH') {
 9935:             if (keys(%{$usertypes}) > 0) {
 9936:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 9937:                                              $dom,$numinrow,$othertitle,
 9938:                                              'statustocreate',$rowtotal);
 9939:                 $$rowtotal ++;
 9940:             }
 9941:         }
 9942:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 9943:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 9944:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 9945:         my $rem;
 9946:         my $numperrow = 2;
 9947:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 9948:         $datatable .= '<tr'.$css_class.'>'.
 9949:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 9950:                      '<td class="LC_left_item">'."\n".
 9951:                      '<table>'."\n";
 9952:         for (my $i=0; $i<@fields; $i++) {
 9953:             $rem = $i%($numperrow);
 9954:             if ($rem == 0) {
 9955:                 if ($i > 0) {
 9956:                     $datatable .= '</tr>';
 9957:                 }
 9958:                 $datatable .= '<tr>';
 9959:             }
 9960:             my $currval;
 9961:             if (ref($createsettings) eq 'HASH') {
 9962:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 9963:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 9964:                 }
 9965:             }
 9966:             $datatable .= '<td class="LC_left_item">'.
 9967:                           '<span class="LC_nobreak">'.
 9968:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 9969:                           'value="'.$currval.'" size="10" />&nbsp;'.
 9970:                           $fieldtitles{$fields[$i]}.'</span></td>';
 9971:         }
 9972:         my $colsleft = $numperrow - $rem;
 9973:         if ($colsleft > 1 ) {
 9974:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9975:                          '&nbsp;</td>';
 9976:         } elsif ($colsleft == 1) {
 9977:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 9978:         }
 9979:         $datatable .= '</tr></table></td></tr>';
 9980:         $$rowtotal ++;
 9981:     } elsif ($position eq 'middle') {
 9982:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 9983:         my @posstypes;
 9984:         if (ref($types) eq 'ARRAY') {
 9985:             @posstypes = @{$types};
 9986:         }
 9987:         unless (grep(/^default$/,@posstypes)) {
 9988:             push(@posstypes,'default');
 9989:         }
 9990:         my %usertypeshash;
 9991:         if (ref($usertypes) eq 'HASH') {
 9992:             %usertypeshash = %{$usertypes};
 9993:         }
 9994:         $usertypeshash{'default'} = $othertitle;
 9995:         foreach my $status (@posstypes) {
 9996:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 9997:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 9998:             $$rowtotal ++;
 9999:         }
10000:     } else {
10001:         my %choices = &Apache::lonlocal::texthash (
10002:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
10003:                                                   );
10004:         my @toggles = sort(keys(%choices));
10005:         my %defaultchecked = (
10006:                                'cancreate_email' => 'off',
10007:                              );
10008:         my $customclass = 'LC_selfcreate_email';
10009:         my $classprefix = 'LC_canmodify_emailusername_';
10010:         my $optionsprefix = 'LC_options_emailusername_';
10011:         my $display = 'none';
10012:         my $rowstyle = 'display:none';
10013:         if (grep(/^\Qemail\E$/,@selfcreate)) {
10014:             $display = 'block';
10015:             $rowstyle = 'display:table-row';
10016:         }
10017:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
10018:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
10019:                                                      \%choices,$$rowtotal,$onclick);
10020:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
10021:                                          $rowstyle);
10022:         $$rowtotal ++;
10023:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
10024:                                       $rowstyle);
10025:         $$rowtotal ++;
10026:         my (@ordered,@posstypes,%usertypeshash);
10027:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10028:         my ($emailrules,$emailruleorder) =
10029:             &Apache::lonnet::inst_userrules($dom,'email');
10030:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
10031:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
10032:         if (ref($types) eq 'ARRAY') {
10033:             @posstypes = @{$types};
10034:         }
10035:         if (@posstypes) {
10036:             unless (grep(/^default$/,@posstypes)) {
10037:                 push(@posstypes,'default');
10038:             }
10039:             if (ref($usertypes) eq 'HASH') {
10040:                 %usertypeshash = %{$usertypes};
10041:             }
10042:             my $currassign;
10043:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
10044:                 $currassign = {
10045:                                   selfassign => $domdefaults{'inststatusguest'},
10046:                               };
10047:                 @ordered = @{$domdefaults{'inststatusguest'}};
10048:             } else {
10049:                 $currassign = { selfassign => [] };
10050:             }
10051:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
10052:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
10053:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
10054:                                          $numinrow,$othertitle,'selfassign',
10055:                                          $rowtotal,$onclicktypes,$customclass,
10056:                                          $rowstyle);
10057:             $$rowtotal ++;
10058:             $usertypeshash{'default'} = $othertitle;
10059:             foreach my $status (@posstypes) {
10060:                 my $css_class;
10061:                 if ($$rowtotal%2) {
10062:                     $css_class = 'LC_odd_row ';
10063:                 }
10064:                 $css_class .= $customclass;
10065:                 my $rowid = $optionsprefix.$status;
10066:                 my $hidden = 1;
10067:                 my $currstyle = 'display:none';
10068:                 if (grep(/^\Q$status\E$/,@ordered)) {
10069:                     $currstyle = $rowstyle;
10070:                     $hidden = 0; 
10071:                 }
10072:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
10073:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
10074:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
10075:                 unless ($hidden) {
10076:                     $$rowtotal ++;
10077:                 }
10078:             }
10079:         } else {
10080:             my $css_class;
10081:             if ($$rowtotal%2) {
10082:                 $css_class = 'LC_odd_row ';
10083:             }
10084:             $css_class .= $customclass;
10085:             $usertypeshash{'default'} = $othertitle;
10086:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
10087:                                          $emailrules,$emailruleorder,$settings,'default','',
10088:                                          $othertitle,$css_class,$rowstyle,$intdom);
10089:             $$rowtotal ++;
10090:         }
10091:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
10092:         $numinrow = 1;
10093:         if (@posstypes) {
10094:             foreach my $status (@posstypes) {
10095:                 my $rowid = $classprefix.$status;
10096:                 my $datarowstyle = 'display:none';
10097:                 if (grep(/^\Q$status\E$/,@ordered)) { 
10098:                     $datarowstyle = $rowstyle; 
10099:                 }
10100:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
10101:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
10102:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
10103:                 unless ($datarowstyle eq 'display:none') {
10104:                     $$rowtotal ++;
10105:                 }
10106:             }
10107:         } else {
10108:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
10109:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
10110:                                                    $infotitles,'',$customclass,$rowstyle);
10111:         }
10112:     }
10113:     return $datatable;
10114: }
10115: 
10116: sub selfcreate_javascript {
10117:     return <<"ENDSCRIPT";
10118: 
10119: <script type="text/javascript">
10120: // <![CDATA[
10121: 
10122: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
10123:     var x = document.getElementsByClassName(target);
10124:     var insttypes = 0;
10125:     var insttypeRegExp = new RegExp(prefix);
10126:     if ((x.length != undefined) && (x.length > 0)) {
10127:         if (form.elements[radio].length != undefined) {
10128:             for (var i=0; i<form.elements[radio].length; i++) {
10129:                 if (form.elements[radio][i].checked) {
10130:                     if (form.elements[radio][i].value == 1) {
10131:                         for (var j=0; j<x.length; j++) {
10132:                             if (x[j].id == 'undefined') {
10133:                                 x[j].style.display = 'table-row';
10134:                             } else if (insttypeRegExp.test(x[j].id)) {
10135:                                 insttypes ++;
10136:                             } else {
10137:                                 x[j].style.display = 'table-row';
10138:                             }
10139:                         }
10140:                     } else {
10141:                         for (var j=0; j<x.length; j++) {
10142:                             x[j].style.display = 'none';
10143:                         }
10144:                     }
10145:                     break;
10146:                 }
10147:             }
10148:             if (insttypes > 0) {
10149:                 toggleDataRow(form,checkbox,target,altprefix);
10150:                 toggleDataRow(form,checkbox,target,prefix,1);
10151:             }
10152:         }
10153:     }
10154:     return;
10155: }
10156: 
10157: function toggleDataRow(form,checkbox,target,prefix,docount) {
10158:     if (form.elements[checkbox].length != undefined) {
10159:         var count = 0;
10160:         if (docount) {
10161:             for (var i=0; i<form.elements[checkbox].length; i++) {
10162:                 if (form.elements[checkbox][i].checked) {
10163:                     count ++;
10164:                 }
10165:             }
10166:         }
10167:         for (var i=0; i<form.elements[checkbox].length; i++) {
10168:             var type = form.elements[checkbox][i].value;
10169:             if (document.getElementById(prefix+type)) {
10170:                 if (form.elements[checkbox][i].checked) {
10171:                     document.getElementById(prefix+type).style.display = 'table-row';
10172:                     if (count % 2 == 1) {
10173:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
10174:                     } else {
10175:                         document.getElementById(prefix+type).className = target;
10176:                     }
10177:                     count ++;
10178:                 } else {
10179:                     document.getElementById(prefix+type).style.display = 'none';
10180:                 }
10181:             }
10182:         }
10183:     }
10184:     return;
10185: }
10186: 
10187: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
10188:     var caller = radio+'_'+status;
10189:     if (form.elements[caller].length != undefined) {
10190:         for (var i=0; i<form.elements[caller].length; i++) {
10191:             if (form.elements[caller][i].checked) {
10192:                 if (document.getElementById(altprefix+'_inst_'+status)) {
10193:                     var curr = form.elements[caller][i].value;
10194:                     if (prefix) {
10195:                         document.getElementById(prefix+'_'+status).style.display = 'none';
10196:                     }
10197:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
10198:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
10199:                     if (curr == 'custom') {
10200:                         if (prefix) { 
10201:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
10202:                         }
10203:                     } else if (curr == 'inst') {
10204:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
10205:                     } else if (curr == 'noninst') {
10206:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
10207:                     }
10208:                     break;
10209:                 }
10210:             }
10211:         }
10212:     }
10213: }
10214: 
10215: // ]]>
10216: </script>
10217: 
10218: ENDSCRIPT
10219: }
10220: 
10221: sub noninst_users {
10222:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
10223:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_; 
10224:     my $class = 'LC_left_item';
10225:     if ($css_class) {
10226:         $css_class = ' class="'.$css_class.'"'; 
10227:     }
10228:     if ($rowid) {
10229:         $rowid = ' id="'.$rowid.'"';
10230:     }
10231:     if ($rowstyle) {
10232:         $rowstyle = ' style="'.$rowstyle.'"';
10233:     }
10234:     my ($output,$description);
10235:     if ($type eq 'default') {
10236:         $description = &mt('Requests for: [_1]',$typetitle);
10237:     } else {
10238:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
10239:     }
10240:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
10241:               "<td>$description</td>\n".           
10242:               '<td class="'.$class.'" colspan="2">'.
10243:               '<table><tr>';
10244:     my %headers = &Apache::lonlocal::texthash( 
10245:               approve  => 'Processing',
10246:               email    => 'E-mail',
10247:               username => 'Username',
10248:     );
10249:     foreach my $item ('approve','email','username') {
10250:         $output .= '<th>'.$headers{$item}.'</th>';
10251:     }
10252:     $output .= '</tr><tr>';
10253:     foreach my $item ('approve','email','username') {
10254:         $output .= '<td style="vertical-align: top">';
10255:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
10256:         if ($item eq 'approve') {
10257:             %choices = &Apache::lonlocal::texthash (
10258:                                                      automatic => 'Automatically approved',
10259:                                                      approval  => 'Queued for approval',
10260:                                                    );
10261:             @options = ('automatic','approval');
10262:             $hashref = $processing;
10263:             $defoption = 'automatic';
10264:             $name = 'cancreate_emailprocess_'.$type;
10265:         } elsif ($item eq 'email') {
10266:             %choices = &Apache::lonlocal::texthash (
10267:                                                      any     => 'Any e-mail',
10268:                                                      inst    => 'Institutional only',
10269:                                                      noninst => 'Non-institutional only',
10270:                                                      custom  => 'Custom restrictions',
10271:                                                    );
10272:             @options = ('any','inst','noninst');
10273:             my $showcustom;
10274:             if (ref($emailrules) eq 'HASH') {
10275:                 if (keys(%{$emailrules}) > 0) {
10276:                     push(@options,'custom');
10277:                     $showcustom = 'cancreate_emailrule';
10278:                     if (ref($settings) eq 'HASH') {
10279:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
10280:                             foreach my $rule (@{$settings->{'email_rule'}}) {
10281:                                 if (exists($emailrules->{$rule})) {
10282:                                     $hascustom ++;
10283:                                 }
10284:                             }
10285:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
10286:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
10287:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
10288:                                     if (exists($emailrules->{$rule})) {
10289:                                         $hascustom ++;
10290:                                     }
10291:                                 }
10292:                             }
10293:                         }
10294:                     }
10295:                 }
10296:             }
10297:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
10298:                                                      "'cancreate_emaildomain','$type'".');"';
10299:             $hashref = $emailoptions;
10300:             $defoption = 'any';
10301:             $name = 'cancreate_emailoptions_'.$type;
10302:         } elsif ($item eq 'username') {
10303:             %choices = &Apache::lonlocal::texthash (
10304:                                                      all    => 'Same as e-mail',
10305:                                                      first  => 'Omit @domain',
10306:                                                      free   => 'Free to choose',
10307:                                                    );
10308:             @options = ('all','first','free');
10309:             $hashref = $emailverified;
10310:             $defoption = 'all';
10311:             $name = 'cancreate_usernameoptions_'.$type;
10312:         }
10313:         foreach my $option (@options) {
10314:             my $checked;
10315:             if (ref($hashref) eq 'HASH') {
10316:                 if ($type eq '') {
10317:                     if (!exists($hashref->{'default'})) {
10318:                         if ($option eq $defoption) {
10319:                             $checked = ' checked="checked"';
10320:                         }
10321:                     } else {
10322:                         if ($hashref->{'default'} eq $option) {
10323:                             $checked = ' checked="checked"';
10324:                         }
10325:                     }
10326:                 } else {
10327:                     if (!exists($hashref->{$type})) {
10328:                         if ($option eq $defoption) {
10329:                             $checked = ' checked="checked"';
10330:                         }
10331:                     } else {
10332:                         if ($hashref->{$type} eq $option) {
10333:                             $checked = ' checked="checked"';
10334:                         }
10335:                     }
10336:                 }
10337:             } elsif (($item eq 'email') && ($hascustom)) {
10338:                 if ($option eq 'custom') {
10339:                     $checked = ' checked="checked"';
10340:                 }
10341:             } elsif ($option eq $defoption) {
10342:                 $checked = ' checked="checked"';
10343:             }
10344:             $output .= '<span class="LC_nobreak"><label>'.
10345:                        '<input type="radio" name="'.$name.'"'.
10346:                        $checked.' value="'.$option.'"'.$onclick.' />'.
10347:                        $choices{$option}.'</label></span><br />';
10348:             if ($item eq 'email') {
10349:                 if ($option eq 'custom') {
10350:                     my $id = 'cancreate_emailrule_'.$type;
10351:                     my $display = 'none';
10352:                     if ($checked) {
10353:                         $display = 'inline';
10354:                     }
10355:                     my $numinrow = 2;
10356:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
10357:                                '<legend>'.&mt('Disallow').'</legend><table>'.
10358:                                &user_formats_row('email',$settings,$emailrules,
10359:                                                  $emailruleorder,$numinrow,'',$type);
10360:                               '</table></fieldset>';
10361:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
10362:                     my %text = &Apache::lonlocal::texthash (
10363:                                                              inst    => 'must end:',
10364:                                                              noninst => 'cannot end:',
10365:                                                            );
10366:                     my $value;
10367:                     if (ref($emaildomain) eq 'HASH') {
10368:                         if (ref($emaildomain->{$type}) eq 'HASH') {
10369:                             $value = $emaildomain->{$type}->{$option}; 
10370:                         }
10371:                     }
10372:                     if ($value eq '') {
10373:                         $value = '@'.$intdom;
10374:                     }
10375:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
10376:                     my $display = 'none';
10377:                     if ($checked) {
10378:                         $display = 'inline';
10379:                     }
10380:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
10381:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
10382:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
10383:                                '</div>';
10384:                 }
10385:             }
10386:         }
10387:         $output .= '</td>'."\n";
10388:     }
10389:     $output .= "</tr></table></td></tr>\n";
10390:     return $output;
10391: }
10392: 
10393: sub captcha_choice {
10394:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
10395:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
10396:         $vertext,$currver);
10397:     my %lt = &captcha_phrases();
10398:     $keyentry = 'hidden';
10399:     my $colspan=2;
10400:     if ($context eq 'cancreate') {
10401:         $rowname = &mt('CAPTCHA validation');
10402:     } elsif ($context eq 'login') {
10403:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
10404:     } elsif ($context eq 'passwords') {
10405:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
10406:         $colspan=1;
10407:     }
10408:     if (ref($settings) eq 'HASH') {
10409:         if ($settings->{'captcha'}) {
10410:             $checked{$settings->{'captcha'}} = ' checked="checked"';
10411:         } else {
10412:             $checked{'original'} = ' checked="checked"';
10413:         }
10414:         if ($settings->{'captcha'} eq 'recaptcha') {
10415:             $pubtext = $lt{'pub'};
10416:             $privtext = $lt{'priv'};
10417:             $keyentry = 'text';
10418:             $vertext = $lt{'ver'};
10419:             $currver = $settings->{'recaptchaversion'};
10420:             if ($currver ne '2') {
10421:                 $currver = 1;
10422:             }
10423:         }
10424:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
10425:             $currpub = $settings->{'recaptchakeys'}{'public'};
10426:             $currpriv = $settings->{'recaptchakeys'}{'private'};
10427:         }
10428:     } else {
10429:         $checked{'original'} = ' checked="checked"';
10430:     }
10431:     my $css_class;
10432:     if ($itemcount%2) {
10433:         $css_class = 'LC_odd_row';
10434:     }
10435:     if ($customcss) {
10436:         $css_class .= " $customcss";
10437:     }
10438:     $css_class =~ s/^\s+//;
10439:     if ($css_class) {
10440:         $css_class = ' class="'.$css_class.'"';
10441:     }
10442:     if ($rowstyle) {
10443:         $css_class .= ' style="'.$rowstyle.'"';
10444:     }
10445:     my $output = '<tr'.$css_class.'>'.
10446:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
10447:                  '<table><tr><td>'."\n";
10448:     foreach my $option ('original','recaptcha','notused') {
10449:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
10450:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
10451:                    $lt{$option}.'</label></span>';
10452:         unless ($option eq 'notused') {
10453:             $output .= ('&nbsp;'x2)."\n";
10454:         }
10455:     }
10456: #
10457: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
10458: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
10459: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
10460: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
10461: #
10462:     $output .= '</td></tr>'."\n".
10463:                '<tr><td class="LC_zero_height">'."\n".
10464:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
10465:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
10466:                $currpub.'" size="40" /></span><br />'."\n".
10467:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
10468:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
10469:                $currpriv.'" size="40" /></span><br />'.
10470:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
10471:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
10472:                $currver.'" size="3" /></span><br />'.
10473:                '</td></tr></table>'."\n".
10474:                '</td></tr>';
10475:     return $output;
10476: }
10477: 
10478: sub user_formats_row {
10479:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
10480:     my $output;
10481:     my %text = (
10482:                    'username' => 'new usernames',
10483:                    'id'       => 'IDs',
10484:                );
10485:     unless (($type eq 'email') || ($type eq 'unamemap')) {
10486:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
10487:         $output = '<tr '.$css_class.'>'.
10488:                   '<td><span class="LC_nobreak">'.
10489:                   &mt("Format rules to check for $text{$type}: ").
10490:                   '</td><td class="LC_left_item" colspan="2"><table>';
10491:     }
10492:     my $rem;
10493:     if (ref($ruleorder) eq 'ARRAY') {
10494:         for (my $i=0; $i<@{$ruleorder}; $i++) {
10495:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
10496:                 my $rem = $i%($numinrow);
10497:                 if ($rem == 0) {
10498:                     if ($i > 0) {
10499:                         $output .= '</tr>';
10500:                     }
10501:                     $output .= '<tr>';
10502:                 }
10503:                 my $check = ' ';
10504:                 if (ref($settings) eq 'HASH') {
10505:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
10506:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
10507:                             $check = ' checked="checked" ';
10508:                         }
10509:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
10510:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
10511:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
10512:                                 $check = ' checked="checked" ';
10513:                             }
10514:                         }
10515:                     }
10516:                 }
10517:                 my $name = $type.'_rule';
10518:                 if ($type eq 'email') {
10519:                     $name .= '_'.$status;
10520:                 }
10521:                 $output .= '<td class="LC_left_item">'.
10522:                            '<span class="LC_nobreak"><label>'.
10523:                            '<input type="checkbox" name="'.$name.'" '.
10524:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
10525:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
10526:             }
10527:         }
10528:         $rem = @{$ruleorder}%($numinrow);
10529:     }
10530:     my $colsleft;
10531:     if ($rem) {
10532:         $colsleft = $numinrow - $rem;
10533:     }
10534:     if ($colsleft > 1 ) {
10535:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
10536:                    '&nbsp;</td>';
10537:     } elsif ($colsleft == 1) {
10538:         $output .= '<td class="LC_left_item">&nbsp;</td>';
10539:     }
10540:     $output .= '</tr>';
10541:     unless (($type eq 'email') || ($type eq 'unamemap')) {
10542:         $output .= '</table></td></tr>';
10543:     }
10544:     return $output;
10545: }
10546: 
10547: sub usercreation_types {
10548:     my %lt = &Apache::lonlocal::texthash (
10549:                     author     => 'When adding a co-author',
10550:                     course     => 'When adding a user to a course',
10551:                     requestcrs => 'When requesting a course',
10552:                     any        => 'Any',
10553:                     official   => 'Institutional only ',
10554:                     unofficial => 'Non-institutional only',
10555:                     none       => 'None',
10556:     );
10557:     return %lt;
10558: }
10559: 
10560: sub selfcreation_types {
10561:     my %lt = &Apache::lonlocal::texthash (
10562:                     selfcreate => 'User creates own account',
10563:                     any        => 'Any',
10564:                     official   => 'Institutional only ',
10565:                     unofficial => 'Non-institutional only',
10566:                     email      => 'E-mail address',
10567:                     login      => 'Institutional Login',
10568:                     sso        => 'SSO',
10569:              );
10570: }
10571: 
10572: sub authtype_names {
10573:     my %lt = &Apache::lonlocal::texthash(
10574:                       int    => 'Internal',
10575:                       krb4   => 'Kerberos 4',
10576:                       krb5   => 'Kerberos 5',
10577:                       loc    => 'Local',
10578:                       lti    => 'LTI',
10579:                   );
10580:     return %lt;
10581: }
10582: 
10583: sub context_names {
10584:     my %context_title = &Apache::lonlocal::texthash(
10585:        author => 'Creating users when an Author',
10586:        course => 'Creating users when in a course',
10587:        domain => 'Creating users when a Domain Coordinator',
10588:     );
10589:     return %context_title;
10590: }
10591: 
10592: sub print_usermodification {
10593:     my ($position,$dom,$settings,$rowtotal) = @_;
10594:     my $numinrow = 4;
10595:     my ($context,$datatable,$rowcount);
10596:     if ($position eq 'top') {
10597:         $rowcount = 0;
10598:         $context = 'author'; 
10599:         foreach my $role ('ca','aa') {
10600:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
10601:                                                    $numinrow,$rowcount);
10602:             $$rowtotal ++;
10603:             $rowcount ++;
10604:         }
10605:     } elsif ($position eq 'bottom') {
10606:         $context = 'course';
10607:         $rowcount = 0;
10608:         foreach my $role ('st','ep','ta','in','cr') {
10609:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
10610:                                                    $numinrow,$rowcount);
10611:             $$rowtotal ++;
10612:             $rowcount ++;
10613:         }
10614:     }
10615:     return $datatable;
10616: }
10617: 
10618: sub print_defaults {
10619:     my ($position,$dom,$settings,$rowtotal) = @_;
10620:     my $rownum = 0;
10621:     my ($datatable,$css_class,$titles);
10622:     unless ($position eq 'bottom') {
10623:         $titles = &defaults_titles($dom);
10624:     }
10625:     if ($position eq 'top') {
10626:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
10627:                      'datelocale_def','portal_def');
10628:         my %defaults;
10629:         if (ref($settings) eq 'HASH') {
10630:             %defaults = %{$settings};
10631:         } else {
10632:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
10633:             foreach my $item (@items) {
10634:                 $defaults{$item} = $domdefaults{$item};
10635:             }
10636:         }
10637:         foreach my $item (@items) {
10638:             if ($rownum%2) {
10639:                 $css_class = '';
10640:             } else {
10641:                 $css_class = ' class="LC_odd_row" ';
10642:             }
10643:             $datatable .= '<tr'.$css_class.'>'.
10644:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
10645:                           '</span></td><td class="LC_right_item" colspan="3">';
10646:             if ($item eq 'auth_def') {
10647:                 my @authtypes = ('internal','krb4','krb5','localauth','lti');
10648:                 my %shortauth = (
10649:                                  internal => 'int',
10650:                                  krb4 => 'krb4',
10651:                                  krb5 => 'krb5',
10652:                                  localauth  => 'loc',
10653:                                  lti => 'lti',
10654:                                 );
10655:                 my %authnames = &authtype_names();
10656:                 foreach my $auth (@authtypes) {
10657:                     my $checked = ' ';
10658:                     if ($defaults{$item} eq $auth) {
10659:                         $checked = ' checked="checked" ';
10660:                     }
10661:                     $datatable .= '<label><input type="radio" name="'.$item.
10662:                                   '" value="'.$auth.'"'.$checked.'/>'.
10663:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
10664:                 }
10665:             } elsif ($item eq 'timezone_def') {
10666:                 my $includeempty = 1;
10667:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
10668:             } elsif ($item eq 'datelocale_def') {
10669:                 my $includeempty = 1;
10670:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
10671:             } elsif ($item eq 'lang_def') {
10672:                 my $includeempty = 1;
10673:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
10674:             } else {
10675:                 my $size;
10676:                 if ($item eq 'portal_def') {
10677:                     $size = ' size="25"';
10678:                 }
10679:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
10680:                               $defaults{$item}.'"'.$size.' />';
10681:             }
10682:             $datatable .= '</td></tr>';
10683:             $rownum ++;
10684:         }
10685:     } elsif ($position eq 'middle') {
10686:         my %defaults;
10687:         if (ref($settings) eq 'HASH') {
10688:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
10689:                 my $maxnum = @{$settings->{'inststatusorder'}};
10690:                 for (my $i=0; $i<$maxnum; $i++) {
10691:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
10692:                     my $item = $settings->{'inststatusorder'}->[$i];
10693:                     my $title = $settings->{'inststatustypes'}->{$item};
10694:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
10695:                     $datatable .= '<tr'.$css_class.'>'.
10696:                                   '<td><span class="LC_nobreak">'.
10697:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
10698:                     for (my $k=0; $k<=$maxnum; $k++) {
10699:                         my $vpos = $k+1;
10700:                         my $selstr;
10701:                         if ($k == $i) {
10702:                             $selstr = ' selected="selected" ';
10703:                         }
10704:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10705:                     }
10706:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
10707:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
10708:                                   &mt('delete').'</span></td>'.
10709:                                   '<td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.&mt('Name displayed').':'.
10710:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
10711:                                   '</span></td></tr>';
10712:                 }
10713:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
10714:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
10715:                 $datatable .= '<tr '.$css_class.'>'.
10716:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
10717:                 for (my $k=0; $k<=$maxnum; $k++) {
10718:                     my $vpos = $k+1;
10719:                     my $selstr;
10720:                     if ($k == $maxnum) {
10721:                         $selstr = ' selected="selected" ';
10722:                     }
10723:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10724:                 }
10725:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
10726:                               '<input type="text" size="10" name="addinststatus" value="" />'.
10727:                               '&nbsp;'.&mt('(new)').
10728:                               '</span></td><td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.
10729:                               &mt('Name displayed').':'.
10730:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
10731:                               '</tr>'."\n";
10732:                 $rownum ++;
10733:             }
10734:         }
10735:     } else {
10736:         my ($unamemaprules,$ruleorder) =
10737:             &Apache::lonnet::inst_userrules($dom,'unamemap');
10738:         $css_class = $rownum%2?' class="LC_odd_row"':'';
10739:         if ((ref($unamemaprules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10740:             my $numinrow = 2;
10741:             $datatable .= '<tr'.$css_class.'><td>'.&mt('Available conversions').'</td><td><table>'.
10742:                           &user_formats_row('unamemap',$settings,$unamemaprules,
10743:                                             $ruleorder,$numinrow).
10744:                           '</table></td></tr>';
10745:         }
10746:         if ($datatable eq '') {
10747:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
10748:                           &mt('No rules set for domain in customized localenroll.pm').
10749:                           '</td></tr>';
10750:         }
10751:     }
10752:     $$rowtotal += $rownum;
10753:     return $datatable;
10754: }
10755: 
10756: sub get_languages_hash {
10757:     my %langchoices;
10758:     foreach my $id (&Apache::loncommon::languageids()) {
10759:         my $code = &Apache::loncommon::supportedlanguagecode($id);
10760:         if ($code ne '') {
10761:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
10762:         }
10763:     }
10764:     return %langchoices;
10765: }
10766: 
10767: sub defaults_titles {
10768:     my ($dom) = @_;
10769:     my %titles = &Apache::lonlocal::texthash (
10770:                    'auth_def'      => 'Default authentication type',
10771:                    'auth_arg_def'  => 'Default authentication argument',
10772:                    'lang_def'      => 'Default language',
10773:                    'timezone_def'  => 'Default timezone',
10774:                    'datelocale_def' => 'Default locale for dates',
10775:                    'portal_def'     => 'Portal/Default URL',
10776:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
10777:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
10778:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
10779:                  );
10780:     if ($dom) {
10781:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
10782:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
10783:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
10784:         $protocol = 'http' if ($protocol ne 'https');
10785:         if ($uint_dom) {
10786:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
10787:                                          $uint_dom);
10788:         }
10789:     }
10790:     return (\%titles);
10791: }
10792: 
10793: sub print_scantron {
10794:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
10795:     if ($position eq 'top') {
10796:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
10797:     } else {
10798:         return &print_scantronconfig($dom,$settings,\$rowtotal);
10799:     }
10800: }
10801: 
10802: sub scantron_javascript {
10803:     return <<"ENDSCRIPT";
10804: 
10805: <script type="text/javascript">
10806: // <![CDATA[
10807: 
10808: function toggleScantron(form) {
10809:     var csvfieldset = new Array();
10810:     if (document.getElementById('scantroncsv_cols')) {
10811:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
10812:     }
10813:     if (document.getElementById('scantroncsv_options')) {
10814:         csvfieldset.push(document.getElementById('scantroncsv_options'));
10815:     }
10816:     if (csvfieldset.length) {
10817:         if (document.getElementById('scantronconfcsv')) {
10818:             var scantroncsv = document.getElementById('scantronconfcsv');
10819:             if (scantroncsv.checked) {
10820:                 for (var i=0; i<csvfieldset.length; i++) {
10821:                     csvfieldset[i].style.display = 'block';
10822:                 }
10823:             } else {
10824:                 for (var i=0; i<csvfieldset.length; i++) {
10825:                     csvfieldset[i].style.display = 'none';
10826:                 }
10827:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
10828:                 if (csvselects.length) {
10829:                     for (var j=0; j<csvselects.length; j++) {
10830:                         csvselects[j].selectedIndex = 0;
10831:                     }
10832:                 }
10833:             }
10834:         }
10835:     }
10836:     return;
10837: }
10838: // ]]>
10839: </script>
10840: 
10841: ENDSCRIPT
10842: 
10843: }
10844: 
10845: sub print_scantronformat {
10846:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
10847:     my $itemcount = 1;
10848:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
10849:         %confhash);
10850:     my $switchserver = &check_switchserver($dom,$confname);
10851:     my %lt = &Apache::lonlocal::texthash (
10852:                 default => 'Default bubblesheet format file error',
10853:                 custom  => 'Custom bubblesheet format file error',
10854:              );
10855:     my %scantronfiles = (
10856:         default => 'default.tab',
10857:         custom => 'custom.tab',
10858:     );
10859:     foreach my $key (keys(%scantronfiles)) {
10860:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
10861:                               .$scantronfiles{$key};
10862:     }
10863:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
10864:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
10865:         if (!$switchserver) {
10866:             my $servadm = $r->dir_config('lonAdmEMail');
10867:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
10868:             if ($configuserok eq 'ok') {
10869:                 if ($author_ok eq 'ok') {
10870:                     my %legacyfile = (
10871:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
10872:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
10873:                     );
10874:                     my %md5chk;
10875:                     foreach my $type (keys(%legacyfile)) {
10876:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
10877:                         chomp($md5chk{$type});
10878:                     }
10879:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
10880:                         foreach my $type (keys(%legacyfile)) {
10881:                             ($scantronurls{$type},my $error) =
10882:                                 &legacy_scantronformat($r,$dom,$confname,
10883:                                                  $type,$legacyfile{$type},
10884:                                                  $scantronurls{$type},
10885:                                                  $scantronfiles{$type});
10886:                             if ($error ne '') {
10887:                                 $error{$type} = $error;
10888:                             }
10889:                         }
10890:                         if (keys(%error) == 0) {
10891:                             $is_custom = 1;
10892:                             $confhash{'scantron'}{'scantronformat'} =
10893:                                 $scantronurls{'custom'};
10894:                             my $putresult =
10895:                                 &Apache::lonnet::put_dom('configuration',
10896:                                                          \%confhash,$dom);
10897:                             if ($putresult ne 'ok') {
10898:                                 $error{'custom'} =
10899:                                     '<span class="LC_error">'.
10900:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10901:                             }
10902:                         }
10903:                     } else {
10904:                         ($scantronurls{'default'},my $error) =
10905:                             &legacy_scantronformat($r,$dom,$confname,
10906:                                           'default',$legacyfile{'default'},
10907:                                           $scantronurls{'default'},
10908:                                           $scantronfiles{'default'});
10909:                         if ($error eq '') {
10910:                             $confhash{'scantron'}{'scantronformat'} = ''; 
10911:                             my $putresult =
10912:                                 &Apache::lonnet::put_dom('configuration',
10913:                                                          \%confhash,$dom);
10914:                             if ($putresult ne 'ok') {
10915:                                 $error{'default'} =
10916:                                     '<span class="LC_error">'.
10917:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10918:                             }
10919:                         } else {
10920:                             $error{'default'} = $error;
10921:                         }
10922:                     }
10923:                 }
10924:             }
10925:         } else {
10926:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
10927:         }
10928:     }
10929:     if (ref($settings) eq 'HASH') {
10930:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
10931:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
10932:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
10933:                 $scantronurl = '';
10934:             } else {
10935:                 $scantronurl = $settings->{'scantronformat'};
10936:             }
10937:             $is_custom = 1;
10938:         } else {
10939:             $scantronurl = $scantronurls{'default'};
10940:         }
10941:     } else {
10942:         if ($is_custom) {
10943:             $scantronurl = $scantronurls{'custom'};
10944:         } else {
10945:             $scantronurl = $scantronurls{'default'};
10946:         }
10947:     }
10948:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10949:     $datatable .= '<tr'.$css_class.'>';
10950:     if (!$is_custom) {
10951:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
10952:                       '<span class="LC_nobreak">';
10953:         if ($scantronurl) {
10954:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
10955:                                                          undef,undef,undef,undef,'background-color:#ffffff');
10956:         } else {
10957:             $datatable = &mt('File unavailable for display');
10958:         }
10959:         $datatable .= '</span></td>';
10960:         if (keys(%error) == 0) { 
10961:             $datatable .= '<td style="vertical-align: bottom">';
10962:             if (!$switchserver) {
10963:                 $datatable .= &mt('Upload:').'<br />';
10964:             }
10965:         } else {
10966:             my $errorstr;
10967:             foreach my $key (sort(keys(%error))) {
10968:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
10969:             }
10970:             $datatable .= '<td>'.$errorstr;
10971:         }
10972:     } else {
10973:         if (keys(%error) > 0) {
10974:             my $errorstr;
10975:             foreach my $key (sort(keys(%error))) {
10976:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
10977:             } 
10978:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
10979:         } elsif ($scantronurl) {
10980:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
10981:                                                        undef,undef,undef,undef,'background-color:#ffffff');
10982:             $datatable .= '<td><span class="LC_nobreak">'.
10983:                           $link.
10984:                           '<label><input type="checkbox" name="scantronformat_del"'.
10985:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
10986:                           '<td><span class="LC_nobreak">&nbsp;'.
10987:                           &mt('Replace:').'</span><br />';
10988:         }
10989:     }
10990:     if (keys(%error) == 0) {
10991:         if ($switchserver) {
10992:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
10993:         } else {
10994:             $datatable .='<span class="LC_nobreak">&nbsp;'.
10995:                          '<input type="file" name="scantronformat" /></span>';
10996:         }
10997:     }
10998:     $datatable .= '</td></tr>';
10999:     $$rowtotal ++;
11000:     return $datatable;
11001: }
11002: 
11003: sub legacy_scantronformat {
11004:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
11005:     my ($url,$error);
11006:     my @statinfo = &Apache::lonnet::stat_file($newurl);
11007:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
11008:         (my $result,$url) =
11009:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
11010:                          '','',$newfile);
11011:         if ($result ne 'ok') {
11012:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
11013:         }
11014:     }
11015:     return ($url,$error);
11016: }
11017: 
11018: sub print_scantronconfig {
11019:     my ($dom,$settings,$rowtotal) = @_;
11020:     my $itemcount = 2;
11021:     my $is_checked = ' checked="checked"';
11022:     my %optionson = (
11023:                      hdr => ' checked="checked"',
11024:                      pad => ' checked="checked"',
11025:                      rem => ' checked="checked"',
11026:                     );
11027:     my %optionsoff = (
11028:                       hdr => '',
11029:                       pad => '',
11030:                       rem => '',
11031:                      );
11032:     my $currcsvsty = 'none';
11033:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
11034:     my @fields = &scantroncsv_fields();
11035:     my %titles = &scantronconfig_titles();
11036:     if (ref($settings) eq 'HASH') {
11037:         if (ref($settings->{config}) eq 'HASH') {
11038:             if ($settings->{config}->{dat}) {
11039:                 $checked{'dat'} = $is_checked;
11040:             }
11041:             if (ref($settings->{config}->{csv}) eq 'HASH') {
11042:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
11043:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
11044:                     if (keys(%csvfields) > 0) {
11045:                         $checked{'csv'} = $is_checked;
11046:                         $currcsvsty = 'block';
11047:                     }
11048:                 }
11049:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
11050:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
11051:                     foreach my $option (keys(%optionson)) {
11052:                         unless ($csvoptions{$option}) {
11053:                             $optionsoff{$option} = $optionson{$option};
11054:                             $optionson{$option} = '';
11055:                         }
11056:                     }
11057:                 }
11058:             }
11059:         } else {
11060:             $checked{'dat'} = $is_checked;
11061:         }
11062:     } else {
11063:         $checked{'dat'} = $is_checked;
11064:     }
11065:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
11066:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
11067:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
11068:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
11069:     foreach my $item ('dat','csv') {
11070:         my $id;
11071:         if ($item eq 'csv') {
11072:             $id = 'id="scantronconfcsv" ';
11073:         }
11074:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
11075:                       $titles{$item}.'</label>'.('&nbsp;'x3);
11076:         if ($item eq 'csv') {
11077:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
11078:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
11079:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
11080:             foreach my $col (@fields) {
11081:                 my $selnone;
11082:                 if ($csvfields{$col} eq '') {
11083:                     $selnone = ' selected="selected"';
11084:                 }
11085:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
11086:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
11087:                               '<option value=""'.$selnone.'></option>';
11088:                 for (my $i=0; $i<20; $i++) {
11089:                     my $shown = $i+1;
11090:                     my $sel;
11091:                     unless ($selnone) {
11092:                         if (exists($csvfields{$col})) {
11093:                             if ($csvfields{$col} == $i) {
11094:                                 $sel = ' selected="selected"';
11095:                             }
11096:                         }
11097:                     }
11098:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
11099:                 }
11100:                 $datatable .= '</select></td></tr>';
11101:            }
11102:            $datatable .= '</table></fieldset>'.
11103:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
11104:                          '<legend>'.&mt('CSV Options').'</legend>';
11105:            foreach my $option ('hdr','pad','rem') {
11106:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
11107:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
11108:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
11109:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
11110:            }
11111:            $datatable .= '</fieldset>';
11112:            $itemcount ++;
11113:         }
11114:     }
11115:     $datatable .= '</td></tr>';
11116:     $$rowtotal ++;
11117:     return $datatable;
11118: }
11119: 
11120: sub scantronconfig_titles {
11121:     return &Apache::lonlocal::texthash(
11122:                                           dat => 'Standard format (.dat)',
11123:                                           csv => 'Comma separated values (.csv)',
11124:                                           hdr => 'Remove first line in file (contains column titles)',
11125:                                           pad => 'Prepend 0s to PaperID',
11126:                                           rem => 'Remove leading spaces (except Question Response columns)',
11127:                                           CODE => 'CODE',
11128:                                           ID   => 'Student ID',
11129:                                           PaperID => 'Paper ID',
11130:                                           FirstName => 'First Name',
11131:                                           LastName => 'Last Name',
11132:                                           FirstQuestion => 'First Question Response',
11133:                                           Section => 'Section',
11134:     );
11135: }
11136: 
11137: sub scantroncsv_fields {
11138:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
11139: }
11140: 
11141: sub print_coursecategories {
11142:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
11143:     my $datatable;
11144:     if ($position eq 'top') {
11145:         my (%checked);
11146:         my @catitems = ('unauth','auth');
11147:         my @cattypes = ('std','domonly','codesrch','none');
11148:         $checked{'unauth'} = 'std';
11149:         $checked{'auth'} = 'std';
11150:         if (ref($settings) eq 'HASH') {
11151:             foreach my $type (@cattypes) {
11152:                 if ($type eq $settings->{'unauth'}) {
11153:                     $checked{'unauth'} = $type;
11154:                 }
11155:                 if ($type eq $settings->{'auth'}) {
11156:                     $checked{'auth'} = $type;
11157:                 }
11158:             }
11159:         }
11160:         my %lt = &Apache::lonlocal::texthash (
11161:                                                unauth   => 'Catalog type for unauthenticated users',
11162:                                                auth     => 'Catalog type for authenticated users',
11163:                                                none     => 'No catalog',
11164:                                                std      => 'Standard catalog',
11165:                                                domonly  => 'Domain-only catalog',
11166:                                                codesrch => "Code search form",
11167:                                              );
11168:        my $itemcount = 0;
11169:        foreach my $item (@catitems) {
11170:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
11171:            $datatable .= '<tr '.$css_class.'>'.
11172:                          '<td>'.$lt{$item}.'</td>'.
11173:                          '<td class="LC_right_item"><span class="LC_nobreak">';
11174:            foreach my $type (@cattypes) {
11175:                my $ischecked;
11176:                if ($checked{$item} eq $type) {
11177:                    $ischecked=' checked="checked"';
11178:                }
11179:                $datatable .= '<label>'.
11180:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
11181:                              ' />'.$lt{$type}.'</label>&nbsp;';
11182:            }
11183:            $datatable .= '</span></td></tr>';
11184:            $itemcount ++;
11185:         }
11186:         $$rowtotal += $itemcount;
11187:     } elsif ($position eq 'middle') {
11188:         my $toggle_cats_crs = ' ';
11189:         my $toggle_cats_dom = ' checked="checked" ';
11190:         my $can_cat_crs = ' ';
11191:         my $can_cat_dom = ' checked="checked" ';
11192:         my $toggle_catscomm_comm = ' ';
11193:         my $toggle_catscomm_dom = ' checked="checked" ';
11194:         my $can_catcomm_comm = ' ';
11195:         my $can_catcomm_dom = ' checked="checked" ';
11196:         my $toggle_catsplace_place = ' ';
11197:         my $toggle_catsplace_dom = ' checked="checked" ';
11198:         my $can_catplace_place = ' ';
11199:         my $can_catplace_dom = ' checked="checked" ';
11200: 
11201:         if (ref($settings) eq 'HASH') {
11202:             if ($settings->{'togglecats'} eq 'crs') {
11203:                 $toggle_cats_crs = $toggle_cats_dom;
11204:                 $toggle_cats_dom = ' ';
11205:             }
11206:             if ($settings->{'categorize'} eq 'crs') {
11207:                 $can_cat_crs = $can_cat_dom;
11208:                 $can_cat_dom = ' ';
11209:             }
11210:             if ($settings->{'togglecatscomm'} eq 'comm') {
11211:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
11212:                 $toggle_catscomm_dom = ' ';
11213:             }
11214:             if ($settings->{'categorizecomm'} eq 'comm') {
11215:                 $can_catcomm_comm = $can_catcomm_dom;
11216:                 $can_catcomm_dom = ' ';
11217:             }
11218:             if ($settings->{'togglecatsplace'} eq 'place') {
11219:                 $toggle_catsplace_place = $toggle_catsplace_dom;
11220:                 $toggle_catsplace_dom = ' ';
11221:             }
11222:             if ($settings->{'categorizeplace'} eq 'place') {
11223:                 $can_catplace_place = $can_catplace_dom;
11224:                 $can_catplace_dom = ' ';
11225:             }
11226:         }
11227:         my %title = &Apache::lonlocal::texthash (
11228:                      togglecats      => 'Show/Hide a course in catalog',
11229:                      togglecatscomm  => 'Show/Hide a community in catalog',
11230:                      togglecatsplace => 'Show/Hide a placement test in catalog',
11231:                      categorize      => 'Assign a category to a course',
11232:                      categorizecomm  => 'Assign a category to a community',
11233:                      categorizeplace => 'Assign a category to a placement test',
11234:                     );
11235:         my %level = &Apache::lonlocal::texthash (
11236:                      dom   => 'Set in Domain',
11237:                      crs   => 'Set in Course',
11238:                      comm  => 'Set in Community',
11239:                      place => 'Set in Placement Test',
11240:                     );
11241:         $datatable = '<tr class="LC_odd_row">'.
11242:                   '<td>'.$title{'togglecats'}.'</td>'.
11243:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
11244:                   '<input type="radio" name="togglecats"'.
11245:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11246:                   '<label><input type="radio" name="togglecats"'.
11247:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
11248:                   '</tr><tr>'.
11249:                   '<td>'.$title{'categorize'}.'</td>'.
11250:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11251:                   '<label><input type="radio" name="categorize"'.
11252:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11253:                   '<label><input type="radio" name="categorize"'.
11254:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
11255:                   '</tr><tr class="LC_odd_row">'.
11256:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
11257:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
11258:                   '<input type="radio" name="togglecatscomm"'.
11259:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11260:                   '<label><input type="radio" name="togglecatscomm"'.
11261:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
11262:                   '</tr><tr>'.
11263:                   '<td>'.$title{'categorizecomm'}.'</td>'.
11264:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11265:                   '<label><input type="radio" name="categorizecomm"'.
11266:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11267:                   '<label><input type="radio" name="categorizecomm"'.
11268:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
11269:                   '</tr><tr class="LC_odd_row">'.
11270:                   '<td>'.$title{'togglecatsplace'}.'</td>'.
11271:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
11272:                   '<input type="radio" name="togglecatsplace"'.
11273:                   $toggle_catsplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11274:                   '<label><input type="radio" name="togglecatscomm"'.
11275:                   $toggle_catsplace_place.' value="comm" />'.$level{'place'}.'</label></span></td>'.
11276:                   '</tr><tr>'.
11277:                   '<td>'.$title{'categorizeplace'}.'</td>'.
11278:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11279:                   '<label><input type="radio" name="categorizeplace"'.
11280:                   $can_catplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11281:                   '<label><input type="radio" name="categorizeplace"'.
11282:                   $can_catplace_place.'value="place" />'.$level{'place'}.'</label></span></td>'.
11283:                   '</tr>';
11284:         $$rowtotal += 6;
11285:     } else {
11286:         my $css_class;
11287:         my $itemcount = 1;
11288:         my $cathash; 
11289:         if (ref($settings) eq 'HASH') {
11290:             $cathash = $settings->{'cats'};
11291:         }
11292:         if (ref($cathash) eq 'HASH') {
11293:             my (@cats,@trails,%allitems,%idx,@jsarray);
11294:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
11295:                                                    \%allitems,\%idx,\@jsarray);
11296:             my $maxdepth = scalar(@cats);
11297:             my $colattrib = '';
11298:             if ($maxdepth > 2) {
11299:                 $colattrib = ' colspan="2" ';
11300:             }
11301:             my @path;
11302:             if (@cats > 0) {
11303:                 if (ref($cats[0]) eq 'ARRAY') {
11304:                     my $numtop = @{$cats[0]};
11305:                     my $maxnum = $numtop;
11306:                     my %default_names = (
11307:                           instcode    => &mt('Official courses'),
11308:                           communities => &mt('Communities'),
11309:                           placement   => &mt('Placement Tests'),
11310:                     );
11311: 
11312:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
11313:                         ($cathash->{'instcode::0'} eq '') ||
11314:                         (!grep(/^communities$/,@{$cats[0]})) || 
11315:                         ($cathash->{'communities::0'} eq '') ||
11316:                         (!grep(/^placement$/,@{$cats[0]})) ||
11317:                         ($cathash->{'placement::0'} eq '')) {
11318:                         $maxnum ++;
11319:                     }
11320:                     my $lastidx;
11321:                     for (my $i=0; $i<$numtop; $i++) {
11322:                         my $parent = $cats[0][$i];
11323:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
11324:                         my $item = &escape($parent).'::0';
11325:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
11326:                         $lastidx = $idx{$item};
11327:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11328:                                       .'<select name="'.$item.'"'.$chgstr.'>';
11329:                         for (my $k=0; $k<=$maxnum; $k++) {
11330:                             my $vpos = $k+1;
11331:                             my $selstr;
11332:                             if ($k == $i) {
11333:                                 $selstr = ' selected="selected" ';
11334:                             }
11335:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11336:                         }
11337:                         $datatable .= '</select></span></td><td>';
11338:                         if ($parent eq 'instcode' || $parent eq 'communities' || $parent eq 'placement') {
11339:                             $datatable .=  '<span class="LC_nobreak">'
11340:                                            .$default_names{$parent}.'</span>';
11341:                             if ($parent eq 'instcode') {
11342:                                 $datatable .= '<br /><span class="LC_nobreak">('
11343:                                               .&mt('with institutional codes')
11344:                                               .')</span></td><td'.$colattrib.'>';
11345:                             } else {
11346:                                 $datatable .= '<table><tr><td>';
11347:                             }
11348:                             $datatable .= '<span class="LC_nobreak">'
11349:                                           .'<label><input type="radio" name="'
11350:                                           .$parent.'" value="1" checked="checked" />'
11351:                                           .&mt('Display').'</label>';
11352:                             if ($parent eq 'instcode') {
11353:                                 $datatable .= '&nbsp;';
11354:                             } else {
11355:                                 $datatable .= '</span></td></tr><tr><td>'
11356:                                               .'<span class="LC_nobreak">';
11357:                             }
11358:                             $datatable .= '<label><input type="radio" name="'
11359:                                           .$parent.'" value="0" />'
11360:                                           .&mt('Do not display').'</label></span>';
11361:                             if (($parent eq 'communities') || ($parent eq 'placement')) {
11362:                                 $datatable .= '</td></tr></table>';
11363:                             }
11364:                             $datatable .= '</td>';
11365:                         } else {
11366:                             $datatable .= $parent
11367:                                           .'&nbsp;<span class="LC_nobreak"><label>'
11368:                                           .'<input type="checkbox" name="deletecategory" '
11369:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
11370:                         }
11371:                         my $depth = 1;
11372:                         push(@path,$parent);
11373:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
11374:                         pop(@path);
11375:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
11376:                         $itemcount ++;
11377:                     }
11378:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
11379:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
11380:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
11381:                     for (my $k=0; $k<=$maxnum; $k++) {
11382:                         my $vpos = $k+1;
11383:                         my $selstr;
11384:                         if ($k == $numtop) {
11385:                             $selstr = ' selected="selected" ';
11386:                         }
11387:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11388:                     }
11389:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
11390:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
11391:                                   .'</tr>'."\n";
11392:                     $itemcount ++;
11393:                     foreach my $default ('instcode','communities','placement') {
11394:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
11395:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
11396:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
11397:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
11398:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
11399:                             for (my $k=0; $k<=$maxnum; $k++) {
11400:                                 my $vpos = $k+1;
11401:                                 my $selstr;
11402:                                 if ($k == $maxnum) {
11403:                                     $selstr = ' selected="selected" ';
11404:                                 }
11405:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11406:                             }
11407:                             $datatable .= '</select></span></td>'.
11408:                                           '<td><span class="LC_nobreak">'.
11409:                                           $default_names{$default}.'</span>';
11410:                             if ($default eq 'instcode') {
11411:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
11412:                                               .&mt('with institutional codes').')</span>';
11413:                             }
11414:                             $datatable .= '</td>'
11415:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
11416:                                           .&mt('Display').'</label>&nbsp;'
11417:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
11418:                                           .&mt('Do not display').'</label></span></td></tr>';
11419:                         }
11420:                     }
11421:                 }
11422:             } else {
11423:                 $datatable .= &initialize_categories($itemcount);
11424:             }
11425:         } else {
11426:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
11427:                           .&initialize_categories($itemcount);
11428:         }
11429:         $$rowtotal += $itemcount;
11430:     }
11431:     return $datatable;
11432: }
11433: 
11434: sub print_serverstatuses {
11435:     my ($dom,$settings,$rowtotal) = @_;
11436:     my $datatable;
11437:     my @pages = &serverstatus_pages();
11438:     my (%namedaccess,%machineaccess);
11439:     foreach my $type (@pages) {
11440:         $namedaccess{$type} = '';
11441:         $machineaccess{$type}= '';
11442:     }
11443:     if (ref($settings) eq 'HASH') {
11444:         foreach my $type (@pages) {
11445:             if (exists($settings->{$type})) {
11446:                 if (ref($settings->{$type}) eq 'HASH') {
11447:                     foreach my $key (keys(%{$settings->{$type}})) {
11448:                         if ($key eq 'namedusers') {
11449:                             $namedaccess{$type} = $settings->{$type}->{$key};
11450:                         } elsif ($key eq 'machines') {
11451:                             $machineaccess{$type} = $settings->{$type}->{$key};
11452:                         }
11453:                     }
11454:                 }
11455:             }
11456:         }
11457:     }
11458:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
11459:     my $rownum = 0;
11460:     my $css_class;
11461:     foreach my $type (@pages) {
11462:         $rownum ++;
11463:         $css_class = $rownum%2?' class="LC_odd_row"':'';
11464:         $datatable .= '<tr'.$css_class.'>'.
11465:                       '<td><span class="LC_nobreak">'.
11466:                       $titles->{$type}.'</span></td>'.
11467:                       '<td class="LC_left_item">'.
11468:                       '<input type="text" name="'.$type.'_namedusers" '.
11469:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
11470:                       '<td class="LC_right_item">'.
11471:                       '<span class="LC_nobreak">'.
11472:                       '<input type="text" name="'.$type.'_machines" '.
11473:                       'value="'.$machineaccess{$type}.'" size="10" />'.
11474:                       '</span></td></tr>'."\n";
11475:     }
11476:     $$rowtotal += $rownum;
11477:     return $datatable;
11478: }
11479: 
11480: sub serverstatus_pages {
11481:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
11482:             'checksums','clusterstatus','certstatus','metadata_keywords',
11483:             'metadata_harvest','takeoffline','takeonline','showenv','toggledebug',
11484:             'ping','domconf','uniquecodes','diskusage','coursecatalog');
11485: }
11486: 
11487: sub defaults_javascript {
11488:     my ($settings) = @_;
11489:     return unless (ref($settings) eq 'HASH');
11490:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
11491:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
11492:         if ($maxnum eq '') {
11493:             $maxnum = 0;
11494:         }
11495:         $maxnum ++;
11496:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
11497:         return <<"ENDSCRIPT";
11498: <script type="text/javascript">
11499: // <![CDATA[
11500: function reorderTypes(form,caller) {
11501:     var changedVal;
11502: $jstext 
11503:     var newpos = 'addinststatus_pos';
11504:     var current = new Array;
11505:     var maxh = $maxnum;
11506:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
11507:     var oldVal;
11508:     if (caller == newpos) {
11509:         changedVal = newitemVal;
11510:     } else {
11511:         var curritem = 'inststatus_pos_'+caller;
11512:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
11513:         current[newitemVal] = newpos;
11514:     }
11515:     for (var i=0; i<inststatuses.length; i++) {
11516:         if (inststatuses[i] != caller) {
11517:             var elementName = 'inststatus_pos_'+inststatuses[i];
11518:             if (form.elements[elementName]) {
11519:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
11520:                 current[currVal] = elementName;
11521:             }
11522:         }
11523:     }
11524:     for (var j=0; j<maxh; j++) {
11525:         if (current[j] == undefined) {
11526:             oldVal = j;
11527:         }
11528:     }
11529:     if (oldVal < changedVal) {
11530:         for (var k=oldVal+1; k<=changedVal ; k++) {
11531:            var elementName = current[k];
11532:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
11533:         }
11534:     } else {
11535:         for (var k=changedVal; k<oldVal; k++) {
11536:             var elementName = current[k];
11537:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
11538:         }
11539:     }
11540:     return;
11541: }
11542: 
11543: // ]]>
11544: </script>
11545: 
11546: ENDSCRIPT
11547:     }
11548:     return;
11549: }
11550: 
11551: sub passwords_javascript {
11552:     my ($prefix) = @_;
11553:     my %intalert;
11554:     if ($prefix eq 'passwords') {
11555:         %intalert = &Apache::lonlocal::texthash (
11556:             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.',
11557:             authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
11558:             passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
11559:             passmax => 'Warning: maximum password length must be a positive integer (or blank).',
11560:             passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
11561:             passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
11562:         );
11563:     } elsif ($prefix eq 'secrets') {
11564:         %intalert = &Apache::lonlocal::texthash (
11565:             passmin => 'Warning: minimum secret length must be a positive integer greater than 6.',
11566:             passmax => 'Warning: maximum secret length must be a positive integer (or blank).',
11567:         );
11568:     }
11569:     &js_escape(\%intalert);
11570:     my $defmin = $Apache::lonnet::passwdmin;
11571:     my $intauthjs; 
11572:     if ($prefix eq 'passwords') { $intauthjs = <<"ENDSCRIPT";
11573: 
11574: function warnIntAuth(field) {
11575:     if (field.name == 'intauth_check') {
11576:         if (field.value == '2') {
11577:             alert('$intalert{authcheck}');
11578:         }
11579:     }
11580:     if (field.name == 'intauth_cost') {
11581:         field.value.replace(/\s/g,'');
11582:         if (field.value != '') {
11583:             var regexdigit=/^\\d+\$/;
11584:             if (!regexdigit.test(field.value)) {
11585:                 alert('$intalert{authcost}');
11586:             }
11587:         }
11588:     }
11589:     return;
11590: }
11591: 
11592: ENDSCRIPT
11593: 
11594:      }
11595: 
11596:      $intauthjs .= <<"ENDSCRIPT";
11597: 
11598: function warnInt$prefix(field) {
11599:     field.value.replace(/^\s+/,'');
11600:     field.value.replace(/\s+\$/,'');
11601:     var regexdigit=/^\\d+\$/;
11602:     if (field.name == '${prefix}_min') {
11603:         if (field.value == '') {
11604:             alert('$intalert{passmin}');
11605:             field.value = '$defmin';
11606:         } else {
11607:             if (!regexdigit.test(field.value)) {
11608:                 alert('$intalert{passmin}');
11609:                 field.value = '$defmin';
11610:             }
11611:             var minval = parseInt(field.value,10);
11612:             if (minval < $defmin) {
11613:                 alert('$intalert{passmin}');
11614:                 field.value = '$defmin';
11615:             }
11616:         }
11617:     } else {
11618:         if (field.value == '0') {
11619:             field.value = '';
11620:         }
11621:         if (field.value != '') {
11622:             if (field.name == '${prefix}_expire') {
11623:                 var regexpposnum=/^\\d+(|\\.\\d*)\$/; 
11624:                 if (!regexpposnum.test(field.value)) {
11625:                     alert('$intalert{passexp}');
11626:                     field.value = '';
11627:                 } else {
11628:                     var expval = parseFloat(field.value);
11629:                     if (expval == 0) {
11630:                         alert('$intalert{passexp}');
11631:                         field.value = '';
11632:                     }
11633:                 }
11634:             } else {
11635:                 if (!regexdigit.test(field.value)) {
11636:                     if (field.name == '${prefix}_max') {
11637:                         alert('$intalert{passmax}');
11638:                     } else {
11639:                         if (field.name == '${prefix}_numsaved') {
11640:                             alert('$intalert{passnum}');
11641:                         }
11642:                     }
11643:                     field.value = '';
11644:                 }
11645:             }
11646:         }
11647:     }
11648:     return;
11649: }
11650: 
11651: ENDSCRIPT
11652:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
11653: }
11654: 
11655: sub coursecategories_javascript {
11656:     my ($settings) = @_;
11657:     my ($output,$jstext,$cathash);
11658:     if (ref($settings) eq 'HASH') {
11659:         $cathash = $settings->{'cats'};
11660:     }
11661:     if (ref($cathash) eq 'HASH') {
11662:         my (@cats,@jsarray,%idx);
11663:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
11664:         if (@jsarray > 0) {
11665:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
11666:             for (my $i=0; $i<@jsarray; $i++) {
11667:                 if (ref($jsarray[$i]) eq 'ARRAY') {
11668:                     my $catstr = join('","',@{$jsarray[$i]});
11669:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
11670:                 }
11671:             }
11672:         }
11673:     } else {
11674:         $jstext  = '    var categories = Array(1);'."\n".
11675:                    '    categories[0] = Array("instcode_pos");'."\n"; 
11676:     }
11677:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
11678:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
11679:     my $placement_reserved = &mt('The name: [_1] is a reserved category.','"placement"');
11680:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
11681:     &js_escape(\$instcode_reserved);
11682:     &js_escape(\$communities_reserved);
11683:     &js_escape(\$placement_reserved);
11684:     &js_escape(\$choose_again);
11685:     $output = <<"ENDSCRIPT";
11686: <script type="text/javascript">
11687: // <![CDATA[
11688: function reorderCats(form,parent,item,idx) {
11689:     var changedVal;
11690: $jstext
11691:     var newpos = 'addcategory_pos';
11692:     if (parent == '') {
11693:         var has_instcode = 0;
11694:         var maxtop = categories[idx].length;
11695:         for (var j=0; j<maxtop; j++) {
11696:             if (categories[idx][j] == 'instcode::0') {
11697:                 has_instcode == 1;
11698:             }
11699:         }
11700:         if (has_instcode == 0) {
11701:             categories[idx][maxtop] = 'instcode_pos';
11702:         }
11703:     } else {
11704:         newpos += '_'+parent;
11705:     }
11706:     var maxh = 1 + categories[idx].length;
11707:     var current = new Array;
11708:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
11709:     if (item == newpos) {
11710:         changedVal = newitemVal;
11711:     } else {
11712:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
11713:         current[newitemVal] = newpos;
11714:     }
11715:     for (var i=0; i<categories[idx].length; i++) {
11716:         var elementName = categories[idx][i];
11717:         if (elementName != item) {
11718:             if (form.elements[elementName]) {
11719:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
11720:                 current[currVal] = elementName;
11721:             }
11722:         }
11723:     }
11724:     var oldVal;
11725:     for (var j=0; j<maxh; j++) {
11726:         if (current[j] == undefined) {
11727:             oldVal = j;
11728:         }
11729:     }
11730:     if (oldVal < changedVal) {
11731:         for (var k=oldVal+1; k<=changedVal ; k++) {
11732:            var elementName = current[k];
11733:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
11734:         }
11735:     } else {
11736:         for (var k=changedVal; k<oldVal; k++) {
11737:             var elementName = current[k];
11738:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
11739:         }
11740:     }
11741:     return;
11742: }
11743: 
11744: function categoryCheck(form) {
11745:     if (form.elements['addcategory_name'].value == 'instcode') {
11746:         alert('$instcode_reserved\\n$choose_again');
11747:         return false;
11748:     }
11749:     if (form.elements['addcategory_name'].value == 'communities') {
11750:         alert('$communities_reserved\\n$choose_again');
11751:         return false;
11752:     }
11753:     if (form.elements['addcategory_name'].value == 'placement') {
11754:         alert('$placement_reserved\\n$choose_again');
11755:         return false;
11756:     }
11757:     return true;
11758: }
11759: 
11760: // ]]>
11761: </script>
11762: 
11763: ENDSCRIPT
11764:     return $output;
11765: }
11766: 
11767: sub initialize_categories {
11768:     my ($itemcount) = @_;
11769:     my ($datatable,$css_class,$chgstr);
11770:     my %default_names = &Apache::lonlocal::texthash (
11771:                       instcode    => 'Official courses (with institutional codes)',
11772:                       communities => 'Communities',
11773:                       placement   => 'Placement Tests',
11774:                         );
11775:     my %selnum = (
11776:                    instcode    => '0',
11777:                    communities => '1',
11778:                    placement   => '2',
11779:                  );
11780:     my %selected;
11781:     foreach my $default ('instcode','communities','placement') {
11782:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
11783:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
11784:         map { $selected{$selnum{$_}} = '' } keys(%selnum);
11785:         $selected{$selnum{$default}} = ' selected="selected"';
11786:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11787:                      .'<select name="'.$default.'_pos"'.$chgstr.'>'
11788:                      .'<option value="0"'.$selected{'0'}.'>1</option>'
11789:                      .'<option value="1"'.$selected{'1'}.'>2</option>'
11790:                      .'<option value="2"'.$selected{'2'}.'>3</option>'
11791:                      .'<option value="3">4</option></select>&nbsp;'
11792:                      .$default_names{$default}
11793:                      .'</span></td><td><span class="LC_nobreak">'
11794:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
11795:                      .&mt('Display').'</label>&nbsp;<label>'
11796:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
11797:                  .'</label></span></td></tr>';
11798:         $itemcount ++;
11799:     }
11800:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
11801:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
11802:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11803:                   .'<select name="addcategory_pos"'.$chgstr.'>'
11804:                   .'<option value="0">1</option>'
11805:                   .'<option value="1">2</option>'
11806:                   .'<option value="2">3</option>'
11807:                   .'<option value="3" selected="selected">4</option></select>&nbsp;'
11808:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
11809:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
11810:                   .'</td></tr>';
11811:     return $datatable;
11812: }
11813: 
11814: sub build_category_rows {
11815:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
11816:     my ($text,$name,$item,$chgstr);
11817:     if (ref($cats) eq 'ARRAY') {
11818:         my $maxdepth = scalar(@{$cats});
11819:         if (ref($cats->[$depth]) eq 'HASH') {
11820:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
11821:                 my $numchildren = @{$cats->[$depth]{$parent}};
11822:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
11823:                 $text .= '<td><table class="LC_data_table">';
11824:                 my ($idxnum,$parent_name,$parent_item);
11825:                 my $higher = $depth - 1;
11826:                 if ($higher == 0) {
11827:                     $parent_name = &escape($parent).'::'.$higher;
11828:                 } else {
11829:                     if (ref($path) eq 'ARRAY') {
11830:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
11831:                     }
11832:                 }
11833:                 $parent_item = 'addcategory_pos_'.$parent_name;
11834:                 for (my $j=0; $j<=$numchildren; $j++) {
11835:                     if ($j < $numchildren) {
11836:                         $name = $cats->[$depth]{$parent}[$j];
11837:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
11838:                         $idxnum = $idx->{$item};
11839:                     } else {
11840:                         $name = $parent_name;
11841:                         $item = $parent_item;
11842:                     }
11843:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
11844:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
11845:                     for (my $i=0; $i<=$numchildren; $i++) {
11846:                         my $vpos = $i+1;
11847:                         my $selstr;
11848:                         if ($j == $i) {
11849:                             $selstr = ' selected="selected" ';
11850:                         }
11851:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
11852:                     }
11853:                     $text .= '</select>&nbsp;';
11854:                     if ($j < $numchildren) {
11855:                         my $deeper = $depth+1;
11856:                         $text .= $name.'&nbsp;'
11857:                                  .'<label><input type="checkbox" name="deletecategory" value="'
11858:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
11859:                         if(ref($path) eq 'ARRAY') {
11860:                             push(@{$path},$name);
11861:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
11862:                             pop(@{$path});
11863:                         }
11864:                     } else {
11865:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
11866:                         if ($j == $numchildren) {
11867:                             $text .= $name;
11868:                         } else {
11869:                             $text .= $item;
11870:                         }
11871:                         $text .= '" value="" />';
11872:                     }
11873:                     $text .= '</td></tr>';
11874:                 }
11875:                 $text .= '</table></td>';
11876:             } else {
11877:                 my $higher = $depth-1;
11878:                 if ($higher == 0) {
11879:                     $name = &escape($parent).'::'.$higher;
11880:                 } else {
11881:                     if (ref($path) eq 'ARRAY') {
11882:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
11883:                     }
11884:                 }
11885:                 my $colspan;
11886:                 if ($parent ne 'instcode') {
11887:                     $colspan = $maxdepth - $depth - 1;
11888:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
11889:                 }
11890:             }
11891:         }
11892:     }
11893:     return $text;
11894: }
11895: 
11896: sub modifiable_userdata_row {
11897:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
11898:         $rowid,$customcss,$rowstyle,$itemdesc) = @_;
11899:     my ($role,$rolename,$statustype);
11900:     $role = $item;
11901:     if ($context eq 'cancreate') {
11902:         if ($item =~ /^(emailusername)_(.+)$/) {
11903:             $role = $1;
11904:             $statustype = $2;
11905:             if (ref($usertypes) eq 'HASH') {
11906:                 if ($usertypes->{$statustype}) {
11907:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
11908:                 } else {
11909:                     $rolename = &mt('Data provided by user');
11910:                 }
11911:             }
11912:         }
11913:     } elsif ($context eq 'selfcreate') {
11914:         if (ref($usertypes) eq 'HASH') {
11915:             $rolename = $usertypes->{$role};
11916:         } else {
11917:             $rolename = $role;
11918:         }
11919:     } elsif ($context eq 'lti') {
11920:         $rolename = &mt('Institutional data used (if available)');
11921:     } elsif ($context eq 'privacy') {
11922:         $rolename = $itemdesc;
11923:     } else {
11924:         if ($role eq 'cr') {
11925:             $rolename = &mt('Custom role');
11926:         } else {
11927:             $rolename = &Apache::lonnet::plaintext($role);
11928:         }
11929:     }
11930:     my (@fields,%fieldtitles);
11931:     if (ref($fieldsref) eq 'ARRAY') {
11932:         @fields = @{$fieldsref};
11933:     } else {
11934:         @fields = ('lastname','firstname','middlename','generation',
11935:                    'permanentemail','id');
11936:     }
11937:     if ((ref($titlesref) eq 'HASH')) {
11938:         %fieldtitles = %{$titlesref};
11939:     } else {
11940:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
11941:     }
11942:     my $output;
11943:     my $css_class;
11944:     if ($rowcount%2) {
11945:         $css_class = 'LC_odd_row';
11946:     }
11947:     if ($customcss) {
11948:         $css_class .= " $customcss";
11949:     }
11950:     $css_class =~ s/^\s+//;
11951:     if ($css_class) {
11952:         $css_class = ' class="'.$css_class.'"';
11953:     }
11954:     if ($rowstyle) {
11955:         $css_class .= ' style="'.$rowstyle.'"';
11956:     }
11957:     if ($rowid) {
11958:         $rowid = ' id="'.$rowid.'"';
11959:     }
11960:     $output = '<tr '.$css_class.$rowid.'>'.
11961:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
11962:               '<td class="LC_left_item" colspan="2"><table>';
11963:     my $rem;
11964:     my %checks;
11965:     my %current;
11966:     if (ref($settings) eq 'HASH') {
11967:         my $hashref;
11968:         if ($context eq 'lti') {
11969:             if (ref($settings) eq 'HASH') {
11970:                 $hashref = $settings->{'instdata'};
11971:             }
11972:         } elsif ($context eq 'privacy') {
11973:             my ($key,$inner) = split(/_/,$role);
11974:             if (ref($settings) eq 'HASH') {
11975:                 if (ref($settings->{$key}) eq 'HASH') {
11976:                     $hashref = $settings->{$key}->{$inner};
11977:                 }
11978:             }
11979:         } elsif (ref($settings->{$context}) eq 'HASH') {
11980:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
11981:                 $hashref = $settings->{'lti_instdata'};
11982:             }
11983:             if ($role eq 'emailusername') {
11984:                 if ($statustype) {
11985:                     if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
11986:                         $hashref = $settings->{$context}->{$role}->{$statustype};
11987:                     }
11988:                 }
11989:             }
11990:         }
11991:         if (ref($hashref) eq 'HASH') { 
11992:             foreach my $field (@fields) {
11993:                 if ($hashref->{$field}) {
11994:                     if ($role eq 'emailusername') {
11995:                         $checks{$field} = $hashref->{$field};
11996:                     } else {
11997:                         $checks{$field} = ' checked="checked" ';
11998:                     }
11999:                 }
12000:             }
12001:         }
12002:     }
12003:  
12004:     my $total = scalar(@fields);
12005:     for (my $i=0; $i<$total; $i++) {
12006:         $rem = $i%($numinrow);
12007:         if ($rem == 0) {
12008:             if ($i > 0) {
12009:                 $output .= '</tr>';
12010:             }
12011:             $output .= '<tr>';
12012:         }
12013:         my $check = ' ';
12014:         unless ($role eq 'emailusername') {
12015:             if (exists($checks{$fields[$i]})) {
12016:                 $check = $checks{$fields[$i]};
12017:             } elsif ($context eq 'privacy') {
12018:                 if ($role =~ /^priv_(domain|course)$/) {
12019:                     if (ref($settings) ne 'HASH') {
12020:                         $check = ' checked="checked" ';
12021:                     }
12022:                 } elsif ($role =~ /^priv_(author|community)$/) {
12023:                     if (ref($settings) ne 'HASH') {
12024:                         unless ($fields[$i] eq 'id') {
12025:                             $check = ' checked="checked" ';
12026:                         }
12027:                     }
12028:                 } elsif ($role =~ /^(unpriv|othdom)_/) {
12029:                     if (ref($settings) ne 'HASH') {
12030:                         if (($fields[$i] eq 'lastname') || ($fields[$i] eq 'firstname')) {
12031:                             $check = ' checked="checked" ';
12032:                         }
12033:                     }
12034:                 }
12035:             } elsif ($context ne 'lti') {
12036:                 if ($role eq 'st') {
12037:                     if (ref($settings) ne 'HASH') {
12038:                         $check = ' checked="checked" '; 
12039:                     }
12040:                 }
12041:             }
12042:         }
12043:         $output .= '<td class="LC_left_item">'.
12044:                    '<span class="LC_nobreak">';
12045:         my $prefix = 'canmodify';
12046:         if ($role eq 'emailusername') {
12047:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
12048:                 $checks{$fields[$i]} = 'omit';
12049:             }
12050:             foreach my $option ('required','optional','omit') {
12051:                 my $checked='';
12052:                 if ($checks{$fields[$i]} eq $option) {
12053:                     $checked='checked="checked" ';
12054:                 }
12055:                 $output .= '<label>'.
12056:                            '<input type="radio" name="'.$prefix.'_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
12057:                            &mt($option).'</label>'.('&nbsp;' x2);
12058:             }
12059:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
12060:         } else {
12061:             if ($context eq 'lti') {
12062:                 $prefix = 'lti';
12063:             } elsif ($context eq 'privacy') {
12064:                 $prefix = 'privacy';
12065:             }
12066:             $output .= '<label>'.
12067:                        '<input type="checkbox" name="'.$prefix.'_'.$role.'" '.
12068:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
12069:                        '</label>';
12070:         }
12071:         $output .= '</span></td>';
12072:     }
12073:     $rem = $total%$numinrow;
12074:     my $colsleft;
12075:     if ($rem) {
12076:         $colsleft = $numinrow - $rem;
12077:     }
12078:     if ($colsleft > 1) {
12079:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
12080:                    '&nbsp;</td>';
12081:     } elsif ($colsleft == 1) {
12082:         $output .= '<td class="LC_left_item">&nbsp;</td>';
12083:     }
12084:     $output .= '</tr></table></td></tr>';
12085:     return $output;
12086: }
12087: 
12088: sub insttypes_row {
12089:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
12090:         $customcss,$rowstyle) = @_;
12091:     my %lt = &Apache::lonlocal::texthash (
12092:                       cansearch => 'Users allowed to search',
12093:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
12094:                       lockablenames => 'User preference to lock name',
12095:                       selfassign    => 'Self-reportable affiliations',
12096:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
12097:              );
12098:     my $showdom;
12099:     if ($context eq 'cansearch') {
12100:         $showdom = ' ('.$dom.')';
12101:     }
12102:     my $class = 'LC_left_item';
12103:     if ($context eq 'statustocreate') {
12104:         $class = 'LC_right_item';
12105:     }
12106:     my $css_class;
12107:     if ($$rowtotal%2) {
12108:         $css_class = 'LC_odd_row';
12109:     }
12110:     if ($customcss) {
12111:         $css_class .= ' '.$customcss;
12112:     }
12113:     $css_class =~ s/^\s+//;
12114:     if ($css_class) {
12115:         $css_class = ' class="'.$css_class.'"';
12116:     }
12117:     if ($rowstyle) {
12118:         $css_class .= ' style="'.$rowstyle.'"';
12119:     }
12120:     if ($onclick) {
12121:         $onclick = 'onclick="'.$onclick.'" ';
12122:     }
12123:     my $output = '<tr'.$css_class.'>'.
12124:                  '<td>'.$lt{$context}.$showdom.
12125:                  '</td><td class="'.$class.'" colspan="2"><table>';
12126:     my $rem;
12127:     if (ref($types) eq 'ARRAY') {
12128:         for (my $i=0; $i<@{$types}; $i++) {
12129:             if (defined($usertypes->{$types->[$i]})) {
12130:                 my $rem = $i%($numinrow);
12131:                 if ($rem == 0) {
12132:                     if ($i > 0) {
12133:                         $output .= '</tr>';
12134:                     }
12135:                     $output .= '<tr>';
12136:                 }
12137:                 my $check = ' ';
12138:                 if (ref($settings) eq 'HASH') {
12139:                     if (ref($settings->{$context}) eq 'ARRAY') {
12140:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
12141:                             $check = ' checked="checked" ';
12142:                         }
12143:                     } elsif (ref($settings->{$context}) eq 'HASH') {
12144:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
12145:                             $check = ' checked="checked" ';
12146:                         }
12147:                     } elsif ($context eq 'statustocreate') {
12148:                         $check = ' checked="checked" ';
12149:                     }
12150:                 }
12151:                 $output .= '<td class="LC_left_item">'.
12152:                            '<span class="LC_nobreak"><label>'.
12153:                            '<input type="checkbox" name="'.$context.'" '.
12154:                            'value="'.$types->[$i].'"'.$check.$onclick.' />'.
12155:                            $usertypes->{$types->[$i]}.'</label></span></td>';
12156:             }
12157:         }
12158:         $rem = @{$types}%($numinrow);
12159:     }
12160:     my $colsleft = $numinrow - $rem;
12161:     if ($context eq 'overrides') {
12162:         if ($colsleft > 1) {
12163:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
12164:         } else {
12165:             $output .= '<td class="LC_left_item">';
12166:         }
12167:         $output .= '&nbsp;';  
12168:     } else {
12169:         if ($rem == 0) {
12170:             $output .= '<tr>';
12171:         }
12172:         if ($colsleft > 1) {
12173:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
12174:         } else {
12175:             $output .= '<td class="LC_left_item">';
12176:         }
12177:         my $defcheck = ' ';
12178:         if (ref($settings) eq 'HASH') {  
12179:             if (ref($settings->{$context}) eq 'ARRAY') {
12180:                 if (grep(/^default$/,@{$settings->{$context}})) {
12181:                     $defcheck = ' checked="checked" ';
12182:                 }
12183:             } elsif ($context eq 'statustocreate') {
12184:                 $defcheck = ' checked="checked" ';
12185:             }
12186:         }
12187:         $output .= '<span class="LC_nobreak"><label>'.
12188:                    '<input type="checkbox" name="'.$context.'" '.
12189:                    'value="default"'.$defcheck.$onclick.' />'.
12190:                    $othertitle.'</label></span>';
12191:     }
12192:     $output .= '</td></tr></table></td></tr>';
12193:     return $output;
12194: }
12195: 
12196: sub sorted_searchtitles {
12197:     my %searchtitles = &Apache::lonlocal::texthash(
12198:                          'uname' => 'username',
12199:                          'lastname' => 'last name',
12200:                          'lastfirst' => 'last name, first name',
12201:                      );
12202:     my @titleorder = ('uname','lastname','lastfirst');
12203:     return (\%searchtitles,\@titleorder);
12204: }
12205: 
12206: sub sorted_searchtypes {
12207:     my %srchtypes_desc = (
12208:                            exact    => 'is exact match',
12209:                            contains => 'contains ..',
12210:                            begins   => 'begins with ..',
12211:                          );
12212:     my @srchtypeorder = ('exact','begins','contains');
12213:     return (\%srchtypes_desc,\@srchtypeorder);
12214: }
12215: 
12216: sub usertype_update_row {
12217:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
12218:     my $datatable;
12219:     my $numinrow = 4;
12220:     foreach my $type (@{$types}) {
12221:         if (defined($usertypes->{$type})) {
12222:             $$rownums ++;
12223:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
12224:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
12225:                           '</td><td class="LC_left_item"><table>';
12226:             for (my $i=0; $i<@{$fields}; $i++) {
12227:                 my $rem = $i%($numinrow);
12228:                 if ($rem == 0) {
12229:                     if ($i > 0) {
12230:                         $datatable .= '</tr>';
12231:                     }
12232:                     $datatable .= '<tr>';
12233:                 }
12234:                 my $check = ' ';
12235:                 if (ref($settings) eq 'HASH') {
12236:                     if (ref($settings->{'fields'}) eq 'HASH') {
12237:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
12238:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
12239:                                 $check = ' checked="checked" ';
12240:                             }
12241:                         }
12242:                     }
12243:                 }
12244: 
12245:                 if ($i == @{$fields}-1) {
12246:                     my $colsleft = $numinrow - $rem;
12247:                     if ($colsleft > 1) {
12248:                         $datatable .= '<td colspan="'.$colsleft.'">';
12249:                     } else {
12250:                         $datatable .= '<td>';
12251:                     }
12252:                 } else {
12253:                     $datatable .= '<td>';
12254:                 }
12255:                 $datatable .= '<span class="LC_nobreak"><label>'.
12256:                               '<input type="checkbox" name="updateable_'.$type.
12257:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
12258:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
12259:             }
12260:             $datatable .= '</tr></table></td></tr>';
12261:         }
12262:     }
12263:     return $datatable;
12264: }
12265: 
12266: sub modify_login {
12267:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
12268:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
12269:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon,
12270:         %currsaml,%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlwindow,%samlnotsso);
12271:     %title = ( coursecatalog => 'Display course catalog',
12272:                adminmail => 'Display administrator E-mail address',
12273:                helpdesk  => 'Display "Contact Helpdesk" link',
12274:                newuser => 'Link for visitors to create a user account',
12275:                loginheader => 'Log-in box header',
12276:                saml => 'Dual SSO and non-SSO login');
12277:     @offon = ('off','on');
12278:     if (ref($domconfig{login}) eq 'HASH') {
12279:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
12280:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
12281:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
12282:             }
12283:         }
12284:         if (ref($domconfig{login}{'saml'}) eq 'HASH') {
12285:             foreach my $lonhost (keys(%{$domconfig{login}{'saml'}})) {
12286:                 if (ref($domconfig{login}{'saml'}{$lonhost}) eq 'HASH') {
12287:                     $currsaml{$lonhost} = $domconfig{login}{'saml'}{$lonhost};
12288:                     $saml{$lonhost} = 1;
12289:                     $samltext{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'text'};
12290:                     $samlurl{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'url'};
12291:                     $samlalt{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'alt'};
12292:                     $samlimg{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'img'};
12293:                     $samltitle{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'title'};
12294:                     $samlwindow{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'window'};
12295:                     $samlnotsso{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'notsso'};
12296:                 }
12297:             }
12298:         }
12299:     }
12300:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
12301:                                            \%domconfig,\%loginhash);
12302:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
12303:     foreach my $item (@toggles) {
12304:         $loginhash{login}{$item} = $env{'form.'.$item};
12305:     }
12306:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
12307:     if (ref($colchanges{'login'}) eq 'HASH') {  
12308:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
12309:                                          \%loginhash);
12310:     }
12311: 
12312:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
12313:     my %domservers = &Apache::lonnet::get_servers($dom);
12314:     my @loginvia_attribs = ('serverpath','custompath','exempt');
12315:     if (keys(%servers) > 1) {
12316:         foreach my $lonhost (keys(%servers)) {
12317:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
12318:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
12319:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
12320:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
12321:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
12322:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12323:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12324:                         $changes{'loginvia'}{$lonhost} = 1;
12325:                     } else {
12326:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
12327:                         $changes{'loginvia'}{$lonhost} = 1;
12328:                     }
12329:                 } else {
12330:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12331:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12332:                         $changes{'loginvia'}{$lonhost} = 1;
12333:                     }
12334:                 }
12335:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
12336:                     foreach my $item (@loginvia_attribs) {
12337:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
12338:                     }
12339:                 } else {
12340:                     foreach my $item (@loginvia_attribs) {
12341:                         my $new = $env{'form.'.$lonhost.'_'.$item};
12342:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
12343:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
12344:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
12345:                                 $new = '/';
12346:                             }
12347:                         }
12348:                         if (($item eq 'custompath') && 
12349:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
12350:                             $new = '';
12351:                         }
12352:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
12353:                             $changes{'loginvia'}{$lonhost} = 1;
12354:                         }
12355:                         if ($item eq 'exempt') {
12356:                             $new = &check_exempt_addresses($new);
12357:                         }
12358:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
12359:                     }
12360:                 }
12361:             } else {
12362:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12363:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12364:                     $changes{'loginvia'}{$lonhost} = 1;
12365:                     foreach my $item (@loginvia_attribs) {
12366:                         my $new = $env{'form.'.$lonhost.'_'.$item};
12367:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
12368:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
12369:                                 $new = '/';
12370:                             }
12371:                         }
12372:                         if (($item eq 'custompath') && 
12373:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
12374:                             $new = '';
12375:                         }
12376:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
12377:                     }
12378:                 }
12379:             }
12380:         }
12381:     }
12382: 
12383:     my $servadm = $r->dir_config('lonAdmEMail');
12384:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
12385:     if (ref($domconfig{'login'}) eq 'HASH') {
12386:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
12387:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
12388:                 if ($lang eq 'nolang') {
12389:                     push(@currlangs,$lang);
12390:                 } elsif (defined($langchoices{$lang})) {
12391:                     push(@currlangs,$lang);
12392:                 } else {
12393:                     next;
12394:                 }
12395:             }
12396:         }
12397:     }
12398:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
12399:     if (@currlangs > 0) {
12400:         foreach my $lang (@currlangs) {
12401:             if (grep(/^\Q$lang\E$/,@delurls)) {
12402:                 $changes{'helpurl'}{$lang} = 1;
12403:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
12404:                 $changes{'helpurl'}{$lang} = 1;
12405:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
12406:                 push(@newlangs,$lang);
12407:             } else {
12408:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
12409:             }
12410:         }
12411:     }
12412:     unless (grep(/^nolang$/,@currlangs)) {
12413:         if ($env{'form.loginhelpurl_nolang.filename'}) {
12414:             $changes{'helpurl'}{'nolang'} = 1;
12415:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
12416:             push(@newlangs,'nolang');
12417:         }
12418:     }
12419:     if ($env{'form.loginhelpurl_add_lang'}) {
12420:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
12421:             ($env{'form.loginhelpurl_add_file.filename'})) {
12422:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
12423:             $addedfile = $env{'form.loginhelpurl_add_lang'};
12424:         }
12425:     }
12426:     if ((@newlangs > 0) || ($addedfile)) {
12427:         my $error;
12428:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12429:         if ($configuserok eq 'ok') {
12430:             if ($switchserver) {
12431:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
12432:             } elsif ($author_ok eq 'ok') {
12433:                 my @allnew = @newlangs;
12434:                 if ($addedfile ne '') {
12435:                     push(@allnew,$addedfile);
12436:                 }
12437:                 foreach my $lang (@allnew) {
12438:                     my $formelem = 'loginhelpurl_'.$lang;
12439:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
12440:                         $formelem = 'loginhelpurl_add_file';
12441:                     }
12442:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
12443:                                                                "help/$lang",'','',$newfile{$lang});
12444:                     if ($result eq 'ok') {
12445:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
12446:                         $changes{'helpurl'}{$lang} = 1;
12447:                     } else {
12448:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
12449:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12450:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
12451:                             (!grep(/^\Q$lang\E$/,@delurls))) {
12452:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
12453:                         }
12454:                     }
12455:                 }
12456:             } else {
12457:                 $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);
12458:             }
12459:         } else {
12460:             $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);
12461:         }
12462:         if ($error) {
12463:             &Apache::lonnet::logthis($error);
12464:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12465:         }
12466:     }
12467: 
12468:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
12469:     if (ref($domconfig{'login'}) eq 'HASH') {
12470:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
12471:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
12472:                 if ($domservers{$lonhost}) {
12473:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
12474:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
12475:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
12476:                     }
12477:                 }
12478:             }
12479:         }
12480:     }
12481:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
12482:     foreach my $lonhost (sort(keys(%domservers))) {
12483:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
12484:             $changes{'headtag'}{$lonhost} = 1;
12485:         } else {
12486:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
12487:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
12488:             }
12489:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
12490:                 push(@newhosts,$lonhost);
12491:             } elsif ($currheadtagurls{$lonhost}) {
12492:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
12493:                 if ($currexempt{$lonhost}) {
12494:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
12495:                         $changes{'headtag'}{$lonhost} = 1;
12496:                     }
12497:                 } elsif ($possexempt{$lonhost}) {
12498:                     $changes{'headtag'}{$lonhost} = 1;
12499:                 }
12500:                 if ($possexempt{$lonhost}) {
12501:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
12502:                 }
12503:             }
12504:         }
12505:     }
12506:     if (@newhosts) {
12507:         my $error;
12508:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12509:         if ($configuserok eq 'ok') {
12510:             if ($switchserver) {
12511:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
12512:             } elsif ($author_ok eq 'ok') {
12513:                 foreach my $lonhost (@newhosts) {
12514:                     my $formelem = 'loginheadtag_'.$lonhost;
12515:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
12516:                                                                           "login/headtag/$lonhost",'','',
12517:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
12518:                     if ($result eq 'ok') {
12519:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
12520:                         $changes{'headtag'}{$lonhost} = 1;
12521:                         if ($possexempt{$lonhost}) {
12522:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
12523:                         }
12524:                     } else {
12525:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
12526:                                            $newheadtagurls{$lonhost},$result);
12527:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12528:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
12529:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
12530:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
12531:                         }
12532:                     }
12533:                 }
12534:             } else {
12535:                 $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);
12536:             }
12537:         } else {
12538:             $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);
12539:         }
12540:         if ($error) {
12541:             &Apache::lonnet::logthis($error);
12542:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12543:         }
12544:     }
12545:     my @delsamlimg = &Apache::loncommon::get_env_multiple('form.saml_img_del');
12546:     my @newsamlimgs;
12547:     foreach my $lonhost (keys(%domservers)) {
12548:         if ($env{'form.saml_'.$lonhost}) {
12549:             if ($env{'form.saml_img_'.$lonhost.'.filename'}) {
12550:                 push(@newsamlimgs,$lonhost);
12551:             }
12552:             foreach my $item ('text','alt','url','title','window','notsso') {
12553:                 $env{'form.saml_'.$item.'_'.$lonhost} =~ s/^\s+|\s+$//g;
12554:             }
12555:             if ($saml{$lonhost}) {
12556:                 if ($env{'form.saml_window_'.$lonhost} ne '1') {
12557:                     $env{'form.saml_window_'.$lonhost} = '';
12558:                 }
12559:                 if (grep(/^\Q$lonhost\E$/,@delsamlimg)) {
12560: #FIXME Need to obsolete published image
12561:                     delete($currsaml{$lonhost}{'img'});
12562:                     $changes{'saml'}{$lonhost} = 1;
12563:                 }
12564:                 if ($env{'form.saml_alt_'.$lonhost} ne $samlalt{$lonhost}) {
12565:                     $changes{'saml'}{$lonhost} = 1;
12566:                 }
12567:                 if ($env{'form.saml_text_'.$lonhost} ne $samltext{$lonhost}) {
12568:                     $changes{'saml'}{$lonhost} = 1;
12569:                 }
12570:                 if ($env{'form.saml_url_'.$lonhost} ne $samlurl{$lonhost}) {
12571:                     $changes{'saml'}{$lonhost} = 1;
12572:                 }
12573:                 if ($env{'form.saml_title_'.$lonhost} ne $samltitle{$lonhost}) {
12574:                     $changes{'saml'}{$lonhost} = 1;
12575:                 }
12576:                 if ($env{'form.saml_window_'.$lonhost} ne $samlwindow{$lonhost}) {
12577:                     $changes{'saml'}{$lonhost} = 1;
12578:                 }
12579:                 if ($env{'form.saml_notsso_'.$lonhost} ne $samlnotsso{$lonhost}) {
12580:                     $changes{'saml'}{$lonhost} = 1;
12581:                 }
12582:             } else {
12583:                 $changes{'saml'}{$lonhost} = 1;
12584:             }
12585:             foreach my $item ('text','alt','url','title','window','notsso') {
12586:                 $currsaml{$lonhost}{$item} = $env{'form.saml_'.$item.'_'.$lonhost};
12587:             }
12588:         } else {
12589:             if ($saml{$lonhost}) {  
12590:                 $changes{'saml'}{$lonhost} = 1;
12591:                 delete($currsaml{$lonhost});
12592:             }
12593:         }
12594:     }
12595:     foreach my $posshost (keys(%currsaml)) {
12596:         unless (exists($domservers{$posshost})) { 
12597:             delete($currsaml{$posshost}); 
12598:         }
12599:     }
12600:     %{$loginhash{'login'}{'saml'}} = %currsaml;
12601:     if (@newsamlimgs) {
12602:         my $error;
12603:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12604:         if ($configuserok eq 'ok') {
12605:             if ($switchserver) {
12606:                 $error = &mt("Upload of SSO Button Image is not permitted to this server: [_1].",$switchserver);
12607:             } elsif ($author_ok eq 'ok') {
12608:                 foreach my $lonhost (@newsamlimgs) {
12609:                     my $formelem = 'saml_img_'.$lonhost;
12610:                     my ($result,$imgurl) = &publishlogo($r,'upload',$formelem,$dom,$confname,
12611:                                                         "login/saml/$lonhost",'','',
12612:                                                         $env{'form.saml_img_'.$lonhost.'.filename'});
12613:                     if ($result eq 'ok') {
12614:                         $currsaml{$lonhost}{'img'} = $imgurl;
12615:                         $loginhash{'login'}{'saml'}{$lonhost}{'img'} = $imgurl;
12616:                         $changes{'saml'}{$lonhost} = 1;
12617:                     } else {
12618:                         my $puberror = &mt("Upload of SSO button image failed for [_1] because an error occurred publishing the file in RES space. Error was: [_2].",
12619:                                            $lonhost,$result);
12620:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12621:                     }
12622:                 }
12623:             } else {
12624:                 $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);
12625:             }
12626:         } else {
12627:             $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);
12628:         }
12629:         if ($error) {
12630:             &Apache::lonnet::logthis($error);
12631:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12632:         }
12633:     }
12634:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
12635: 
12636:     my $defaulthelpfile = '/adm/loginproblems.html';
12637:     my $defaulttext = &mt('Default in use');
12638: 
12639:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
12640:                                              $dom);
12641:     if ($putresult eq 'ok') {
12642:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
12643:         my %defaultchecked = (
12644:                     'coursecatalog' => 'on',
12645:                     'helpdesk'      => 'on',
12646:                     'adminmail'     => 'off',
12647:                     'newuser'       => 'off',
12648:         );
12649:         if (ref($domconfig{'login'}) eq 'HASH') {
12650:             foreach my $item (@toggles) {
12651:                 if ($defaultchecked{$item} eq 'on') { 
12652:                     if (($domconfig{'login'}{$item} eq '0') &&
12653:                         ($env{'form.'.$item} eq '1')) {
12654:                         $changes{$item} = 1;
12655:                     } elsif (($domconfig{'login'}{$item} eq '' ||
12656:                               $domconfig{'login'}{$item} eq '1') &&
12657:                              ($env{'form.'.$item} eq '0')) {
12658:                         $changes{$item} = 1;
12659:                     }
12660:                 } elsif ($defaultchecked{$item} eq 'off') {
12661:                     if (($domconfig{'login'}{$item} eq '1') &&
12662:                         ($env{'form.'.$item} eq '0')) {
12663:                         $changes{$item} = 1;
12664:                     } elsif (($domconfig{'login'}{$item} eq '' ||
12665:                               $domconfig{'login'}{$item} eq '0') &&
12666:                              ($env{'form.'.$item} eq '1')) {
12667:                         $changes{$item} = 1;
12668:                     }
12669:                 }
12670:             }
12671:         }
12672:         if (keys(%changes) > 0 || $colchgtext) {
12673:             &Apache::loncommon::devalidate_domconfig_cache($dom);
12674:             if (exists($changes{'saml'})) {
12675:                 my $hostid_in_use;
12676:                 my @hosts = &Apache::lonnet::current_machine_ids();
12677:                 if (@hosts > 1) {
12678:                     foreach my $hostid (@hosts) {
12679:                         if (&Apache::lonnet::host_domain($hostid) eq $dom) {
12680:                             $hostid_in_use = $hostid;
12681:                             last;
12682:                         }
12683:                     }
12684:                 } else {
12685:                     $hostid_in_use = $r->dir_config('lonHostID');
12686:                 }
12687:                 if (($hostid_in_use) &&
12688:                     (&Apache::lonnet::host_domain($hostid_in_use) eq $dom)) {
12689:                     &Apache::lonnet::devalidate_cache_new('samllanding',$hostid_in_use);
12690:                 }
12691:                 if (ref($lastactref) eq 'HASH') {
12692:                     if (ref($changes{'saml'}) eq 'HASH') {
12693:                         my %updates;
12694:                         map { $updates{$_} = 1; } keys(%{$changes{'saml'}});
12695:                         $lastactref->{'samllanding'} = \%updates;
12696:                     }
12697:                 }
12698:             }
12699:             if (ref($lastactref) eq 'HASH') {
12700:                 $lastactref->{'domainconfig'} = 1;
12701:             }
12702:             $resulttext = &mt('Changes made:').'<ul>';
12703:             foreach my $item (sort(keys(%changes))) {
12704:                 if ($item eq 'loginvia') {
12705:                     if (ref($changes{$item}) eq 'HASH') {
12706:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
12707:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12708:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
12709:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
12710:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
12711:                                     $protocol = 'http' if ($protocol ne 'https');
12712:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
12713: 
12714:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
12715:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
12716:                                     } else {
12717:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
12718:                                     }
12719:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
12720:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
12721:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
12722:                                     }
12723:                                     $resulttext .= '</li>';
12724:                                 } else {
12725:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
12726:                                 }
12727:                             } else {
12728:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
12729:                             }
12730:                         }
12731:                         $resulttext .= '</ul></li>';
12732:                     }
12733:                 } elsif ($item eq 'helpurl') {
12734:                     if (ref($changes{$item}) eq 'HASH') {
12735:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
12736:                             if (grep(/^\Q$lang\E$/,@delurls)) {
12737:                                 my ($chg,$link);
12738:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
12739:                                 if ($lang eq 'nolang') {
12740:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
12741:                                 } else {
12742:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
12743:                                 }
12744:                                 $resulttext .= '<li>'.$chg.'</li>';
12745:                             } else {
12746:                                 my $chg;
12747:                                 if ($lang eq 'nolang') {
12748:                                     $chg = &mt('custom log-in help file for no preferred language');
12749:                                 } else {
12750:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
12751:                                 }
12752:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
12753:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
12754:                                                       '?inhibitmenu=yes',$chg,600,500).
12755:                                                '</li>';
12756:                             }
12757:                         }
12758:                     }
12759:                 } elsif ($item eq 'headtag') {
12760:                     if (ref($changes{$item}) eq 'HASH') {
12761:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12762:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
12763:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
12764:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
12765:                                 $resulttext .= '<li><a href="'.
12766:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
12767:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
12768:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
12769:                                 if ($possexempt{$lonhost}) {
12770:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
12771:                                 } else {
12772:                                     $resulttext .= &mt('included for any client IP');
12773:                                 }
12774:                                 $resulttext .= '</li>';
12775:                             }
12776:                         }
12777:                     }
12778:                 } elsif ($item eq 'saml') {
12779:                     if (ref($changes{$item}) eq 'HASH') {
12780:                         my %notlt = (
12781:                                        text   => 'Text for log-in by SSO',
12782:                                        img    => 'SSO button image',
12783:                                        alt    => 'Alt text for button image',
12784:                                        url    => 'SSO URL',
12785:                                        title  => 'Tooltip for SSO link',
12786:                                        window => 'Pop-up window if iframe',
12787:                                        notsso => 'Text for non-SSO log-in',
12788:                                     );
12789:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12790:                             if (ref($currsaml{$lonhost}) eq 'HASH') {
12791:                                 $resulttext .= '<li>'.&mt("$title{$item} in use for [_1]","<b>$lonhost</b>").
12792:                                                '<ul>';
12793:                                 foreach my $key ('text','img','alt','url','title','window','notsso') {
12794:                                     if ($currsaml{$lonhost}{$key} eq '') {
12795:                                         $resulttext .= '<li>'.&mt("$notlt{$key} not in use").'</li>';
12796:                                     } else {
12797:                                         my $value = "'$currsaml{$lonhost}{$key}'";
12798:                                         if ($key eq 'img') {
12799:                                             $value = '<img src="'.$currsaml{$lonhost}{$key}.'" />';
12800:                                         } elsif ($key eq 'window') {
12801:                                             $value = 'On';
12802:                                         }
12803:                                         $resulttext .= '<li>'.&mt("$notlt{$key} set to: [_1]",
12804:                                                                   $value).'</li>';
12805:                                     }
12806:                                 }
12807:                                 $resulttext .= '</ul></li>';
12808:                             } else {
12809:                                 $resulttext .= '<li>'.&mt("$title{$item} not in use for [_1]",$lonhost).'</li>';
12810:                             }
12811:                         }
12812:                     }
12813:                 } elsif ($item eq 'captcha') {
12814:                     if (ref($loginhash{'login'}) eq 'HASH') {
12815:                         my $chgtxt;
12816:                         if ($loginhash{'login'}{$item} eq 'notused') {
12817:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
12818:                         } else {
12819:                             my %captchas = &captcha_phrases();
12820:                             if ($captchas{$loginhash{'login'}{$item}}) {
12821:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
12822:                             } else {
12823:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
12824:                             }
12825:                         }
12826:                         $resulttext .= '<li>'.$chgtxt.'</li>';
12827:                     }
12828:                 } elsif ($item eq 'recaptchakeys') {
12829:                     if (ref($loginhash{'login'}) eq 'HASH') {
12830:                         my ($privkey,$pubkey);
12831:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
12832:                             $pubkey = $loginhash{'login'}{$item}{'public'};
12833:                             $privkey = $loginhash{'login'}{$item}{'private'};
12834:                         }
12835:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
12836:                         if (!$pubkey) {
12837:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
12838:                         } else {
12839:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
12840:                         }
12841:                         if (!$privkey) {
12842:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
12843:                         } else {
12844:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
12845:                         }
12846:                         $chgtxt .= '</ul>';
12847:                         $resulttext .= '<li>'.$chgtxt.'</li>';
12848:                     }
12849:                 } elsif ($item eq 'recaptchaversion') {
12850:                     if (ref($loginhash{'login'}) eq 'HASH') {
12851:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
12852:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
12853:                                            '</li>';
12854:                         }
12855:                     }
12856:                 } else {
12857:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
12858:                 }
12859:             }
12860:             $resulttext .= $colchgtext.'</ul>';
12861:         } else {
12862:             $resulttext = &mt('No changes made to log-in page settings');
12863:         }
12864:     } else {
12865:         $resulttext = '<span class="LC_error">'.
12866: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
12867:     }
12868:     if ($errors) {
12869:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
12870:                        $errors.'</ul>';
12871:     }
12872:     return $resulttext;
12873: }
12874: 
12875: sub check_exempt_addresses {
12876:     my ($iplist) = @_;
12877:     $iplist =~ s/^\s+//;
12878:     $iplist =~ s/\s+$//;
12879:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
12880:     my (@okips,$new);
12881:     foreach my $ip (@poss_ips) {
12882:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
12883:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
12884:                 push(@okips,$ip);
12885:             }
12886:         }
12887:     }
12888:     if (@okips > 0) {
12889:         $new = join(',',@okips);
12890:     } else {
12891:         $new = '';
12892:     }
12893:     return $new;
12894: }
12895: 
12896: sub color_font_choices {
12897:     my %choices =
12898:         &Apache::lonlocal::texthash (
12899:             img => "Header",
12900:             bgs => "Background colors",
12901:             links => "Link colors",
12902:             images => "Images",
12903:             font => "Font color",
12904:             fontmenu => "Font menu",
12905:             pgbg => "Page",
12906:             tabbg => "Header",
12907:             sidebg => "Border",
12908:             link => "Link",
12909:             alink => "Active link",
12910:             vlink => "Visited link",
12911:         );
12912:     return %choices;
12913: }
12914: 
12915: sub modify_ipaccess {
12916:     my ($dom,$lastactref,%domconfig) = @_;
12917:     my (@allpos,%changes,%confhash,$errors,$resulttext);
12918:     my (@items,%deletions,%itemids,@warnings);
12919:     my ($typeorder,$types) = &commblocktype_text();
12920:     if ($env{'form.ipaccess_add'}) {
12921:         my $name = $env{'form.ipaccess_name_add'};
12922:         my ($newid,$error) = &get_ipaccess_id($dom,$name);
12923:         if ($newid) {
12924:             $itemids{'add'} = $newid;
12925:             push(@items,'add');
12926:             $changes{$newid} = 1;
12927:         } else {
12928:             $error = &mt('Failed to acquire unique ID for new IP access control item');
12929:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12930:         }
12931:     }
12932:     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
12933:         my @todelete = &Apache::loncommon::get_env_multiple('form.ipaccess_del');
12934:         if (@todelete) {
12935:             map { $deletions{$_} = 1; } @todelete;
12936:         }
12937:         my $maxnum = $env{'form.ipaccess_maxnum'};
12938:         for (my $i=0; $i<$maxnum; $i++) {
12939:             my $itemid = $env{'form.ipaccess_id_'.$i};
12940:             $itemid =~ s/\D+//g;
12941:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
12942:                 if ($deletions{$itemid}) {
12943:                     $changes{$itemid} = $domconfig{'ipaccess'}{$itemid}{'name'};
12944:                 } else {
12945:                     push(@items,$i);
12946:                     $itemids{$i} = $itemid;
12947:                 }
12948:             }
12949:         }
12950:     }
12951:     foreach my $idx (@items) {
12952:         my $itemid = $itemids{$idx};
12953:         next unless ($itemid);
12954:         my %current;
12955:         unless ($idx eq 'add') {
12956:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
12957:                 %current = %{$domconfig{'ipaccess'}{$itemid}};
12958:             }
12959:         }
12960:         my $position = $env{'form.ipaccess_pos_'.$itemid};
12961:         $position =~ s/\D+//g;
12962:         if ($position ne '') {
12963:             $allpos[$position] = $itemid;
12964:         }
12965:         my $name = $env{'form.ipaccess_name_'.$idx};
12966:         $name =~ s/^\s+|\s+$//g;
12967:         $confhash{$itemid}{'name'} = $name;
12968:         my $possrange = $env{'form.ipaccess_range_'.$idx};
12969:         $possrange =~ s/^\s+|\s+$//g;
12970:         unless ($possrange eq '') {
12971:             $possrange =~ s/[\r\n]+/\s/g;
12972:             $possrange =~ s/\s*-\s*/-/g;
12973:             $possrange =~ s/\s+/,/g;
12974:             $possrange =~ s/,+/,/g;
12975:             if ($possrange ne '') {
12976:                 my (@ok,$count);
12977:                 $count = 0; 
12978:                 foreach my $poss (split(/\,/,$possrange)) {
12979:                     $count ++;
12980:                     $poss = &validate_ip_pattern($poss);
12981:                     if ($poss ne '') {
12982:                         push(@ok,$poss);
12983:                     }
12984:                 }
12985:                 my $diff = $count - scalar(@ok);
12986:                 if ($diff) {
12987:                     $errors .= '<li><span class="LC_error">'.
12988:                                &mt('[quant,_1,IP] invalid and excluded from saved value for IP range(s) for [_2]',
12989:                                    $diff,$name).
12990:                                '</span></li>';
12991:                 }
12992:                 if (@ok) {
12993:                     my @cidr_list;
12994:                     foreach my $item (@ok) {
12995:                         @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
12996:                     }
12997:                     $confhash{$itemid}{'ip'} = join(',',@cidr_list);
12998:                 }
12999:             }
13000:         }
13001:         foreach my $field ('name','ip') {
13002:             unless (($idx eq 'add') || ($changes{$itemid})) {
13003:                 if ($current{$field} ne $confhash{$itemid}{$field}) {
13004:                     $changes{$itemid} = 1;
13005:                     last;
13006:                 }
13007:             }
13008:         }
13009:         $confhash{$itemid}{'commblocks'} = {};
13010:          
13011:         my %commblocks;
13012:         map { $commblocks{$_} = 1; } &Apache::loncommon::get_env_multiple('form.ipaccess_block_'.$idx);  
13013:         foreach my $type (@{$typeorder}) {
13014:             if ($commblocks{$type}) {
13015:                 $confhash{$itemid}{'commblocks'}{$type} = 'on';
13016:             }
13017:             unless (($idx eq 'add') || ($changes{$itemid})) {
13018:                 if (ref($current{'commblocks'}) eq 'HASH') {
13019:                     if ($confhash{$itemid}{'commblocks'}{$type} ne $current{'commblocks'}{$type}) {
13020:                         $changes{$itemid} = 1;
13021:                     }
13022:                 } elsif ($confhash{$itemid}{'commblocks'}{$type}) {
13023:                     $changes{$itemid} = 1;
13024:                 }
13025:             }
13026:         }
13027:         $confhash{$itemid}{'courses'} = {};
13028:         my %crsdeletions;
13029:         my @delcrs = &Apache::loncommon::get_env_multiple('form.ipaccess_course_delete_'.$idx);
13030:         if (@delcrs) {
13031:             map { $crsdeletions{$_} = 1; } @delcrs;
13032:         }
13033:         if (ref($current{'courses'}) eq 'HASH') {
13034:             foreach my $cid (sort(keys(%{$current{'courses'}}))) {
13035:                 if ($crsdeletions{$cid}) {
13036:                     $changes{$itemid} = 1;
13037:                 } else {
13038:                     $confhash{$itemid}{'courses'}{$cid} = 1;
13039:                 }
13040:             }
13041:         }
13042:         $env{'form.ipaccess_cnum_'.$idx} =~ s/^\s+|\s+$//g;
13043:         $env{'form.ipaccess_cdom_'.$idx} =~ s/^\s+|\s+$//g;
13044:         if (($env{'form.ipaccess_cnum_'.$idx} =~ /^$match_courseid$/) && 
13045:             ($env{'form.ipaccess_cdom_'.$idx} =~ /^$match_domain$/)) {
13046:             if (&Apache::lonnet::homeserver($env{'form.ipaccess_cnum_'.$idx},
13047:                                             $env{'form.ipaccess_cdom_'.$idx}) eq 'no_host') {
13048:                 $errors .= '<li><span class="LC_error">'.
13049:                            &mt('Invalid courseID [_1] omitted from list of allowed courses',
13050:                                $env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}).
13051:                            '</span></li>';
13052:             } else {
13053:                 $confhash{$itemid}{'courses'}{$env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}} = 1;
13054:                 $changes{$itemid} = 1;
13055:             }
13056:         }
13057:     }
13058:     if (@allpos > 0) {
13059:         my $idx = 0;
13060:         foreach my $itemid (@allpos) {
13061:             if ($itemid ne '') {
13062:                 $confhash{$itemid}{'order'} = $idx;
13063:                 unless ($changes{$itemid}) {
13064:                     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
13065:                         if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
13066:                             if ($domconfig{'ipaccess'}{$itemid}{'order'} ne $idx) {
13067:                                 $changes{$itemid} = 1;
13068:                             }
13069:                         }
13070:                     }
13071:                 }
13072:                 $idx ++;
13073:             }
13074:         }
13075:     }
13076:     if (keys(%changes)) {
13077:         my %defaultshash = (
13078:                               ipaccess => \%confhash,
13079:                            );
13080:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
13081:                                                  $dom);
13082:         if ($putresult eq 'ok') {
13083:             my $cachetime = 1800;
13084:             &Apache::lonnet::do_cache_new('ipaccess',$dom,\%confhash,$cachetime);
13085:             if (ref($lastactref) eq 'HASH') {
13086:                 $lastactref->{'ipaccess'} = 1;
13087:             }
13088:             $resulttext = &mt('Changes made:').'<ul>';
13089:             my %bynum;
13090:             foreach my $itemid (sort(keys(%changes))) {
13091:                 if (ref($confhash{$itemid}) eq 'HASH') {
13092:                     my $position = $confhash{$itemid}{'order'};
13093:                     if ($position =~ /^\d+$/) {
13094:                         $bynum{$position} = $itemid;
13095:                     }
13096:                 }
13097:             }
13098:             if (keys(%deletions)) {
13099:                 foreach my $itemid (sort { $a <=> $b } keys(%deletions)) {
13100:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
13101:                 }
13102:             }
13103:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
13104:                 my $itemid = $bynum{$pos};
13105:                 if (ref($confhash{$itemid}) eq 'HASH') {
13106:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'name'}.'</b><ul>';
13107:                     my $position = $pos + 1;
13108:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
13109:                     if ($confhash{$itemid}{'ip'} eq '') {
13110:                         $resulttext .= '<li>'.&mt('No IP Range(s) set').'</li>';
13111:                     } else {
13112:                         $resulttext .= '<li>'.&mt('IP Range(s): [_1]',$confhash{$itemid}{'ip'}).'</li>';
13113:                     }
13114:                     if (keys(%{$confhash{$itemid}{'commblocks'}})) {
13115:                         $resulttext .= '<li>'.&mt('Functionality Blocked: [_1]',
13116:                                                   join(', ', map { $types->{$_}; } sort(keys(%{$confhash{$itemid}{'commblocks'}})))).
13117:                                        '</li>';
13118:                     } else {
13119:                         $resulttext .= '<li>'.&mt('No functionality blocked').'</li>';
13120:                     }
13121:                     if (keys(%{$confhash{$itemid}{'courses'}})) {
13122:                         my @courses;
13123:                         foreach my $cid (sort(keys(%{$confhash{$itemid}{'courses'}}))) {
13124:                             my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1}); 
13125:                             push(@courses,$courseinfo{'description'}.' ('.$cid.')');
13126:                         }
13127:                         $resulttext .= '<li>'.&mt('Courses/Communities allowed').':<ul><li>'.
13128:                                              join('</li><li>',@courses).'</li></ul>';
13129:                     } else {
13130:                         $resulttext .= '<li>'.&mt('No courses allowed').'</li>';
13131:                     }
13132:                     $resulttext .= '</ul></li>';
13133:                 }
13134:             }
13135:             $resulttext .= '</ul>';
13136:         } else {
13137:             $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
13138:         }
13139:     } else {
13140:         $resulttext = &mt('No changes made');
13141:     }
13142:     if ($errors) {
13143:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
13144:                        $errors.'</ul></p>';
13145:     }
13146:     return $resulttext;
13147: }
13148: 
13149: sub get_ipaccess_id {
13150:     my ($domain,$location) = @_;
13151:     # get lock on ipaccess db
13152:     my $lockhash = {
13153:                       lock => $env{'user.name'}.
13154:                               ':'.$env{'user.domain'},
13155:                    };
13156:     my $tries = 0;
13157:     my $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
13158:     my ($id,$error);
13159: 
13160:     while (($gotlock ne 'ok') && ($tries<10)) {
13161:         $tries ++;
13162:         sleep (0.1);
13163:         $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
13164:     }
13165:     if ($gotlock eq 'ok') {
13166:         my %currids = &Apache::lonnet::dump_dom('ipaccess',$domain);
13167:         if ($currids{'lock'}) {
13168:             delete($currids{'lock'});
13169:             if (keys(%currids)) {
13170:                 my @curr = sort { $a <=> $b } keys(%currids);
13171:                 if ($curr[-1] =~ /^\d+$/) {
13172:                     $id = 1 + $curr[-1];
13173:                 }
13174:             } else {
13175:                 $id = 1;
13176:             }
13177:             if ($id) {
13178:                 unless (&Apache::lonnet::newput_dom('ipaccess',{ $id => $location },$domain) eq 'ok') {
13179:                     $error = 'nostore';
13180:                 }
13181:             } else {
13182:                 $error = 'nonumber';
13183:             }
13184:         }
13185:         my $dellockoutcome = &Apache::lonnet::del_dom('ipaccess',['lock'],$domain);
13186:     } else {
13187:         $error = 'nolock';
13188:     }
13189:     return ($id,$error);
13190: }
13191: 
13192: sub modify_rolecolors {
13193:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
13194:     my ($resulttext,%rolehash);
13195:     $rolehash{'rolecolors'} = {};
13196:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
13197:         if ($domconfig{'rolecolors'} eq '') {
13198:             $domconfig{'rolecolors'} = {};
13199:         }
13200:     }
13201:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
13202:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
13203:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
13204:                                              $dom);
13205:     if ($putresult eq 'ok') {
13206:         if (keys(%changes) > 0) {
13207:             &Apache::loncommon::devalidate_domconfig_cache($dom);
13208:             if (ref($lastactref) eq 'HASH') {
13209:                 $lastactref->{'domainconfig'} = 1;
13210:             }
13211:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
13212:                                              $rolehash{'rolecolors'});
13213:         } else {
13214:             $resulttext = &mt('No changes made to default color schemes');
13215:         }
13216:     } else {
13217:         $resulttext = '<span class="LC_error">'.
13218: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
13219:     }
13220:     if ($errors) {
13221:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
13222:                        $errors.'</ul>';
13223:     }
13224:     return $resulttext;
13225: }
13226: 
13227: sub modify_colors {
13228:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
13229:     my (%changes,%choices);
13230:     my @bgs;
13231:     my @links = ('link','alink','vlink');
13232:     my @logintext;
13233:     my @images;
13234:     my $servadm = $r->dir_config('lonAdmEMail');
13235:     my $errors;
13236:     my %defaults;
13237:     foreach my $role (@{$roles}) {
13238:         if ($role eq 'login') {
13239:             %choices = &login_choices();
13240:             @logintext = ('textcol','bgcol');
13241:         } else {
13242:             %choices = &color_font_choices();
13243:         }
13244:         if ($role eq 'login') {
13245:             @images = ('img','logo','domlogo','login');
13246:             @bgs = ('pgbg','mainbg','sidebg');
13247:         } else {
13248:             @images = ('img');
13249:             @bgs = ('pgbg','tabbg','sidebg');
13250:         }
13251:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
13252:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
13253:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
13254:         }
13255:         if ($role eq 'login') {
13256:             foreach my $item (@logintext) {
13257:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13258:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13259:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13260:                 }
13261:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
13262:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13263:                 }
13264:             }
13265:         } else {
13266:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
13267:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
13268:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
13269:             }
13270:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
13271:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
13272:             }
13273:         }
13274:         foreach my $item (@bgs) {
13275:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13276:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13277:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13278:             }
13279:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
13280:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13281:             }
13282:         }
13283:         foreach my $item (@links) {
13284:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13285:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13286:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13287:             }
13288:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
13289:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13290:             }
13291:         }
13292:         my ($configuserok,$author_ok,$switchserver) = 
13293:             &config_check($dom,$confname,$servadm);
13294:         my ($width,$height) = &thumb_dimensions();
13295:         if (ref($domconfig->{$role}) ne 'HASH') {
13296:             $domconfig->{$role} = {};
13297:         }
13298:         foreach my $img (@images) {
13299:             if ($role eq 'login') {
13300:                 if (($img eq 'img') || ($img eq 'logo')) {  
13301:                     if (defined($env{'form.login_showlogo_'.$img})) {
13302:                         $confhash->{$role}{'showlogo'}{$img} = 1;
13303:                     } else { 
13304:                         $confhash->{$role}{'showlogo'}{$img} = 0;
13305:                     }
13306:                 }
13307:                 if ($env{'form.login_alt_'.$img} ne '') {
13308:                     $confhash->{$role}{'alttext'}{$img} = $env{'form.login_alt_'.$img};
13309:                 }
13310:             }
13311: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
13312: 		 && !defined($domconfig->{$role}{$img})
13313: 		 && !$env{'form.'.$role.'_del_'.$img}
13314: 		 && $env{'form.'.$role.'_import_'.$img}) {
13315: 		# import the old configured image from the .tab setting
13316: 		# if they haven't provided a new one 
13317: 		$domconfig->{$role}{$img} = 
13318: 		    $env{'form.'.$role.'_import_'.$img};
13319: 	    }
13320:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
13321:                 my $error;
13322:                 if ($configuserok eq 'ok') {
13323:                     if ($switchserver) {
13324:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
13325:                     } else {
13326:                         if ($author_ok eq 'ok') {
13327:                             my ($result,$logourl) = 
13328:                                 &publishlogo($r,'upload',$role.'_'.$img,
13329:                                            $dom,$confname,$img,$width,$height);
13330:                             if ($result eq 'ok') {
13331:                                 $confhash->{$role}{$img} = $logourl;
13332:                                 $changes{$role}{'images'}{$img} = 1;
13333:                             } else {
13334:                                 $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);
13335:                             }
13336:                         } else {
13337:                             $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);
13338:                         }
13339:                     }
13340:                 } else {
13341:                     $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);
13342:                 }
13343:                 if ($error) {
13344:                     &Apache::lonnet::logthis($error);
13345:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13346:                 }
13347:             } elsif ($domconfig->{$role}{$img} ne '') {
13348:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
13349:                     my $error;
13350:                     if ($configuserok eq 'ok') {
13351: # is confname an author?
13352:                         if ($switchserver eq '') {
13353:                             if ($author_ok eq 'ok') {
13354:                                 my ($result,$logourl) = 
13355:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
13356:                                             $dom,$confname,$img,$width,$height);
13357:                                 if ($result eq 'ok') {
13358:                                     $confhash->{$role}{$img} = $logourl;
13359: 				    $changes{$role}{'images'}{$img} = 1;
13360:                                 }
13361:                             }
13362:                         }
13363:                     }
13364:                 }
13365:             }
13366:         }
13367:         if (ref($domconfig) eq 'HASH') {
13368:             if (ref($domconfig->{$role}) eq 'HASH') {
13369:                 foreach my $img (@images) {
13370:                     if ($domconfig->{$role}{$img} ne '') {
13371:                         if ($env{'form.'.$role.'_del_'.$img}) {
13372:                             $confhash->{$role}{$img} = '';
13373:                             $changes{$role}{'images'}{$img} = 1;
13374:                         } else {
13375:                             if ($confhash->{$role}{$img} eq '') {
13376:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
13377:                             }
13378:                         }
13379:                     } else {
13380:                         if ($env{'form.'.$role.'_del_'.$img}) {
13381:                             $confhash->{$role}{$img} = '';
13382:                             $changes{$role}{'images'}{$img} = 1;
13383:                         } 
13384:                     }
13385:                     if ($role eq 'login') {
13386:                         if (($img eq 'logo') || ($img eq 'img')) {
13387:                             if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
13388:                                 if ($confhash->{$role}{'showlogo'}{$img} ne 
13389:                                     $domconfig->{$role}{'showlogo'}{$img}) {
13390:                                     $changes{$role}{'showlogo'}{$img} = 1; 
13391:                                 }
13392:                             } else {
13393:                                 if ($confhash->{$role}{'showlogo'}{$img} == 0) {
13394:                                     $changes{$role}{'showlogo'}{$img} = 1;
13395:                                 }
13396:                             }
13397:                         }
13398:                         if ($img ne 'login') {
13399:                             if (ref($domconfig->{$role}{'alttext'}) eq 'HASH') {
13400:                                 if ($confhash->{$role}{'alttext'}{$img} ne
13401:                                     $domconfig->{$role}{'alttext'}{$img}) {
13402:                                     $changes{$role}{'alttext'}{$img} = 1;
13403:                                 }
13404:                             } else {
13405:                                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
13406:                                     $changes{$role}{'alttext'}{$img} = 1;
13407:                                 }
13408:                             }
13409:                         }
13410:                     }
13411:                 }
13412:                 if ($domconfig->{$role}{'font'} ne '') {
13413:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
13414:                         $changes{$role}{'font'} = 1;
13415:                     }
13416:                 } else {
13417:                     if ($confhash->{$role}{'font'}) {
13418:                         $changes{$role}{'font'} = 1;
13419:                     }
13420:                 }
13421:                 if ($role ne 'login') {
13422:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
13423:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
13424:                             $changes{$role}{'fontmenu'} = 1;
13425:                         }
13426:                     } else {
13427:                         if ($confhash->{$role}{'fontmenu'}) {
13428:                             $changes{$role}{'fontmenu'} = 1;
13429:                         }
13430:                     }
13431:                 }
13432:                 foreach my $item (@bgs) {
13433:                     if ($domconfig->{$role}{$item} ne '') {
13434:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13435:                             $changes{$role}{'bgs'}{$item} = 1;
13436:                         } 
13437:                     } else {
13438:                         if ($confhash->{$role}{$item}) {
13439:                             $changes{$role}{'bgs'}{$item} = 1;
13440:                         }
13441:                     }
13442:                 }
13443:                 foreach my $item (@links) {
13444:                     if ($domconfig->{$role}{$item} ne '') {
13445:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13446:                             $changes{$role}{'links'}{$item} = 1;
13447:                         }
13448:                     } else {
13449:                         if ($confhash->{$role}{$item}) {
13450:                             $changes{$role}{'links'}{$item} = 1;
13451:                         }
13452:                     }
13453:                 }
13454:                 foreach my $item (@logintext) {
13455:                     if ($domconfig->{$role}{$item} ne '') {
13456:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13457:                             $changes{$role}{'logintext'}{$item} = 1;
13458:                         }
13459:                     } else {
13460:                         if ($confhash->{$role}{$item}) {
13461:                             $changes{$role}{'logintext'}{$item} = 1;
13462:                         }
13463:                     }
13464:                 }
13465:             } else {
13466:                 &default_change_checker($role,\@images,\@links,\@bgs,
13467:                                         \@logintext,$confhash,\%changes); 
13468:             }
13469:         } else {
13470:             &default_change_checker($role,\@images,\@links,\@bgs,
13471:                                     \@logintext,$confhash,\%changes); 
13472:         }
13473:     }
13474:     return ($errors,%changes);
13475: }
13476: 
13477: sub config_check {
13478:     my ($dom,$confname,$servadm) = @_;
13479:     my ($configuserok,$author_ok,$switchserver,%currroles);
13480:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
13481:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
13482:                                                    $confname,$servadm);
13483:     if ($configuserok eq 'ok') {
13484:         $switchserver = &check_switchserver($dom,$confname);
13485:         if ($switchserver eq '') {
13486:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
13487:         }
13488:     }
13489:     return ($configuserok,$author_ok,$switchserver);
13490: }
13491: 
13492: sub default_change_checker {
13493:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
13494:     foreach my $item (@{$links}) {
13495:         if ($confhash->{$role}{$item}) {
13496:             $changes->{$role}{'links'}{$item} = 1;
13497:         }
13498:     }
13499:     foreach my $item (@{$bgs}) {
13500:         if ($confhash->{$role}{$item}) {
13501:             $changes->{$role}{'bgs'}{$item} = 1;
13502:         }
13503:     }
13504:     foreach my $item (@{$logintext}) {
13505:         if ($confhash->{$role}{$item}) {
13506:             $changes->{$role}{'logintext'}{$item} = 1;
13507:         }
13508:     }
13509:     foreach my $img (@{$images}) {
13510:         if ($env{'form.'.$role.'_del_'.$img}) {
13511:             $confhash->{$role}{$img} = '';
13512:             $changes->{$role}{'images'}{$img} = 1;
13513:         }
13514:         if ($role eq 'login') {
13515:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
13516:                 $changes->{$role}{'showlogo'}{$img} = 1;
13517:             }
13518:             if (ref($confhash->{$role}{'alttext'}) eq 'HASH') {
13519:                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
13520:                     $changes->{$role}{'alttext'}{$img} = 1;
13521:                 }
13522:             }
13523:         }
13524:     }
13525:     if ($confhash->{$role}{'font'}) {
13526:         $changes->{$role}{'font'} = 1;
13527:     }
13528: }
13529: 
13530: sub display_colorchgs {
13531:     my ($dom,$changes,$roles,$confhash) = @_;
13532:     my (%choices,$resulttext);
13533:     if (!grep(/^login$/,@{$roles})) {
13534:         $resulttext = &mt('Changes made:').'<br />';
13535:     }
13536:     foreach my $role (@{$roles}) {
13537:         if ($role eq 'login') {
13538:             %choices = &login_choices();
13539:         } else {
13540:             %choices = &color_font_choices();
13541:         }
13542:         if (ref($changes->{$role}) eq 'HASH') {
13543:             if ($role ne 'login') {
13544:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
13545:             }
13546:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
13547:                 if ($role ne 'login') {
13548:                     $resulttext .= '<ul>';
13549:                 }
13550:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
13551:                     if ($role ne 'login') {
13552:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
13553:                     }
13554:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
13555:                         if (($role eq 'login') && ($key eq 'showlogo')) {
13556:                             if ($confhash->{$role}{$key}{$item}) {
13557:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
13558:                             } else {
13559:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
13560:                             }
13561:                         } elsif (($role eq 'login') && ($key eq 'alttext')) {
13562:                             if ($confhash->{$role}{$key}{$item} ne '') {
13563:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} set to [_1].",
13564:                                                $confhash->{$role}{$key}{$item}).'</li>';
13565:                             } else {
13566:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} deleted.").'</li>';
13567:                             }
13568:                         } elsif ($confhash->{$role}{$item} eq '') {
13569:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
13570:                         } else {
13571:                             my $newitem = $confhash->{$role}{$item};
13572:                             if ($key eq 'images') {
13573:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" style="vertical-align: bottom" />';
13574:                             }
13575:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
13576:                         }
13577:                     }
13578:                     if ($role ne 'login') {
13579:                         $resulttext .= '</ul></li>';
13580:                     }
13581:                 } else {
13582:                     if ($confhash->{$role}{$key} eq '') {
13583:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
13584:                     } else {
13585:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
13586:                     }
13587:                 }
13588:                 if ($role ne 'login') {
13589:                     $resulttext .= '</ul>';
13590:                 }
13591:             }
13592:         }
13593:     }
13594:     return $resulttext;
13595: }
13596: 
13597: sub thumb_dimensions {
13598:     return ('200','50');
13599: }
13600: 
13601: sub check_dimensions {
13602:     my ($inputfile) = @_;
13603:     my ($fullwidth,$fullheight);
13604:     if ($inputfile =~ m|^[/\w.\-]+$|) {
13605:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
13606:             my $imageinfo = <PIPE>;
13607:             if (!close(PIPE)) {
13608:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
13609:             }
13610:             chomp($imageinfo);
13611:             my ($fullsize) = 
13612:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
13613:             if ($fullsize) {
13614:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
13615:             }
13616:         }
13617:     }
13618:     return ($fullwidth,$fullheight);
13619: }
13620: 
13621: sub check_configuser {
13622:     my ($uhome,$dom,$confname,$servadm) = @_;
13623:     my ($configuserok,%currroles);
13624:     if ($uhome eq 'no_host') {
13625:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
13626:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
13627:         $configuserok = 
13628:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
13629:                              $configpass,'','','','','',undef,$servadm);
13630:     } else {
13631:         $configuserok = 'ok';
13632:         %currroles = 
13633:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
13634:     }
13635:     return ($configuserok,%currroles);
13636: }
13637: 
13638: sub check_authorstatus {
13639:     my ($dom,$confname,%currroles) = @_;
13640:     my $author_ok;
13641:     if (!$currroles{':'.$dom.':au'}) {
13642:         my $start = time;
13643:         my $end = 0;
13644:         $author_ok = 
13645:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
13646:                                         'au',$end,$start,'','','domconfig');
13647:     } else {
13648:         $author_ok = 'ok';
13649:     }
13650:     return $author_ok;
13651: }
13652: 
13653: sub publishlogo {
13654:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
13655:     my ($output,$fname,$logourl,$madethumb);
13656:     if ($action eq 'upload') {
13657:         $fname=$env{'form.'.$formname.'.filename'};
13658:         chop($env{'form.'.$formname});
13659:     } else {
13660:         ($fname) = ($formname =~ /([^\/]+)$/);
13661:     }
13662:     if ($savefileas ne '') {
13663:         $fname = $savefileas;
13664:     }
13665:     $fname=&Apache::lonnet::clean_filename($fname);
13666: # See if there is anything left
13667:     unless ($fname) { return ('error: no uploaded file'); }
13668:     $fname="$subdir/$fname";
13669:     my $docroot=$r->dir_config('lonDocRoot');
13670:     my $filepath="$docroot/priv";
13671:     my $relpath = "$dom/$confname";
13672:     my ($fnamepath,$file,$fetchthumb);
13673:     $file=$fname;
13674:     if ($fname=~m|/|) {
13675:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
13676:     }
13677:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
13678:     my $count;
13679:     for ($count=5;$count<=$#parts;$count++) {
13680:         $filepath.="/$parts[$count]";
13681:         if ((-e $filepath)!=1) {
13682:             mkdir($filepath,02770);
13683:         }
13684:     }
13685:     # Check for bad extension and disallow upload
13686:     if ($file=~/\.(\w+)$/ &&
13687:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
13688:         $output = 
13689:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
13690:     } elsif ($file=~/\.(\w+)$/ &&
13691:         !defined(&Apache::loncommon::fileembstyle($1))) {
13692:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
13693:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
13694:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
13695:     } elsif (-d "$filepath/$file") {
13696:         $output = &mt('Filename is a directory name - rename the file and re-upload');
13697:     } else {
13698:         my $source = $filepath.'/'.$file;
13699:         my $logfile;
13700:         if (!open($logfile,">>",$source.'.log')) {
13701:             return (&mt('No write permission to Authoring Space'));
13702:         }
13703:         print $logfile
13704: "\n================= Publish ".localtime()." ================\n".
13705: $env{'user.name'}.':'.$env{'user.domain'}."\n";
13706: # Save the file
13707:         if (!open(FH,">",$source)) {
13708:             &Apache::lonnet::logthis('Failed to create '.$source);
13709:             return (&mt('Failed to create file'));
13710:         }
13711:         if ($action eq 'upload') {
13712:             if (!print FH ($env{'form.'.$formname})) {
13713:                 &Apache::lonnet::logthis('Failed to write to '.$source);
13714:                 return (&mt('Failed to write file'));
13715:             }
13716:         } else {
13717:             my $original = &Apache::lonnet::filelocation('',$formname);
13718:             if(!copy($original,$source)) {
13719:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
13720:                 return (&mt('Failed to write file'));
13721:             }
13722:         }
13723:         close(FH);
13724:         chmod(0660, $source); # Permissions to rw-rw---.
13725: 
13726:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
13727:         my $copyfile=$targetdir.'/'.$file;
13728: 
13729:         my @parts=split(/\//,$targetdir);
13730:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
13731:         for (my $count=5;$count<=$#parts;$count++) {
13732:             $path.="/$parts[$count]";
13733:             if (!-e $path) {
13734:                 print $logfile "\nCreating directory ".$path;
13735:                 mkdir($path,02770);
13736:             }
13737:         }
13738:         my $versionresult;
13739:         if (-e $copyfile) {
13740:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
13741:         } else {
13742:             $versionresult = 'ok';
13743:         }
13744:         if ($versionresult eq 'ok') {
13745:             if (copy($source,$copyfile)) {
13746:                 print $logfile "\nCopied original source to ".$copyfile."\n";
13747:                 $output = 'ok';
13748:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
13749:                 push(@{$modified_urls},[$copyfile,$source]);
13750:                 my $metaoutput = 
13751:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
13752:                 unless ($registered_cleanup) {
13753:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
13754:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
13755:                     $registered_cleanup=1;
13756:                 }
13757:             } else {
13758:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
13759:                 $output = &mt('Failed to copy file to RES space').", $!";
13760:             }
13761:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
13762:                 my $inputfile = $filepath.'/'.$file;
13763:                 my $outfile = $filepath.'/'.'tn-'.$file;
13764:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
13765:                 if ($fullwidth ne '' && $fullheight ne '') { 
13766:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
13767:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
13768:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
13769:                         system({$args[0]} @args);
13770:                         chmod(0660, $filepath.'/tn-'.$file);
13771:                         if (-e $outfile) {
13772:                             my $copyfile=$targetdir.'/tn-'.$file;
13773:                             if (copy($outfile,$copyfile)) {
13774:                                 print $logfile "\nCopied source to ".$copyfile."\n";
13775:                                 my $thumb_metaoutput = 
13776:                                     &write_metadata($dom,$confname,$formname,
13777:                                                     $targetdir,'tn-'.$file,$logfile);
13778:                                 push(@{$modified_urls},[$copyfile,$outfile]);
13779:                                 unless ($registered_cleanup) {
13780:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
13781:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
13782:                                     $registered_cleanup=1;
13783:                                 }
13784:                                 $madethumb = 1;
13785:                             } else {
13786:                                 print $logfile "\nUnable to write ".$copyfile.
13787:                                                ':'.$!."\n";
13788:                             }
13789:                         }
13790:                     }
13791:                 }
13792:             }
13793:         } else {
13794:             $output = $versionresult;
13795:         }
13796:     }
13797:     return ($output,$logourl,$madethumb);
13798: }
13799: 
13800: sub logo_versioning {
13801:     my ($targetdir,$file,$logfile) = @_;
13802:     my $target = $targetdir.'/'.$file;
13803:     my ($maxversion,$fn,$extn,$output);
13804:     $maxversion = 0;
13805:     if ($file =~ /^(.+)\.(\w+)$/) {
13806:         $fn=$1;
13807:         $extn=$2;
13808:     }
13809:     opendir(DIR,$targetdir);
13810:     while (my $filename=readdir(DIR)) {
13811:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
13812:             $maxversion=($1>$maxversion)?$1:$maxversion;
13813:         }
13814:     }
13815:     $maxversion++;
13816:     print $logfile "\nCreating old version ".$maxversion."\n";
13817:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
13818:     if (copy($target,$copyfile)) {
13819:         print $logfile "Copied old target to ".$copyfile."\n";
13820:         $copyfile=$copyfile.'.meta';
13821:         if (copy($target.'.meta',$copyfile)) {
13822:             print $logfile "Copied old target metadata to ".$copyfile."\n";
13823:             $output = 'ok';
13824:         } else {
13825:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
13826:             $output = &mt('Failed to copy old meta').", $!, ";
13827:         }
13828:     } else {
13829:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
13830:         $output = &mt('Failed to copy old target').", $!, ";
13831:     }
13832:     return $output;
13833: }
13834: 
13835: sub write_metadata {
13836:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
13837:     my (%metadatafields,%metadatakeys,$output);
13838:     $metadatafields{'title'}=$formname;
13839:     $metadatafields{'creationdate'}=time;
13840:     $metadatafields{'lastrevisiondate'}=time;
13841:     $metadatafields{'copyright'}='public';
13842:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
13843:                                          $env{'user.domain'};
13844:     $metadatafields{'authorspace'}=$confname.':'.$dom;
13845:     $metadatafields{'domain'}=$dom;
13846:     {
13847:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
13848:         my $mfh;
13849:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
13850:             foreach (sort(keys(%metadatafields))) {
13851:                 unless ($_=~/\./) {
13852:                     my $unikey=$_;
13853:                     $unikey=~/^([A-Za-z]+)/;
13854:                     my $tag=$1;
13855:                     $tag=~tr/A-Z/a-z/;
13856:                     print $mfh "\n\<$tag";
13857:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
13858:                         my $value=$metadatafields{$unikey.'.'.$_};
13859:                         $value=~s/\"/\'\'/g;
13860:                         print $mfh ' '.$_.'="'.$value.'"';
13861:                     }
13862:                     print $mfh '>'.
13863:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
13864:                             .'</'.$tag.'>';
13865:                 }
13866:             }
13867:             $output = 'ok';
13868:             print $logfile "\nWrote metadata";
13869:             close($mfh);
13870:         } else {
13871:             print $logfile "\nFailed to open metadata file";
13872:             $output = &mt('Could not write metadata');
13873:         }
13874:     }
13875:     return $output;
13876: }
13877: 
13878: sub notifysubscribed {
13879:     foreach my $targetsource (@{$modified_urls}){
13880:         next unless (ref($targetsource) eq 'ARRAY');
13881:         my ($target,$source)=@{$targetsource};
13882:         if ($source ne '') {
13883:             if (open(my $logfh,">>",$source.'.log')) {
13884:                 print $logfh "\nCleanup phase: Notifications\n";
13885:                 my @subscribed=&subscribed_hosts($target);
13886:                 foreach my $subhost (@subscribed) {
13887:                     print $logfh "\nNotifying host ".$subhost.':';
13888:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
13889:                     print $logfh $reply;
13890:                 }
13891:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
13892:                 foreach my $subhost (@subscribedmeta) {
13893:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
13894:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
13895:                                                         $subhost);
13896:                     print $logfh $reply;
13897:                 }
13898:                 print $logfh "\n============ Done ============\n";
13899:                 close($logfh);
13900:             }
13901:         }
13902:     }
13903:     return OK;
13904: }
13905: 
13906: sub subscribed_hosts {
13907:     my ($target) = @_;
13908:     my @subscribed;
13909:     if (open(my $fh,"<","$target.subscription")) {
13910:         while (my $subline=<$fh>) {
13911:             if ($subline =~ /^($match_lonid):/) {
13912:                 my $host = $1;
13913:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
13914:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
13915:                         push(@subscribed,$host);
13916:                     }
13917:                 }
13918:             }
13919:         }
13920:     }
13921:     return @subscribed;
13922: }
13923: 
13924: sub check_switchserver {
13925:     my ($dom,$confname) = @_;
13926:     my ($allowed,$switchserver);
13927:     my $home = &Apache::lonnet::homeserver($confname,$dom);
13928:     if ($home eq 'no_host') {
13929:         $home = &Apache::lonnet::domain($dom,'primary');
13930:     }
13931:     my @ids=&Apache::lonnet::current_machine_ids();
13932:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
13933:     if (!$allowed) {
13934: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
13935:     }
13936:     return $switchserver;
13937: }
13938: 
13939: sub modify_quotas {
13940:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
13941:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
13942:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
13943:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
13944:         $validationfieldsref);
13945:     if ($action eq 'quotas') {
13946:         $context = 'tools'; 
13947:     } else {
13948:         $context = $action;
13949:     }
13950:     if ($context eq 'requestcourses') {
13951:         @usertools = ('official','unofficial','community','textbook','placement','lti');
13952:         @options =('norequest','approval','validate','autolimit');
13953:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
13954:         %titles = &courserequest_titles();
13955:         $toolregexp = join('|',@usertools);
13956:         %conditions = &courserequest_conditions();
13957:         $confname = $dom.'-domainconfig';
13958:         my $servadm = $r->dir_config('lonAdmEMail');
13959:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
13960:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
13961:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
13962:     } elsif ($context eq 'requestauthor') {
13963:         @usertools = ('author');
13964:         %titles = &authorrequest_titles();
13965:     } else {
13966:         @usertools = ('aboutme','blog','webdav','portfolio');
13967:         %titles = &tool_titles();
13968:     }
13969:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13970:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13971:     foreach my $key (keys(%env)) {
13972:         if ($context eq 'requestcourses') {
13973:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
13974:                 my $item = $1;
13975:                 my $type = $2;
13976:                 if ($type =~ /^limit_(.+)/) {
13977:                     $limithash{$item}{$1} = $env{$key};
13978:                 } else {
13979:                     $confhash{$item}{$type} = $env{$key};
13980:                 }
13981:             }
13982:         } elsif ($context eq 'requestauthor') {
13983:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
13984:                 $confhash{$1} = $env{$key};
13985:             }
13986:         } else {
13987:             if ($key =~ /^form\.quota_(.+)$/) {
13988:                 $confhash{'defaultquota'}{$1} = $env{$key};
13989:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
13990:                 $confhash{'authorquota'}{$1} = $env{$key};
13991:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
13992:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
13993:             }
13994:         }
13995:     }
13996:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
13997:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
13998:         @approvalnotify = sort(@approvalnotify);
13999:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
14000:         my @crstypes = ('official','unofficial','community','textbook','placement','lti');
14001:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
14002:         foreach my $type (@hasuniquecode) {
14003:             if (grep(/^\Q$type\E$/,@crstypes)) {
14004:                 $confhash{'uniquecode'}{$type} = 1;
14005:             }
14006:         }
14007:         my (%newbook,%allpos);
14008:         if ($context eq 'requestcourses') {
14009:             foreach my $type ('textbooks','templates') {
14010:                 @{$allpos{$type}} = (); 
14011:                 my $invalid;
14012:                 if ($type eq 'textbooks') {
14013:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
14014:                 } else {
14015:                     $invalid = &mt('Invalid LON-CAPA course for template');
14016:                 }
14017:                 if ($env{'form.'.$type.'_addbook'}) {
14018:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
14019:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
14020:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
14021:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
14022:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
14023:                         } else {
14024:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
14025:                             my $position = $env{'form.'.$type.'_addbook_pos'};
14026:                             $position =~ s/\D+//g;
14027:                             if ($position ne '') {
14028:                                 $allpos{$type}[$position] = $newbook{$type};
14029:                             }
14030:                         }
14031:                     } else {
14032:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
14033:                     }
14034:                 }
14035:             } 
14036:         }
14037:         if (ref($domconfig{$action}) eq 'HASH') {
14038:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
14039:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
14040:                     $changes{'notify'}{'approval'} = 1;
14041:                 }
14042:             } else {
14043:                 if ($confhash{'notify'}{'approval'}) {
14044:                     $changes{'notify'}{'approval'} = 1;
14045:                 }
14046:             }
14047:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
14048:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
14049:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
14050:                         unless ($confhash{'uniquecode'}{$crstype}) {
14051:                             $changes{'uniquecode'} = 1;
14052:                         }
14053:                     }
14054:                     unless ($changes{'uniquecode'}) {
14055:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
14056:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
14057:                                 $changes{'uniquecode'} = 1;
14058:                             }
14059:                         }
14060:                     }
14061:                } else {
14062:                    $changes{'uniquecode'} = 1;
14063:                }
14064:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
14065:                 $changes{'uniquecode'} = 1;
14066:             }
14067:             if ($context eq 'requestcourses') {
14068:                 foreach my $type ('textbooks','templates') {
14069:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
14070:                         my %deletions;
14071:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
14072:                         if (@todelete) {
14073:                             map { $deletions{$_} = 1; } @todelete;
14074:                         }
14075:                         my %imgdeletions;
14076:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
14077:                         if (@todeleteimages) {
14078:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
14079:                         }
14080:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
14081:                         for (my $i=0; $i<=$maxnum; $i++) {
14082:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
14083:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
14084:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
14085:                                 if ($deletions{$key}) {
14086:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
14087:                                         #FIXME need to obsolete item in RES space
14088:                                     }
14089:                                     next;
14090:                                 } else {
14091:                                     my $newpos = $env{'form.'.$itemid};
14092:                                     $newpos =~ s/\D+//g;
14093:                                     foreach my $item ('subject','title','publisher','author') {
14094:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
14095:                                                  ($type eq 'templates'));
14096:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
14097:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
14098:                                             $changes{$type}{$key} = 1;
14099:                                         }
14100:                                     }
14101:                                     $allpos{$type}[$newpos] = $key;
14102:                                 }
14103:                                 if ($imgdeletions{$key}) {
14104:                                     $changes{$type}{$key} = 1;
14105:                                     #FIXME need to obsolete item in RES space
14106:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
14107:                                     my ($cdom,$cnum) = split(/_/,$key);
14108:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
14109:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
14110:                                     } else {
14111:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
14112:                                                                                       $cdom,$cnum,$type,$configuserok,
14113:                                                                                       $switchserver,$author_ok);
14114:                                         if ($imgurl) {
14115:                                             $confhash{$type}{$key}{'image'} = $imgurl;
14116:                                             $changes{$type}{$key} = 1; 
14117:                                         }
14118:                                         if ($error) {
14119:                                             &Apache::lonnet::logthis($error);
14120:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14121:                                         }
14122:                                     }
14123:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
14124:                                     $confhash{$type}{$key}{'image'} = 
14125:                                         $domconfig{$action}{$type}{$key}{'image'};
14126:                                 }
14127:                             }
14128:                         }
14129:                     }
14130:                 }
14131:             }
14132:         } else {
14133:             if ($confhash{'notify'}{'approval'}) {
14134:                 $changes{'notify'}{'approval'} = 1;
14135:             }
14136:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
14137:                 $changes{'uniquecode'} = 1;
14138:             }
14139:         }
14140:         if ($context eq 'requestcourses') {
14141:             foreach my $type ('textbooks','templates') {
14142:                 if ($newbook{$type}) {
14143:                     $changes{$type}{$newbook{$type}} = 1;
14144:                     foreach my $item ('subject','title','publisher','author') {
14145:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
14146:                                  ($type eq 'template'));
14147:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
14148:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
14149:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
14150:                         }
14151:                     }
14152:                     if ($type eq 'textbooks') {
14153:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
14154:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
14155:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
14156:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
14157:                             } else {
14158:                                 my ($imageurl,$error) =
14159:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
14160:                                                             $configuserok,$switchserver,$author_ok);
14161:                                 if ($imageurl) {
14162:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
14163:                                 }
14164:                                 if ($error) {
14165:                                     &Apache::lonnet::logthis($error);
14166:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14167:                                 }
14168:                             }
14169:                         }
14170:                     }
14171:                 }
14172:                 if (@{$allpos{$type}} > 0) {
14173:                     my $idx = 0;
14174:                     foreach my $item (@{$allpos{$type}}) {
14175:                         if ($item ne '') {
14176:                             $confhash{$type}{$item}{'order'} = $idx;
14177:                             if (ref($domconfig{$action}) eq 'HASH') {
14178:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
14179:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
14180:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
14181:                                             $changes{$type}{$item} = 1;
14182:                                         }
14183:                                     }
14184:                                 }
14185:                             }
14186:                             $idx ++;
14187:                         }
14188:                     }
14189:                 }
14190:             }
14191:             if (ref($validationitemsref) eq 'ARRAY') {
14192:                 foreach my $item (@{$validationitemsref}) {
14193:                     if ($item eq 'fields') {
14194:                         my @changed;
14195:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
14196:                         if (@{$confhash{'validation'}{$item}} > 0) {
14197:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
14198:                         }
14199:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14200:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14201:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
14202:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
14203:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
14204:                                 } else {
14205:                                     @changed = @{$confhash{'validation'}{$item}};
14206:                                 }
14207:                             } else {
14208:                                 @changed = @{$confhash{'validation'}{$item}};
14209:                             }
14210:                         } else {
14211:                             @changed = @{$confhash{'validation'}{$item}};
14212:                         }
14213:                         if (@changed) {
14214:                             if ($confhash{'validation'}{$item}) {
14215:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
14216:                             } else {
14217:                                 $changes{'validation'}{$item} = &mt('None');
14218:                             }
14219:                         }
14220:                     } else {
14221:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
14222:                         if ($item eq 'markup') {
14223:                             if ($env{'form.requestcourses_validation_'.$item}) {
14224:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
14225:                             }
14226:                         }
14227:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14228:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14229:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
14230:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
14231:                                 }
14232:                             } else {
14233:                                 if ($confhash{'validation'}{$item} ne '') {
14234:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
14235:                                 }
14236:                             }
14237:                         } else {
14238:                             if ($confhash{'validation'}{$item} ne '') {
14239:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
14240:                             }
14241:                         }
14242:                     }
14243:                 }
14244:             }
14245:             if ($env{'form.validationdc'}) {
14246:                 my $newval = $env{'form.validationdc'};
14247:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
14248:                 if (exists($domcoords{$newval})) {
14249:                     $confhash{'validation'}{'dc'} = $newval;
14250:                 }
14251:             }
14252:             if (ref($confhash{'validation'}) eq 'HASH') {
14253:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14254:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14255:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
14256:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
14257:                                 if ($confhash{'validation'}{'dc'} eq '') {
14258:                                     $changes{'validation'}{'dc'} = &mt('None');
14259:                                 } else {
14260:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14261:                                 }
14262:                             }
14263:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
14264:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14265:                         }
14266:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
14267:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14268:                     }
14269:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
14270:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14271:                 }
14272:             } else {
14273:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14274:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14275:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
14276:                             $changes{'validation'}{'dc'} = &mt('None');
14277:                         }
14278:                     }
14279:                 }
14280:             }
14281:         }
14282:     } else {
14283:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
14284:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
14285:     }
14286:     foreach my $item (@usertools) {
14287:         foreach my $type (@{$types},'default','_LC_adv') {
14288:             my $unset; 
14289:             if ($context eq 'requestcourses') {
14290:                 $unset = '0';
14291:                 if ($type eq '_LC_adv') {
14292:                     $unset = '';
14293:                 }
14294:                 if ($confhash{$item}{$type} eq 'autolimit') {
14295:                     $confhash{$item}{$type} .= '=';
14296:                     unless ($limithash{$item}{$type} =~ /\D/) {
14297:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
14298:                     }
14299:                 }
14300:             } elsif ($context eq 'requestauthor') {
14301:                 $unset = '0';
14302:                 if ($type eq '_LC_adv') {
14303:                     $unset = '';
14304:                 }
14305:             } else {
14306:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
14307:                     $confhash{$item}{$type} = 1;
14308:                 } else {
14309:                     $confhash{$item}{$type} = 0;
14310:                 }
14311:             }
14312:             if (ref($domconfig{$action}) eq 'HASH') {
14313:                 if ($action eq 'requestauthor') {
14314:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
14315:                         $changes{$type} = 1;
14316:                     }
14317:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
14318:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
14319:                         $changes{$item}{$type} = 1;
14320:                     }
14321:                 } else {
14322:                     if ($context eq 'requestcourses') {
14323:                         if ($confhash{$item}{$type} ne $unset) {
14324:                             $changes{$item}{$type} = 1;
14325:                         }
14326:                     } else {
14327:                         if (!$confhash{$item}{$type}) {
14328:                             $changes{$item}{$type} = 1;
14329:                         }
14330:                     }
14331:                 }
14332:             } else {
14333:                 if ($context eq 'requestcourses') {
14334:                     if ($confhash{$item}{$type} ne $unset) {
14335:                         $changes{$item}{$type} = 1;
14336:                     }
14337:                 } elsif ($context eq 'requestauthor') {
14338:                     if ($confhash{$type} ne $unset) {
14339:                         $changes{$type} = 1;
14340:                     }
14341:                 } else {
14342:                     if (!$confhash{$item}{$type}) {
14343:                         $changes{$item}{$type} = 1;
14344:                     }
14345:                 }
14346:             }
14347:         }
14348:     }
14349:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
14350:         if (ref($domconfig{'quotas'}) eq 'HASH') {
14351:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
14352:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
14353:                     if (exists($confhash{'defaultquota'}{$key})) {
14354:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
14355:                             $changes{'defaultquota'}{$key} = 1;
14356:                         }
14357:                     } else {
14358:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
14359:                     }
14360:                 }
14361:             } else {
14362:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
14363:                     if (exists($confhash{'defaultquota'}{$key})) {
14364:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
14365:                             $changes{'defaultquota'}{$key} = 1;
14366:                         }
14367:                     } else {
14368:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
14369:                     }
14370:                 }
14371:             }
14372:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
14373:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
14374:                     if (exists($confhash{'authorquota'}{$key})) {
14375:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
14376:                             $changes{'authorquota'}{$key} = 1;
14377:                         }
14378:                     } else {
14379:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
14380:                     }
14381:                 }
14382:             }
14383:         }
14384:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
14385:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
14386:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
14387:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
14388:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
14389:                             $changes{'defaultquota'}{$key} = 1;
14390:                         }
14391:                     } else {
14392:                         if (!exists($domconfig{'quotas'}{$key})) {
14393:                             $changes{'defaultquota'}{$key} = 1;
14394:                         }
14395:                     }
14396:                 } else {
14397:                     $changes{'defaultquota'}{$key} = 1;
14398:                 }
14399:             }
14400:         }
14401:         if (ref($confhash{'authorquota'}) eq 'HASH') {
14402:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
14403:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
14404:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
14405:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
14406:                             $changes{'authorquota'}{$key} = 1;
14407:                         }
14408:                     } else {
14409:                         $changes{'authorquota'}{$key} = 1;
14410:                     }
14411:                 } else {
14412:                     $changes{'authorquota'}{$key} = 1;
14413:                 }
14414:             }
14415:         }
14416:     }
14417: 
14418:     if ($context eq 'requestauthor') {
14419:         $domdefaults{'requestauthor'} = \%confhash;
14420:     } else {
14421:         foreach my $key (keys(%confhash)) {
14422:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
14423:                 $domdefaults{$key} = $confhash{$key};
14424:             }
14425:         }
14426:     }
14427: 
14428:     my %quotahash = (
14429:                       $action => { %confhash }
14430:                     );
14431:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
14432:                                              $dom);
14433:     if ($putresult eq 'ok') {
14434:         if (keys(%changes) > 0) {
14435:             my $cachetime = 24*60*60;
14436:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14437:             if (ref($lastactref) eq 'HASH') {
14438:                 $lastactref->{'domdefaults'} = 1;
14439:             }
14440:             $resulttext = &mt('Changes made:').'<ul>';
14441:             unless (($context eq 'requestcourses') ||
14442:                     ($context eq 'requestauthor')) {
14443:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
14444:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
14445:                     foreach my $type (@{$types},'default') {
14446:                         if (defined($changes{'defaultquota'}{$type})) {
14447:                             my $typetitle = $usertypes->{$type};
14448:                             if ($type eq 'default') {
14449:                                 $typetitle = $othertitle;
14450:                             }
14451:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
14452:                         }
14453:                     }
14454:                     $resulttext .= '</ul></li>';
14455:                 }
14456:                 if (ref($changes{'authorquota'}) eq 'HASH') {
14457:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
14458:                     foreach my $type (@{$types},'default') {
14459:                         if (defined($changes{'authorquota'}{$type})) {
14460:                             my $typetitle = $usertypes->{$type};
14461:                             if ($type eq 'default') {
14462:                                 $typetitle = $othertitle;
14463:                             }
14464:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
14465:                         }
14466:                     }
14467:                     $resulttext .= '</ul></li>';
14468:                 }
14469:             }
14470:             my %newenv;
14471:             foreach my $item (@usertools) {
14472:                 my (%haschgs,%inconf);
14473:                 if ($context eq 'requestauthor') {
14474:                     %haschgs = %changes;
14475:                     %inconf = %confhash;
14476:                 } else {
14477:                     if (ref($changes{$item}) eq 'HASH') {
14478:                         %haschgs = %{$changes{$item}};
14479:                     }
14480:                     if (ref($confhash{$item}) eq 'HASH') {
14481:                         %inconf = %{$confhash{$item}};
14482:                     }
14483:                 }
14484:                 if (keys(%haschgs) > 0) {
14485:                     my $newacc = 
14486:                         &Apache::lonnet::usertools_access($env{'user.name'},
14487:                                                           $env{'user.domain'},
14488:                                                           $item,'reload',$context);
14489:                     if (($context eq 'requestcourses') ||
14490:                         ($context eq 'requestauthor')) {
14491:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
14492:                             $newenv{'environment.canrequest.'.$item} = $newacc;
14493:                         }
14494:                     } else {
14495:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
14496:                             $newenv{'environment.availabletools.'.$item} = $newacc;
14497:                         }
14498:                     }
14499:                     unless ($context eq 'requestauthor') {
14500:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
14501:                     }
14502:                     foreach my $type (@{$types},'default','_LC_adv') {
14503:                         if ($haschgs{$type}) {
14504:                             my $typetitle = $usertypes->{$type};
14505:                             if ($type eq 'default') {
14506:                                 $typetitle = $othertitle;
14507:                             } elsif ($type eq '_LC_adv') {
14508:                                 $typetitle = 'LON-CAPA Advanced Users'; 
14509:                             }
14510:                             if ($inconf{$type}) {
14511:                                 if ($context eq 'requestcourses') {
14512:                                     my $cond;
14513:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
14514:                                         if ($1 eq '') {
14515:                                             $cond = &mt('(Automatic processing of any request).');
14516:                                         } else {
14517:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
14518:                                         }
14519:                                     } else { 
14520:                                         $cond = $conditions{$inconf{$type}};
14521:                                     }
14522:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
14523:                                 } elsif ($context eq 'requestauthor') {
14524:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
14525:                                                              $titles{$inconf{$type}},$typetitle);
14526: 
14527:                                 } else {
14528:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
14529:                                 }
14530:                             } else {
14531:                                 if ($type eq '_LC_adv') {
14532:                                     if ($inconf{$type} eq '0') {
14533:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
14534:                                     } else { 
14535:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
14536:                                     }
14537:                                 } else {
14538:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
14539:                                 }
14540:                             }
14541:                         }
14542:                     }
14543:                     unless ($context eq 'requestauthor') {
14544:                         $resulttext .= '</ul></li>';
14545:                     }
14546:                 }
14547:             }
14548:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
14549:                 if (ref($changes{'notify'}) eq 'HASH') {
14550:                     if ($changes{'notify'}{'approval'}) {
14551:                         if (ref($confhash{'notify'}) eq 'HASH') {
14552:                             if ($confhash{'notify'}{'approval'}) {
14553:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
14554:                             } else {
14555:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
14556:                             }
14557:                         }
14558:                     }
14559:                 }
14560:             }
14561:             if ($action eq 'requestcourses') {
14562:                 my @offon = ('off','on');
14563:                 if ($changes{'uniquecode'}) {
14564:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
14565:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
14566:                         $resulttext .= '<li>'.
14567:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
14568:                                        '</li>';
14569:                     } else {
14570:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
14571:                                        '</li>';
14572:                     }
14573:                 }
14574:                 foreach my $type ('textbooks','templates') {
14575:                     if (ref($changes{$type}) eq 'HASH') {
14576:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
14577:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
14578:                             my %coursehash = &Apache::lonnet::coursedescription($key);
14579:                             my $coursetitle = $coursehash{'description'};
14580:                             my $position = $confhash{$type}{$key}{'order'} + 1;
14581:                             $resulttext .= '<li>';
14582:                             foreach my $item ('subject','title','publisher','author') {
14583:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
14584:                                          ($type eq 'templates'));
14585:                                 my $name = $item.':';
14586:                                 $name =~ s/^(\w)/\U$1/;
14587:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
14588:                             }
14589:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
14590:                             if ($type eq 'textbooks') {
14591:                                 if ($confhash{$type}{$key}{'image'}) {
14592:                                     $resulttext .= ' '.&mt('Image: [_1]',
14593:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
14594:                                                    ' alt="Textbook cover" />').'<br />';
14595:                                 }
14596:                             }
14597:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
14598:                         }
14599:                         $resulttext .= '</ul></li>';
14600:                     }
14601:                 }
14602:                 if (ref($changes{'validation'}) eq 'HASH') {
14603:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
14604:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
14605:                         foreach my $item (@{$validationitemsref}) {
14606:                             if (exists($changes{'validation'}{$item})) {
14607:                                 if ($item eq 'markup') {
14608:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
14609:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
14610:                                 } else {
14611:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
14612:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
14613:                                 }
14614:                             }
14615:                         }
14616:                         if (exists($changes{'validation'}{'dc'})) {
14617:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
14618:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
14619:                         }
14620:                     }
14621:                 }
14622:             }
14623:             $resulttext .= '</ul>';
14624:             if (keys(%newenv)) {
14625:                 &Apache::lonnet::appenv(\%newenv);
14626:             }
14627:         } else {
14628:             if ($context eq 'requestcourses') {
14629:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
14630:             } elsif ($context eq 'requestauthor') {
14631:                 $resulttext = &mt('No changes made to rights to request author space.');
14632:             } else {
14633:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
14634:             }
14635:         }
14636:     } else {
14637:         $resulttext = '<span class="LC_error">'.
14638: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
14639:     }
14640:     if ($errors) {
14641:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
14642:                        '<ul>'.$errors.'</ul></p>';
14643:     }
14644:     return $resulttext;
14645: }
14646: 
14647: sub process_textbook_image {
14648:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
14649:     my $filename = $env{'form.'.$caller.'.filename'};
14650:     my ($error,$url);
14651:     my ($width,$height) = (50,50);
14652:     if ($configuserok eq 'ok') {
14653:         if ($switchserver) {
14654:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
14655:                          $switchserver);
14656:         } elsif ($author_ok eq 'ok') {
14657:             my ($result,$imageurl) =
14658:                 &publishlogo($r,'upload',$caller,$dom,$confname,
14659:                              "$type/$cdom/$cnum/cover",$width,$height);
14660:             if ($result eq 'ok') {
14661:                 $url = $imageurl;
14662:             } else {
14663:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
14664:             }
14665:         } else {
14666:             $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);
14667:         }
14668:     } else {
14669:         $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);
14670:     }
14671:     return ($url,$error);
14672: }
14673: 
14674: sub modify_ltitools {
14675:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
14676:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14677:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
14678:     my $confname = $dom.'-domainconfig';
14679:     my $servadm = $r->dir_config('lonAdmEMail');
14680:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
14681:     my (%posslti,%possfield);
14682:     my @courseroles = ('cc','in','ta','ep','st');
14683:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
14684:     map { $posslti{$_} = 1; } @ltiroles;
14685:     my @allfields = ('fullname','firstname','lastname','email','user','roles');
14686:     map { $possfield{$_} = 1; } @allfields;
14687:     my %lt = &ltitools_names(); 
14688:     if ($env{'form.ltitools_add'}) {
14689:         my $title = $env{'form.ltitools_add_title'};
14690:         $title =~ s/(`)/'/g;
14691:         ($newid,my $error) = &get_ltitools_id($dom,$title);
14692:         if ($newid) {
14693:             my $position = $env{'form.ltitools_add_pos'};
14694:             $position =~ s/\D+//g;
14695:             if ($position ne '') {
14696:                 $allpos[$position] = $newid;
14697:             }
14698:             $changes{$newid} = 1;
14699:             foreach my $item ('title','url','key','secret','lifetime') {
14700:                 $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
14701:                 if ($item eq 'lifetime') {
14702:                     $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
14703:                 }
14704:                 if ($env{'form.ltitools_add_'.$item}) {
14705:                     if (($item eq 'key') || ($item eq 'secret')) {
14706:                         $encconfig{$newid}{$item} = $env{'form.ltitools_add_'.$item};
14707:                     } else {
14708:                         $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
14709:                     }
14710:                 }
14711:             }
14712:             if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
14713:                 $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
14714:             }
14715:             if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
14716:                 $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
14717:             }
14718:             if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
14719:                 $confhash{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
14720:             } else {
14721:                 $confhash{$newid}{'sigmethod'} = 'HMAC-SHA1';
14722:             }
14723:             foreach my $item ('width','height','linktext','explanation') {
14724:                 $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
14725:                 $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
14726:                 if (($item eq 'width') || ($item eq 'height')) {
14727:                     if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
14728:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
14729:                     }
14730:                 } else {
14731:                     if ($env{'form.ltitools_add_'.$item} ne '') {
14732:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item}; 
14733:                     }
14734:                 }
14735:             }
14736:             if ($env{'form.ltitools_add_target'} eq 'window') {
14737:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
14738:             } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
14739:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
14740:             } else {
14741:                 $confhash{$newid}{'display'}{'target'} = 'iframe';
14742:             }
14743:             foreach my $item ('passback','roster') {
14744:                 if ($env{'form.ltitools_'.$item.'_add'}) {
14745:                     $confhash{$newid}{$item} = 1;
14746:                     if ($env{'form.ltitools_'.$item.'valid_add'} ne '') {
14747:                         my $lifetime = $env{'form.ltitools_'.$item.'valid_add'};
14748:                         $lifetime =~ s/^\s+|\s+$//g;
14749:                         if ($lifetime =~ /^\d+\.?\d*$/) {
14750:                             $confhash{$newid}{$item.'valid'} = $lifetime;
14751:                         }
14752:                     }
14753:                 }
14754:             }
14755:             if ($env{'form.ltitools_add_image.filename'} ne '') {
14756:                 my ($imageurl,$error) =
14757:                     &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$newid,
14758:                                             $configuserok,$switchserver,$author_ok);
14759:                 if ($imageurl) {
14760:                     $confhash{$newid}{'image'} = $imageurl;
14761:                 }
14762:                 if ($error) {
14763:                     &Apache::lonnet::logthis($error);
14764:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14765:                 }
14766:             }
14767:             my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
14768:             foreach my $field (@fields) {
14769:                 if ($possfield{$field}) {
14770:                     if ($field eq 'roles') {
14771:                         foreach my $role (@courseroles) {
14772:                             my $choice = $env{'form.ltitools_add_roles_'.$role};
14773:                             if (($choice ne '') && ($posslti{$choice})) {
14774:                                 $confhash{$newid}{'roles'}{$role} = $choice;
14775:                                 if ($role eq 'cc') {
14776:                                     $confhash{$newid}{'roles'}{'co'} = $choice; 
14777:                                 }
14778:                             }
14779:                         }
14780:                     } else {
14781:                         $confhash{$newid}{'fields'}{$field} = 1;
14782:                     }
14783:                 }
14784:             }
14785:             if (ref($confhash{$newid}{'fields'}) eq 'HASH') {
14786:                 if ($confhash{$newid}{'fields'}{'user'}) {
14787:                     if ($env{'form.ltitools_userincdom_add'}) {
14788:                         $confhash{$newid}{'incdom'} = 1;
14789:                     }
14790:                 }
14791:             }
14792:             my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
14793:             foreach my $item (@courseconfig) {
14794:                 $confhash{$newid}{'crsconf'}{$item} = 1;
14795:             }
14796:             if ($env{'form.ltitools_add_custom'}) {
14797:                 my $name = $env{'form.ltitools_add_custom_name'};
14798:                 my $value = $env{'form.ltitools_add_custom_value'};
14799:                 $value =~ s/(`)/'/g;
14800:                 $name =~ s/(`)/'/g;
14801:                 $confhash{$newid}{'custom'}{$name} = $value;
14802:             }
14803:         } else {
14804:             my $error = &mt('Failed to acquire unique ID for new external tool');   
14805:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14806:         }
14807:     }
14808:     if (ref($domconfig{$action}) eq 'HASH') {
14809:         my %deletions;
14810:         my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
14811:         if (@todelete) {
14812:             map { $deletions{$_} = 1; } @todelete;
14813:         }
14814:         my %customadds;
14815:         my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
14816:         if (@newcustom) {
14817:             map { $customadds{$_} = 1; } @newcustom;
14818:         } 
14819:         my %imgdeletions;
14820:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
14821:         if (@todeleteimages) {
14822:             map { $imgdeletions{$_} = 1; } @todeleteimages;
14823:         }
14824:         my $maxnum = $env{'form.ltitools_maxnum'};
14825:         for (my $i=0; $i<=$maxnum; $i++) {
14826:             my $itemid = $env{'form.ltitools_id_'.$i};
14827:             $itemid =~ s/\D+//g;
14828:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
14829:                 if ($deletions{$itemid}) {
14830:                     if ($domconfig{$action}{$itemid}{'image'}) {
14831:                         #FIXME need to obsolete item in RES space
14832:                     }
14833:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
14834:                     next;
14835:                 } else {
14836:                     my $newpos = $env{'form.ltitools_'.$itemid};
14837:                     $newpos =~ s/\D+//g;
14838:                     foreach my $item ('title','url','lifetime') {
14839:                         $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
14840:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
14841:                             $changes{$itemid} = 1;
14842:                         }
14843:                     }
14844:                     foreach my $item ('key','secret') {
14845:                         $encconfig{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
14846:                         if ($domconfig{$action}{$itemid}{$item} ne $encconfig{$itemid}{$item}) {
14847:                             $changes{$itemid} = 1;
14848:                         }
14849:                     }
14850:                     if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
14851:                         $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
14852:                     }
14853:                     if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
14854:                         $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
14855:                     }
14856:                     if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
14857:                         $confhash{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
14858:                     } else {
14859:                         $confhash{$itemid}{'sigmethod'} = 'HMAC-SHA1'; 
14860:                     }
14861:                     if ($domconfig{$action}{$itemid}{'sigmethod'} eq '') {
14862:                         if ($confhash{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
14863:                             $changes{$itemid} = 1;
14864:                         }
14865:                     } elsif ($domconfig{$action}{$itemid}{'sigmethod'} ne $confhash{$itemid}{'sigmethod'}) {
14866:                         $changes{$itemid} = 1;
14867:                     }
14868:                     foreach my $size ('width','height') {
14869:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
14870:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
14871:                         if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
14872:                             $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
14873:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14874:                                 if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
14875:                                     $changes{$itemid} = 1;
14876:                                 }
14877:                             } else {
14878:                                 $changes{$itemid} = 1;
14879:                             }
14880:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14881:                             if ($domconfig{$action}{$itemid}{'display'}{$size} ne '') {
14882:                                 $changes{$itemid} = 1;
14883:                             }
14884:                         }
14885:                     }
14886:                     foreach my $item ('linktext','explanation') {
14887:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
14888:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
14889:                         if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
14890:                             $confhash{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
14891:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14892:                                 if ($domconfig{$action}{$itemid}{'display'}{$item} ne $confhash{$itemid}{'display'}{$item}) {
14893:                                     $changes{$itemid} = 1;
14894:                                 }
14895:                             } else {
14896:                                 $changes{$itemid} = 1;
14897:                             }
14898:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14899:                             if ($domconfig{$action}{$itemid}{'display'}{$item} ne '') {
14900:                                 $changes{$itemid} = 1;
14901:                             }
14902:                         }
14903:                     }
14904:                     if ($env{'form.ltitools_target_'.$i} eq 'window') {
14905:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
14906:                     } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
14907:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
14908:                     } else {
14909:                         $confhash{$itemid}{'display'}{'target'} = 'iframe';
14910:                     }
14911:                     if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14912:                         if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
14913:                             $changes{$itemid} = 1;
14914:                         }
14915:                     } else {
14916:                         $changes{$itemid} = 1;
14917:                     }
14918:                     foreach my $extra ('passback','roster') {
14919:                         if ($env{'form.ltitools_'.$extra.'_'.$i}) {
14920:                             $confhash{$itemid}{$extra} = 1;
14921:                             if ($env{'form.ltitools_'.$extra.'valid_'.$i} ne '') {
14922:                                 my $lifetime = $env{'form.ltitools_'.$extra.'valid_'.$i};
14923:                                 $lifetime =~ s/^\s+|\s+$//g;
14924:                                 if ($lifetime =~ /^\d+\.?\d*$/) {
14925:                                     $confhash{$itemid}{$extra.'valid'} = $lifetime;
14926:                                 }
14927:                             }
14928:                         }
14929:                         if ($domconfig{$action}{$itemid}{$extra} ne $confhash{$itemid}{$extra}) {
14930:                             $changes{$itemid} = 1;
14931:                         }
14932:                         if ($domconfig{$action}{$itemid}{$extra.'valid'} ne $confhash{$itemid}{$extra.'valid'}) {
14933:                             $changes{$itemid} = 1;
14934:                         }
14935:                     }
14936:                     my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
14937:                     foreach my $item ('label','title','target','linktext','explanation','append') {
14938:                         if (grep(/^\Q$item\E$/,@courseconfig)) {
14939:                             $confhash{$itemid}{'crsconf'}{$item} = 1;
14940:                             if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
14941:                                 if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
14942:                                     $changes{$itemid} = 1;
14943:                                 }
14944:                             } else {
14945:                                 $changes{$itemid} = 1;
14946:                             }
14947:                         }
14948:                     }
14949:                     my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
14950:                     foreach my $field (@fields) {
14951:                         if ($possfield{$field}) {
14952:                             if ($field eq 'roles') {
14953:                                 foreach my $role (@courseroles) {
14954:                                     my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
14955:                                     if (($choice ne '') && ($posslti{$choice})) {
14956:                                         $confhash{$itemid}{'roles'}{$role} = $choice;
14957:                                         if ($role eq 'cc') {
14958:                                             $confhash{$itemid}{'roles'}{'co'} = $choice;
14959:                                         }
14960:                                     }
14961:                                     if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
14962:                                         if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
14963:                                             $changes{$itemid} = 1;
14964:                                         }
14965:                                     } elsif ($confhash{$itemid}{'roles'}{$role}) {
14966:                                         $changes{$itemid} = 1;
14967:                                     }
14968:                                 }
14969:                             } else {
14970:                                 $confhash{$itemid}{'fields'}{$field} = 1;
14971:                                 if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
14972:                                     if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
14973:                                         $changes{$itemid} = 1;
14974:                                     }
14975:                                 } else {
14976:                                     $changes{$itemid} = 1;
14977:                                 }
14978:                             }
14979:                         }
14980:                     }
14981:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
14982:                         if ($confhash{$itemid}{'fields'}{'user'}) {
14983:                             if ($env{'form.ltitools_userincdom_'.$i}) {
14984:                                 $confhash{$itemid}{'incdom'} = 1;
14985:                             }
14986:                             if ($domconfig{$action}{$itemid}{'incdom'} ne $confhash{$itemid}{'incdom'}) {
14987:                                 $changes{$itemid} = 1;
14988:                             }
14989:                         }
14990:                     }
14991:                     $allpos[$newpos] = $itemid;
14992:                 }
14993:                 if ($imgdeletions{$itemid}) {
14994:                     $changes{$itemid} = 1;
14995:                     #FIXME need to obsolete item in RES space
14996:                 } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
14997:                     my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
14998:                                                                  $itemid,$configuserok,$switchserver,
14999:                                                                  $author_ok);
15000:                     if ($imgurl) {
15001:                         $confhash{$itemid}{'image'} = $imgurl;
15002:                         $changes{$itemid} = 1;
15003:                     }
15004:                     if ($error) {
15005:                         &Apache::lonnet::logthis($error);
15006:                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
15007:                     }
15008:                 } elsif ($domconfig{$action}{$itemid}{'image'}) {
15009:                     $confhash{$itemid}{'image'} =
15010:                        $domconfig{$action}{$itemid}{'image'};
15011:                 }
15012:                 if ($customadds{$i}) {
15013:                     my $name = $env{'form.ltitools_custom_name_'.$i};
15014:                     $name =~ s/(`)/'/g;
15015:                     $name =~ s/^\s+//;
15016:                     $name =~ s/\s+$//;
15017:                     my $value = $env{'form.ltitools_custom_value_'.$i};
15018:                     $value =~ s/(`)/'/g;
15019:                     $value =~ s/^\s+//;
15020:                     $value =~ s/\s+$//;
15021:                     if ($name ne '') {
15022:                         $confhash{$itemid}{'custom'}{$name} = $value;
15023:                         $changes{$itemid} = 1;
15024:                     }
15025:                 }
15026:                 my %customdels;
15027:                 my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i); 
15028:                 if (@customdeletions) {
15029:                     $changes{$itemid} = 1;
15030:                 }
15031:                 map { $customdels{$_} = 1; } @customdeletions;
15032:                 if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
15033:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
15034:                         unless ($customdels{$key}) {
15035:                             if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
15036:                                 $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i}; 
15037:                             }
15038:                             if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
15039:                                 $changes{$itemid} = 1;
15040:                             }
15041:                         }
15042:                     }
15043:                 }
15044:                 unless ($changes{$itemid}) {
15045:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
15046:                         if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
15047:                             if (ref($confhash{$itemid}{$key}) eq 'HASH') {
15048:                                 foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
15049:                                     unless (exists($confhash{$itemid}{$key}{$innerkey})) {
15050:                                         $changes{$itemid} = 1;
15051:                                         last;
15052:                                     }
15053:                                 }
15054:                             } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
15055:                                 $changes{$itemid} = 1;
15056:                             }
15057:                         }
15058:                         last if ($changes{$itemid});
15059:                     }
15060:                 }
15061:             }
15062:         }
15063:     }
15064:     if (@allpos > 0) {
15065:         my $idx = 0;
15066:         foreach my $itemid (@allpos) {
15067:             if ($itemid ne '') {
15068:                 $confhash{$itemid}{'order'} = $idx;
15069:                 if (ref($domconfig{$action}) eq 'HASH') {
15070:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
15071:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
15072:                             $changes{$itemid} = 1;
15073:                         }
15074:                     }
15075:                 }
15076:                 $idx ++;
15077:             }
15078:         }
15079:     }
15080:     my %ltitoolshash = (
15081:                           $action => { %confhash }
15082:                        );
15083:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
15084:                                              $dom);
15085:     if ($putresult eq 'ok') {
15086:         my %ltienchash = (
15087:                              $action => { %encconfig }
15088:                          );
15089:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
15090:         if (keys(%changes) > 0) {
15091:             my $cachetime = 24*60*60;
15092:             my %ltiall = %confhash;
15093:             foreach my $id (keys(%ltiall)) {
15094:                 if (ref($encconfig{$id}) eq 'HASH') {
15095:                     foreach my $item ('key','secret') {
15096:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
15097:                     }
15098:                 }
15099:             }
15100:             &Apache::lonnet::do_cache_new('ltitools',$dom,\%ltiall,$cachetime);
15101:             if (ref($lastactref) eq 'HASH') {
15102:                 $lastactref->{'ltitools'} = 1;
15103:             }
15104:             $resulttext = &mt('Changes made:').'<ul>';
15105:             my %bynum;
15106:             foreach my $itemid (sort(keys(%changes))) {
15107:                 my $position = $confhash{$itemid}{'order'};
15108:                 $bynum{$position} = $itemid;
15109:             }
15110:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
15111:                 my $itemid = $bynum{$pos}; 
15112:                 if (ref($confhash{$itemid}) ne 'HASH') {
15113:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
15114:                 } else {
15115:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
15116:                     if ($confhash{$itemid}{'image'}) {
15117:                         $resulttext .= '&nbsp;'.
15118:                                        '<img src="'.$confhash{$itemid}{'image'}.'"'.
15119:                                        ' alt="'.&mt('Tool Provider icon').'" />';
15120:                     }
15121:                     $resulttext .= '</li><ul>';
15122:                     my $position = $pos + 1;
15123:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
15124:                     foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
15125:                         if ($confhash{$itemid}{$item} ne '') {
15126:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
15127:                         }
15128:                     }
15129:                     if ($encconfig{$itemid}{'key'} ne '') {
15130:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
15131:                     }
15132:                     if ($encconfig{$itemid}{'secret'} ne '') {
15133:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
15134:                         my $num = length($encconfig{$itemid}{'secret'});
15135:                         $resulttext .= ('*'x$num).'</li>';
15136:                     }
15137:                     $resulttext .= '<li>'.&mt('Configurable in course:');
15138:                     my @possconfig = ('label','title','target','linktext','explanation','append');
15139:                     my $numconfig = 0; 
15140:                     if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') { 
15141:                         foreach my $item (@possconfig) {
15142:                             if ($confhash{$itemid}{'crsconf'}{$item}) {
15143:                                 $numconfig ++;
15144:                                 $resulttext .= ' "'.$lt{'crs'.$item}.'"';
15145:                             }
15146:                         }
15147:                     }
15148:                     if (!$numconfig) {
15149:                         $resulttext .= '&nbsp;'.&mt('None');
15150:                     }
15151:                     $resulttext .= '</li>';
15152:                     foreach my $item ('passback','roster') {
15153:                         $resulttext .= '<li>'.$lt{$item}.'&nbsp;';
15154:                         if ($confhash{$itemid}{$item}) {
15155:                             $resulttext .= &mt('Yes');
15156:                             if ($confhash{$itemid}{$item.'valid'}) {
15157:                                 if ($item eq 'passback') {
15158:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,day] after launch',
15159:                                                            $confhash{$itemid}{$item.'valid'});
15160:                                 } else {
15161:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,second] after launch',
15162:                                                            $confhash{$itemid}{$item.'valid'});
15163:                                 }
15164:                             }
15165:                         } else {
15166:                             $resulttext .= &mt('No');
15167:                         }
15168:                         $resulttext .= '</li>';
15169:                     }
15170:                     if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
15171:                         my $displaylist;
15172:                         if ($confhash{$itemid}{'display'}{'target'}) {
15173:                             $displaylist = &mt('Display target').':&nbsp;'.
15174:                                            $confhash{$itemid}{'display'}{'target'}.',';
15175:                         }
15176:                         foreach my $size ('width','height') { 
15177:                             if ($confhash{$itemid}{'display'}{$size}) {
15178:                                 $displaylist .= ('&nbsp;'x2).$lt{$size}.':&nbsp;'.
15179:                                                 $confhash{$itemid}{'display'}{$size}.',';
15180:                             }
15181:                         }
15182:                         if ($displaylist) {
15183:                             $displaylist =~ s/,$//;
15184:                             $resulttext .= '<li>'.$displaylist.'</li>';
15185:                         }
15186:                         foreach my $item ('linktext','explanation') {
15187:                             if ($confhash{$itemid}{'display'}{$item}) {
15188:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{'display'}{$item}.'</li>';
15189:                             }
15190:                         }
15191:                     }
15192:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
15193:                         my $fieldlist;
15194:                         foreach my $field (@allfields) {
15195:                             if ($confhash{$itemid}{'fields'}{$field}) {
15196:                                 $fieldlist .= ('&nbsp;'x2).$lt{$field}.',';
15197:                             }
15198:                         }
15199:                         if ($fieldlist) {
15200:                             $fieldlist =~ s/,$//;
15201:                             if ($confhash{$itemid}{'fields'}{'user'}) {
15202:                                 if ($confhash{$itemid}{'incdom'}) {
15203:                                     $fieldlist .= ' ('.&mt('username:domain').')';
15204:                                 } else {
15205:                                     $fieldlist .= ' ('.&mt('username').')';
15206:                                 }
15207:                             }
15208:                             $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
15209:                         }
15210:                     }
15211:                     if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
15212:                         my $rolemaps;
15213:                         foreach my $role (@courseroles) {
15214:                             if ($confhash{$itemid}{'roles'}{$role}) {
15215:                                 $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
15216:                                              $confhash{$itemid}{'roles'}{$role}.',';
15217:                             }
15218:                         }
15219:                         if ($rolemaps) {
15220:                             $rolemaps =~ s/,$//; 
15221:                             $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
15222:                         }
15223:                     }
15224:                     if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
15225:                         my $customlist;
15226:                         if (keys(%{$confhash{$itemid}{'custom'}})) {
15227:                             foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
15228:                                 $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.('&nbsp;'x2);
15229:                             } 
15230:                         }
15231:                         if ($customlist) {
15232:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
15233:                         }
15234:                     } 
15235:                     $resulttext .= '</ul></li>';
15236:                 }
15237:             }
15238:             $resulttext .= '</ul>';
15239:         } else {
15240:             $resulttext = &mt('No changes made.');
15241:         }
15242:     } else {
15243:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
15244:     }
15245:     if ($errors) {
15246:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
15247:                        $errors.'</ul>';
15248:     }
15249:     return $resulttext;
15250: }
15251: 
15252: sub process_ltitools_image {
15253:     my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
15254:     my $filename = $env{'form.'.$caller.'.filename'};
15255:     my ($error,$url);
15256:     my ($width,$height) = (21,21);
15257:     if ($configuserok eq 'ok') {
15258:         if ($switchserver) {
15259:             $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
15260:                          $switchserver);
15261:         } elsif ($author_ok eq 'ok') {
15262:             my ($result,$imageurl,$madethumb) =
15263:                 &publishlogo($r,'upload',$caller,$dom,$confname,
15264:                              "ltitools/$itemid/icon",$width,$height);
15265:             if ($result eq 'ok') {
15266:                 if ($madethumb) {
15267:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
15268:                     my $imagethumb = "$path/tn-".$imagefile;
15269:                     $url = $imagethumb;
15270:                 } else {
15271:                     $url = $imageurl;
15272:                 }
15273:             } else {
15274:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
15275:             }
15276:         } else {
15277:             $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);
15278:         }
15279:     } else {
15280:         $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);
15281:     }
15282:     return ($url,$error);
15283: }
15284: 
15285: sub get_ltitools_id {
15286:     my ($cdom,$title) = @_;
15287:     # get lock on ltitools db
15288:     my $lockhash = {
15289:                       lock => $env{'user.name'}.
15290:                               ':'.$env{'user.domain'},
15291:                    };
15292:     my $tries = 0;
15293:     my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
15294:     my ($id,$error);
15295:  
15296:     while (($gotlock ne 'ok') && ($tries<10)) {
15297:         $tries ++;
15298:         sleep (0.1);
15299:         $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
15300:     }
15301:     if ($gotlock eq 'ok') {
15302:         my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
15303:         if ($currids{'lock'}) {
15304:             delete($currids{'lock'});
15305:             if (keys(%currids)) {
15306:                 my @curr = sort { $a <=> $b } keys(%currids);
15307:                 if ($curr[-1] =~ /^\d+$/) {
15308:                     $id = 1 + $curr[-1];
15309:                 }
15310:             } else {
15311:                 $id = 1;
15312:             }
15313:             if ($id) {
15314:                 unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
15315:                     $error = 'nostore';
15316:                 }
15317:             } else {
15318:                 $error = 'nonumber';
15319:             }
15320:         }
15321:         my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
15322:     } else {
15323:         $error = 'nolock';
15324:     }
15325:     return ($id,$error);
15326: }
15327: 
15328: sub modify_proctoring {
15329:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
15330:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15331:     my (@allpos,%changes,%confhash,%encconfhash,$errors,$resulttext,%imgdeletions);
15332:     my $confname = $dom.'-domainconfig';
15333:     my $servadm = $r->dir_config('lonAdmEMail');
15334:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
15335:     my %providernames = &proctoring_providernames();
15336:     my $maxnum = scalar(keys(%providernames));
15337: 
15338:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
15339:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
15340:     if (ref($requref) eq 'HASH') {
15341:         %requserfields = %{$requref};
15342:     }
15343:     if (ref($opturef) eq 'HASH') {
15344:         %optuserfields = %{$opturef};
15345:     }
15346:     if (ref($defref) eq 'HASH') {
15347:         %defaults = %{$defref};
15348:     }
15349:     if (ref($extref) eq 'HASH') {
15350:         %extended = %{$extref};
15351:     }
15352:     if (ref($crsref) eq 'HASH') {
15353:         %crsconf = %{$crsref};
15354:     }
15355:     if (ref($rolesref) eq 'ARRAY') {
15356:         @courseroles = @{$rolesref};
15357:     }
15358:     if (ref($ltiref) eq 'ARRAY') {
15359:         @ltiroles = @{$ltiref};
15360:     }
15361: 
15362:     if (ref($domconfig{$action}) eq 'HASH') {
15363:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.proctoring_image_del');
15364:         if (@todeleteimages) {
15365:             map { $imgdeletions{$_} = 1; } @todeleteimages;
15366:         }
15367:     }
15368:     my %customadds;
15369:     my @newcustom = &Apache::loncommon::get_env_multiple('form.proctoring_customadd');
15370:     if (@newcustom) {
15371:         map { $customadds{$_} = 1; } @newcustom;
15372:     }
15373:     foreach my $provider (sort(keys(%providernames))) {
15374:         $confhash{$provider} = {};
15375:         my $pos = $env{'form.proctoring_pos_'.$provider};
15376:         $pos =~ s/\D+//g;
15377:         $allpos[$pos] = $provider;
15378:         my (%current,%currentenc);
15379:         my $showroles = 0;
15380:         if (ref($domconfig{$action}) eq 'HASH') {
15381:             if (ref($domconfig{$action}{$provider}) eq 'HASH') {
15382:                 %current = %{$domconfig{$action}{$provider}};
15383:                 foreach my $item ('key','secret') { 
15384:                     $currentenc{$item} = $current{$item};
15385:                     delete($current{$item});
15386:                 }
15387:             }
15388:         }
15389:         if ($env{'form.proctoring_available_'.$provider}) {
15390:             $confhash{$provider}{'available'} = 1;
15391:             unless ($current{'available'}) {
15392:                 $changes{$provider} = 1;
15393:             }
15394:         } else {
15395:             %{$confhash{$provider}} = %current;
15396:             %{$encconfhash{$provider}} = %currentenc;
15397:             $confhash{$provider}{'available'} = 0;
15398:             if ($current{'available'}) {
15399:                 $changes{$provider} = 1;
15400:             }
15401:         }
15402:         if ($confhash{$provider}{'available'}) {
15403:             foreach my $field ('lifetime','version','sigmethod','url','key','secret') {
15404:                 my $possval = $env{'form.proctoring_'.$provider.'_'.$field};
15405:                 if ($field eq 'lifetime') {
15406:                     if ($possval =~ /^\d+$/) {
15407:                         $confhash{$provider}{$field} = $possval;
15408:                     }
15409:                 } elsif ($field eq 'version') {
15410:                     if ($possval =~ /^\d+\.\d+$/) {
15411:                         $confhash{$provider}{$field} = $possval;
15412:                     }
15413:                 } elsif ($field eq 'sigmethod') {
15414:                     if ($possval =~ /^\QHMAC-SHA\E(1|256)$/) {
15415:                         $confhash{$provider}{$field} = $possval;
15416:                     }
15417:                 } elsif ($field eq 'url') {
15418:                     $confhash{$provider}{$field} = $possval;
15419:                 } elsif (($field eq 'key') || ($field eq 'secret')) {
15420:                     $encconfhash{$provider}{$field} = $possval;
15421:                     unless ($currentenc{$field} eq $possval) {
15422:                         $changes{$provider} = 1;
15423:                     }
15424:                 }
15425:                 unless (($field eq 'key') || ($field eq 'secret')) {
15426:                     unless ($current{$field} eq $confhash{$provider}{$field}) {
15427:                         $changes{$provider} = 1;
15428:                     }
15429:                 }
15430:             }
15431:             if ($imgdeletions{$provider}) {
15432:                 $changes{$provider} = 1;
15433:             } elsif ($env{'form.proctoring_image_'.$provider.'.filename'} ne '') {
15434:                 my ($imageurl,$error) =
15435:                     &process_proctoring_image($r,$dom,$confname,'proctoring_image_'.$provider,$provider,
15436:                                               $configuserok,$switchserver,$author_ok);
15437:                 if ($imageurl) {
15438:                     $confhash{$provider}{'image'} = $imageurl;
15439:                     $changes{$provider} = 1; 
15440:                 }
15441:                 if ($error) {
15442:                     &Apache::lonnet::logthis($error);
15443:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
15444:                 }
15445:             } elsif (exists($current{'image'})) {
15446:                 $confhash{$provider}{'image'} = $current{'image'};
15447:             }
15448:             if (ref($requserfields{$provider}) eq 'ARRAY') {
15449:                 if (@{$requserfields{$provider}} > 0) {
15450:                     if (grep(/^user$/,@{$requserfields{$provider}})) {
15451:                         if ($env{'form.proctoring_userincdom_'.$provider}) {
15452:                             $confhash{$provider}{'incdom'} = 1;
15453:                         }
15454:                         unless ($current{'incdom'} eq $confhash{$provider}{'incdom'}) {
15455:                             $changes{$provider} = 1;
15456:                         }
15457:                     }
15458:                     if (grep(/^roles$/,@{$requserfields{$provider}})) {
15459:                         $showroles = 1;
15460:                     }
15461:                 }
15462:             }
15463:             $confhash{$provider}{'fields'} = [];
15464:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
15465:                 if (@{$optuserfields{$provider}} > 0) {
15466:                     my @optfields = &Apache::loncommon::get_env_multiple('form.proctoring_optional_'.$provider);
15467:                     foreach my $field (@{$optuserfields{$provider}}) {
15468:                         if (grep(/^\Q$field\E$/,@optfields)) {
15469:                             push(@{$confhash{$provider}{'fields'}},$field);
15470:                         }
15471:                     }
15472:                 }
15473:                 if (ref($current{'fields'}) eq 'ARRAY') {
15474:                     unless ($changes{$provider}) {
15475:                         my @new = sort(@{$confhash{$provider}{'fields'}});
15476:                         my @old = sort(@{$current{'fields'}}); 
15477:                         my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
15478:                         if (@diffs) {
15479:                             $changes{$provider} = 1;
15480:                         }
15481:                     }
15482:                 } elsif (@{$confhash{$provider}{'fields'}}) {
15483:                     $changes{$provider} = 1;
15484:                 }
15485:             }
15486:             if (ref($defaults{$provider}) eq 'ARRAY') {  
15487:                 if (@{$defaults{$provider}} > 0) {
15488:                     my %options;
15489:                     if (ref($extended{$provider}) eq 'HASH') {
15490:                         %options = %{$extended{$provider}};
15491:                     }
15492:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_defaults_'.$provider);
15493:                     foreach my $field (@{$defaults{$provider}}) {
15494:                         if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
15495:                             my $poss = $env{'form.proctoring_defaults_'.$field.'_'.$provider};
15496:                             if (grep(/^\Q$poss\E$/,@{$options{$field}})) {
15497:                                 push(@{$confhash{$provider}{'defaults'}},$poss); 
15498:                             }
15499:                         } elsif ((exists($options{$field})) && (ref($options{$field}) eq 'HASH')) {
15500:                             foreach my $inner (keys(%{$options{$field}})) {
15501:                                 if (ref($options{$field}{$inner}) eq 'ARRAY') {
15502:                                     my $poss = $env{'form.proctoring_'.$inner.'_'.$provider};
15503:                                     if (grep(/^\Q$poss\E$/,@{$options{$field}{$inner}})) {
15504:                                         $confhash{$provider}{'defaults'}{$inner} = $poss;
15505:                                     }
15506:                                 } else {
15507:                                     $confhash{$provider}{'defaults'}{$inner} = $env{'form.proctoring_'.$inner.'_'.$provider};
15508:                                 }
15509:                             }
15510:                         } else {
15511:                             if (grep(/^\Q$field\E$/,@checked)) {
15512:                                 push(@{$confhash{$provider}{'defaults'}},$field);
15513:                             }
15514:                         }
15515:                     }
15516:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
15517:                         if (ref($current{'defaults'}) eq 'ARRAY') {
15518:                             unless ($changes{$provider}) {
15519:                                 my @new = sort(@{$confhash{$provider}{'defaults'}});
15520:                                 my @old = sort(@{$current{'defaults'}});
15521:                                 my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
15522:                                 if (@diffs) {
15523:                                     $changes{$provider} = 1; 
15524:                                 }
15525:                             }
15526:                         } elsif (ref($current{'defaults'}) eq 'ARRAY') {
15527:                             if (@{$current{'defaults'}}) {
15528:                                 $changes{$provider} = 1;
15529:                             }
15530:                         }
15531:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
15532:                         if (ref($current{'defaults'}) eq 'HASH') {
15533:                             unless ($changes{$provider}) {
15534:                                 foreach my $key (keys(%{$confhash{$provider}{'defaults'}})) {
15535:                                     unless ($confhash{$provider}{'defaults'}{$key} eq $current{'defaults'}{$key}) {
15536:                                         $changes{$provider} = 1;
15537:                                         last;
15538:                                     }
15539:                                 }
15540:                             }
15541:                             unless ($changes{$provider}) {
15542:                                 foreach my $key (keys(%{$current{'defaults'}})) {
15543:                                     unless ($current{'defaults'}{$key} eq $confhash{$provider}{'defaults'}{$key}) {
15544:                                         $changes{$provider} = 1;
15545:                                         last;
15546:                                     }
15547:                                 }
15548:                             }
15549:                         } elsif (keys(%{$confhash{$provider}{'defaults'}})) {
15550:                             $changes{$provider} = 1;
15551:                         }
15552:                     }
15553:                 }
15554:             }
15555:             if (ref($crsconf{$provider}) eq 'ARRAY') {
15556:                 if (@{$crsconf{$provider}} > 0) {
15557:                     $confhash{$provider}{'crsconf'} = [];
15558:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_crsconf_'.$provider);
15559:                     foreach my $crsfield (@{$crsconf{$provider}}) {
15560:                         if (grep(/^\Q$crsfield\E$/,@checked)) {
15561:                             push(@{$confhash{$provider}{'crsconf'}},$crsfield);
15562:                         }
15563:                     }
15564:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
15565:                         unless ($changes{$provider}) {  
15566:                             my @new = sort(@{$confhash{$provider}{'crsconf'}});
15567:                             my @old = sort(@{$current{'crsconf'}});
15568:                             my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
15569:                             if (@diffs) {
15570:                                 $changes{$provider} = 1;
15571:                             }
15572:                         }
15573:                     } elsif (@{$confhash{$provider}{'crsconf'}}) {
15574:                         $changes{$provider} = 1;
15575:                     }
15576:                 }
15577:             }
15578:             if ($showroles) {
15579:                 $confhash{$provider}{'roles'} = {};
15580:                 foreach my $role (@courseroles) {
15581:                     my $poss = $env{'form.proctoring_roles_'.$role.'_'.$provider};
15582:                     if (grep(/^\Q$poss\E$/,@ltiroles)) {
15583:                         $confhash{$provider}{'roles'}{$role} = $poss;
15584:                     }
15585:                 }
15586:                 unless ($changes{$provider}) {
15587:                     if (ref($current{'roles'}) eq 'HASH') {
15588:                         foreach my $role (keys(%{$current{'roles'}})) {
15589:                             unless ($current{'roles'}{$role} eq $confhash{$provider}{'roles'}{$role}) {
15590:                                 $changes{$provider} = 1;
15591:                                 last
15592:                             }
15593:                         }
15594:                         unless ($changes{$provider}) {
15595:                             foreach my $role (keys(%{$confhash{$provider}{'roles'}})) {
15596:                                 unless ($confhash{$provider}{'roles'}{$role} eq $current{'roles'}{$role}) {
15597:                                     $changes{$provider} = 1;
15598:                                     last;
15599:                                 }
15600:                             }
15601:                         }
15602:                     } elsif (keys(%{$confhash{$provider}{'roles'}})) {
15603:                         $changes{$provider} = 1;
15604:                     }
15605:                 }
15606:             }
15607:             if (ref($current{'custom'}) eq 'HASH') {
15608:                 my @customdels = &Apache::loncommon::get_env_multiple('form.proctoring_customdel_'.$provider);
15609:                 foreach my $key (keys(%{$current{'custom'}})) {
15610:                     if (grep(/^\Q$key\E$/,@customdels)) {
15611:                         $changes{$provider} = 1;
15612:                     } else {
15613:                         $confhash{$provider}{'custom'}{$key} = $env{'form.proctoring_customval_'.$key.'_'.$provider};
15614:                         if ($confhash{$provider}{'custom'}{$key} ne $current{'custom'}{$key}) {
15615:                             $changes{$provider} = 1;
15616:                         }
15617:                     }
15618:                 }
15619:             }
15620:             if ($customadds{$provider}) {
15621:                 my $name = $env{'form.proctoring_custom_name_'.$provider};
15622:                 $name =~ s/(`)/'/g;
15623:                 $name =~ s/^\s+//;
15624:                 $name =~ s/\s+$//;
15625:                 my $value = $env{'form.proctoring_custom_value_'.$provider};
15626:                 $value =~ s/(`)/'/g;
15627:                 $value =~ s/^\s+//;
15628:                 $value =~ s/\s+$//;
15629:                 if ($name ne '') {
15630:                     $confhash{$provider}{'custom'}{$name} = $value;
15631:                     $changes{$provider} = 1;
15632:                 }
15633:             }
15634:         }
15635:     }
15636:     if (@allpos > 0) {
15637:         my $idx = 0;
15638:         foreach my $provider (@allpos) {
15639:             if ($provider ne '') {
15640:                 $confhash{$provider}{'order'} = $idx;
15641:                 unless ($changes{$provider}) {
15642:                     if (ref($domconfig{$action}) eq 'HASH') {
15643:                         if (ref($domconfig{$action}{$provider}) eq 'HASH') {
15644:                             if ($domconfig{$action}{$provider}{'order'} ne $idx) {
15645:                                 $changes{$provider} = 1;
15646:                             }
15647:                         }
15648:                     }
15649:                 }
15650:                 $idx ++;
15651:             }
15652:         }
15653:     }
15654:     my %proc_hash = (
15655:                           $action => { %confhash }
15656:                        );
15657:     my $putresult = &Apache::lonnet::put_dom('configuration',\%proc_hash,
15658:                                              $dom);
15659:     if ($putresult eq 'ok') {
15660:         my %proc_enchash = (
15661:                              $action => { %encconfhash }
15662:                          );
15663:         &Apache::lonnet::put_dom('encconfig',\%proc_enchash,$dom,undef,1);
15664:         if (keys(%changes) > 0) {
15665:             my $cachetime = 24*60*60;
15666:             my %procall = %confhash;
15667:             foreach my $provider (keys(%procall)) {
15668:                 if (ref($encconfhash{$provider}) eq 'HASH') {
15669:                     foreach my $key ('key','secret') {
15670:                         $procall{$provider}{$key} = $encconfhash{$provider}{$key};
15671:                     }
15672:                 }
15673:             }
15674:             &Apache::lonnet::do_cache_new('proctoring',$dom,\%procall,$cachetime);
15675:             if (ref($lastactref) eq 'HASH') {
15676:                 $lastactref->{'proctoring'} = 1;
15677:             }
15678:             $resulttext = &mt('Configuration for Provider(s) with changes:').'<ul>';
15679:             my %bynum;
15680:             foreach my $provider (sort(keys(%changes))) {
15681:                 my $position = $confhash{$provider}{'order'};
15682:                 $bynum{$position} = $provider;
15683:             }
15684:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
15685:                 my $provider = $bynum{$pos};
15686:                 my %lt = &proctoring_titles($provider);
15687:                 my %fieldtitles = &proctoring_fieldtitles($provider);
15688:                 if (!$confhash{$provider}{'available'}) {
15689:                     $resulttext .= '<li>'.&mt('Proctoring integration unavailable for: [_1]','<b>'.$providernames{$provider}.'</b>').'</li>';
15690:                 } else {
15691:                     $resulttext .= '<li>'.&mt('Proctoring integration available for: [_1]','<b>'.$providernames{$provider}.'</b>');
15692:                     if ($confhash{$provider}{'image'}) {
15693:                         $resulttext .= '&nbsp;'.
15694:                                        '<img src="'.$confhash{$provider}{'image'}.'"'.
15695:                                        ' alt="'.&mt('Proctoring icon').'" />';
15696:                     }
15697:                     $resulttext .= '<ul>';
15698:                     my $position = $pos + 1;
15699:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
15700:                     foreach my $key ('version','sigmethod','url','lifetime') {
15701:                         if ($confhash{$provider}{$key} ne '') {
15702:                             $resulttext .= '<li>'.$lt{$key}.':&nbsp;'.$confhash{$provider}{$key}.'</li>';
15703:                         }
15704:                     }
15705:                     if ($encconfhash{$provider}{'key'} ne '') {
15706:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfhash{$provider}{'key'}.'</li>';
15707:                     }
15708:                     if ($encconfhash{$provider}{'secret'} ne '') {
15709:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
15710:                         my $num = length($encconfhash{$provider}{'secret'});
15711:                         $resulttext .= ('*'x$num).'</li>';
15712:                     }
15713:                     my (@fields,$showroles);
15714:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
15715:                         push(@fields,@{$requserfields{$provider}});
15716:                     }
15717:                     if (ref($confhash{$provider}{'fields'}) eq 'ARRAY') {
15718:                         push(@fields,@{$confhash{$provider}{'fields'}});
15719:                     } elsif (ref($confhash{$provider}{'fields'}) eq 'HASH') {
15720:                         push(@fields,(keys(%{$confhash{$provider}{'fields'}})));
15721:                     }
15722:                     if (@fields) {
15723:                         if (grep(/^roles$/,@fields)) {
15724:                             $showroles = 1;
15725:                         }
15726:                         $resulttext .= '<li>'.$lt{'udsl'}.':&nbsp;"'.
15727:                                        join('", "', map { $lt{$_}; } @fields).'"</li>';
15728:                     }
15729:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
15730:                         if (grep(/^user$/,@{$requserfields{$provider}})) {
15731:                             if ($confhash{$provider}{'incdom'}) {
15732:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'uname:dom'}).'</li>';
15733:                             } else { 
15734:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'username'}).'</li>';
15735:                             }
15736:                         }
15737:                     }
15738:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
15739:                         if (@{$confhash{$provider}{'defaults'}} > 0) {
15740:                             $resulttext .= '<li>'.$lt{'defa'};
15741:                             foreach my $field (@{$confhash{$provider}{'defaults'}}) {
15742:                                 $resulttext .= ' "'.$fieldtitles{$field}.'",';
15743:                             }
15744:                             $resulttext =~ s/,$//;
15745:                             $resulttext .= '</li>';
15746:                         }
15747:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
15748:                         if (keys(%{$confhash{$provider}{'defaults'}})) {
15749:                             $resulttext .= '<li>'.$lt{'defa'}.':&nbsp;<ul>';
15750:                             foreach my $key (sort(keys(%{$confhash{$provider}{'defaults'}}))) {
15751:                                 if ($confhash{$provider}{'defaults'}{$key} ne '') {
15752:                                     $resulttext .= '<li>'.$fieldtitles{$key}.' = '.$confhash{$provider}{'defaults'}{$key}.'</li>';
15753:                                 }
15754:                             }
15755:                             $resulttext .= '</ul></li>';
15756:                         }
15757:                     }
15758:                     if (ref($crsconf{$provider}) eq 'ARRAY') {
15759:                         if (@{$crsconf{$provider}} > 0) {
15760:                             $resulttext .= '<li>'.&mt('Configurable in course:');
15761:                             my $numconfig = 0;
15762:                             if (ref($confhash{$provider}{'crsconf'}) eq 'ARRAY') {
15763:                                 if (@{$confhash{$provider}{'crsconf'}} > 0) {
15764:                                     foreach my $field (@{$confhash{$provider}{'crsconf'}}) {
15765:                                         $numconfig ++;
15766:                                         if ($provider eq 'examity') {
15767:                                             $resulttext .= ' "'.$lt{'crs'.$field}.'",';
15768:                                         } else {
15769:                                             $resulttext .= ' "'.$fieldtitles{$field}.'",';
15770:                                         }
15771:                                     }
15772:                                     $resulttext =~ s/,$//;
15773:                                 }
15774:                             }
15775:                             if (!$numconfig) {
15776:                                 $resulttext .= '&nbsp;'.&mt('None');
15777:                             }
15778:                             $resulttext .= '</li>';
15779:                         }
15780:                     }
15781:                     if ($showroles) {
15782:                         if (ref($confhash{$provider}{'roles'}) eq 'HASH') {
15783:                             my $rolemaps;
15784:                             foreach my $role (@courseroles) {
15785:                                 if ($confhash{$provider}{'roles'}{$role}) {
15786:                                     $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
15787:                                                  $confhash{$provider}{'roles'}{$role}.',';
15788:                                 }
15789:                             }
15790:                             if ($rolemaps) {
15791:                                 $rolemaps =~ s/,$//;
15792:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
15793:                             }
15794:                         }
15795:                     }
15796:                     if (ref($confhash{$provider}{'custom'}) eq 'HASH') {
15797:                         my $customlist;
15798:                         if (keys(%{$confhash{$provider}{'custom'}})) {
15799:                             foreach my $key (sort(keys(%{$confhash{$provider}{'custom'}}))) {
15800:                                 $customlist .= $key.'='.$confhash{$provider}{'custom'}{$key}.', ';
15801:                             }
15802:                             $customlist =~ s/,$//;
15803:                         }
15804:                         if ($customlist) {
15805:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
15806:                         }
15807:                     } 
15808:                     $resulttext .= '</ul></li>';
15809:                 }
15810:             }
15811:             $resulttext .= '</ul>';
15812:         } else {
15813:             $resulttext = &mt('No changes made.');
15814:         }
15815:     } else {
15816:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
15817:     }
15818:     if ($errors) {
15819:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
15820:                        $errors.'</ul>';
15821:     }
15822:     return $resulttext;
15823: }
15824: 
15825: sub process_proctoring_image {
15826:     my ($r,$dom,$confname,$caller,$provider,$configuserok,$switchserver,$author_ok) = @_;
15827:     my $filename = $env{'form.'.$caller.'.filename'};
15828:     my ($error,$url);
15829:     my ($width,$height) = (21,21);
15830:     if ($configuserok eq 'ok') {
15831:         if ($switchserver) {
15832:             $error = &mt('Upload of Remote Proctoring Provider icon is not permitted to this server: [_1]',
15833:                          $switchserver);
15834:         } elsif ($author_ok eq 'ok') {
15835:             my ($result,$imageurl,$madethumb) =
15836:                 &publishlogo($r,'upload',$caller,$dom,$confname,
15837:                              "proctoring/$provider/icon",$width,$height);
15838:             if ($result eq 'ok') {
15839:                 if ($madethumb) {
15840:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
15841:                     my $imagethumb = "$path/tn-".$imagefile;
15842:                     $url = $imagethumb;
15843:                 } else {
15844:                     $url = $imageurl;
15845:                 }
15846:             } else {
15847:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
15848:             }
15849:         } else {
15850:             $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);
15851:         }
15852:     } else {
15853:         $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);
15854:     }
15855:     return ($url,$error);
15856: }
15857: 
15858: sub modify_lti {
15859:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
15860:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15861:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
15862:     my (%posslti,%posslticrs,%posscrstype);
15863:     my @courseroles = ('cc','in','ta','ep','st');
15864:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
15865:     my @lticourseroles = qw(Instructor TeachingAssistant Mentor Learner);
15866:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
15867:     my %coursetypetitles = &Apache::lonlocal::texthash (
15868:                                official   => 'Official',
15869:                                unofficial => 'Unofficial',
15870:                                community  => 'Community',
15871:                                textbook   => 'Textbook',
15872:                                placement  => 'Placement Test',
15873:                                lti        => 'LTI Provider',
15874:     );
15875:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
15876:     my %lt = &lti_names();
15877:     map { $posslti{$_} = 1; } @ltiroles;
15878:     map { $posslticrs{$_} = 1; } @lticourseroles;
15879:     map { $posscrstype{$_} = 1; } @coursetypes;
15880: 
15881:     my %menutitles = &ltimenu_titles();
15882: 
15883:     my (%currltisec,%secchanges,%newltisec,%newltienc,%keyset,%newkeyset);
15884:     $newltisec{'private'}{'keys'} = [];
15885:     $newltisec{'encrypt'} = {};
15886:     $newltisec{'rules'} = {};
15887:     $newltisec{'linkprot'} = {};
15888:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
15889:         %currltisec = %{$domconfig{'ltisec'}};
15890:         if (ref($currltisec{'linkprot'}) eq 'HASH') {
15891:             foreach my $id (keys(%{$currltisec{'linkprot'}})) {
15892:                 unless ($id =~ /^\d+$/) {
15893:                     delete($currltisec{'linkprot'}{$id});
15894:                 }
15895:             }
15896:         }
15897:         if (ref($currltisec{'private'}) eq 'HASH') {
15898:             if (ref($currltisec{'private'}{'keys'}) eq 'ARRAY') {
15899:                 $newltisec{'private'}{'keys'} = $currltisec{'private'}{'keys'};
15900:                 map { $keyset{$_} = 1; } @{$currltisec{'private'}{'keys'}};
15901:             }
15902:         }
15903:     }
15904:     foreach my $item ('crs','dom','consumers') {
15905:         my $formelement;
15906:         if ($item eq 'consumers') { 
15907:             $formelement = 'form.ltisec_'.$item;
15908:         } else {
15909:             $formelement = 'form.ltisec_'.$item.'linkprot';
15910:         }
15911:         if ($env{$formelement}) {
15912:             $newltisec{'encrypt'}{$item} = 1;
15913:             if (ref($currltisec{'encrypt'}) eq 'HASH') {
15914:                 unless ($currltisec{'encrypt'}{$item}) {
15915:                     $secchanges{'encrypt'} = 1;
15916:                 }
15917:             } else {
15918:                 $secchanges{'encrypt'} = 1;
15919:             }
15920:         } elsif (ref($currltisec{'encrypt'}) eq 'HASH') {
15921:             if ($currltisec{'encrypt'}{$item}) {
15922:                 $secchanges{'encrypt'} = 1;
15923:             }
15924:         }
15925:     }
15926:     unless (exists($currltisec{'rules'})) {
15927:         $currltisec{'rules'} = {};
15928:     }
15929:     &password_rule_changes('secrets',$newltisec{'rules'},$currltisec{'rules'},\%secchanges);
15930: 
15931:     my @ids=&Apache::lonnet::current_machine_ids();
15932:     my %servers = &Apache::lonnet::get_servers($dom,'library');
15933:    
15934:     foreach my $hostid (keys(%servers)) {
15935:         if (($hostid ne '') && (grep(/^\Q$hostid\E$/,@ids))) {
15936:             my $newkey;
15937:             my $keyitem = 'form.ltisec_privkey_'.$hostid;
15938:             if (exists($env{$keyitem})) {
15939:                 $env{$keyitem} =~ s/(`)/'/g;
15940:                 if ($keyset{$hostid}) {
15941:                     if ($env{'form.ltisec_changeprivkey_'.$hostid}) {
15942:                         if ($env{$keyitem} ne '') {
15943:                             $secchanges{'private'} = 1;
15944:                             $newkeyset{$hostid} = $env{$keyitem};
15945:                         }
15946:                     }
15947:                 } elsif ($env{$keyitem} ne '') {
15948:                     unless (grep(/^\Q$hostid\E$/,@{$newltisec{'private'}{'keys'}})) { 
15949:                         push(@{$newltisec{'private'}{'keys'}},$hostid);
15950:                     }
15951:                     $secchanges{'private'} = 1;
15952:                     $newkeyset{$hostid} = $env{$keyitem};
15953:                 }
15954:             }
15955:         }
15956:     }
15957: 
15958:     my (%linkprotchg,$linkprotoutput,$is_home);
15959:     my $proterror = &Apache::courseprefs::process_linkprot($dom,'',$currltisec{'linkprot'},
15960:                                                            \%linkprotchg,'domain');
15961:     my $home = &Apache::lonnet::domain($dom,'primary');
15962:     unless (($home eq 'no_host') || ($home eq '')) {
15963:         my @ids=&Apache::lonnet::current_machine_ids();
15964:         foreach my $id (@ids) { if ($id eq $home) { $is_home=1; } }
15965:     }
15966: 
15967:     if (keys(%linkprotchg)) {
15968:         $secchanges{'linkprot'} = 1;
15969:         my %oldlinkprot;
15970:         if (ref($currltisec{'linkprot'}) eq 'HASH') {
15971:             %oldlinkprot = %{$currltisec{'linkprot'}};
15972:         }
15973:         foreach my $id (keys(%linkprotchg)) {
15974:             if (ref($linkprotchg{$id}) eq 'HASH') {
15975:                 foreach my $inner (keys(%{$linkprotchg{$id}})) {
15976:                     if (($inner eq 'secret') || ($inner eq 'key')) {
15977:                         if ($is_home) {
15978:                             $newltienc{$id}{$inner} = $linkprotchg{$id}{$inner};
15979:                         }
15980:                     }
15981:                 }
15982:             } else {
15983:                 $newltisec{'linkprot'}{$id} = $linkprotchg{$id};
15984:             }
15985:         }
15986:         $linkprotoutput = &Apache::courseprefs::store_linkprot($dom,'','domain',\%linkprotchg,\%oldlinkprot);
15987:         if (keys(%linkprotchg)) {
15988:             %{$newltisec{'linkprot'}} = %linkprotchg;
15989:         }
15990:     }
15991:     if (ref($currltisec{'linkprot'}) eq 'HASH') {
15992:         foreach my $id (%{$currltisec{'linkprot'}}) {
15993:             next if ($id !~ /^\d+$/);
15994:             unless (exists($linkprotchg{$id})) {
15995:                 if (ref($currltisec{'linkprot'}{$id}) eq 'HASH') {
15996:                     foreach my $inner (keys(%{$currltisec{'linkprot'}{$id}})) {
15997:                         if (($inner eq 'secret') || ($inner eq 'key')) {
15998:                             if ($is_home) {
15999:                                 $newltienc{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
16000:                             }
16001:                         } else {
16002:                             $newltisec{'linkprot'}{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
16003:                         }
16004:                     }
16005:                 } else {
16006:                     $newltisec{'linkprot'}{$id} = $currltisec{'linkprot'}{$id};
16007:                 }
16008:             }
16009:         }
16010:     }
16011:     if ($proterror) {
16012:         $errors .= '<li>'.$proterror.'</li>';
16013:     }
16014:     my (@items,%deletions,%itemids);
16015:     if ($env{'form.lti_add'}) {
16016:         my $consumer = $env{'form.lti_consumer_add'};
16017:         $consumer =~ s/(`)/'/g;
16018:         ($newid,my $error) = &get_lti_id($dom,$consumer);
16019:         if ($newid) {
16020:             $itemids{'add'} = $newid;
16021:             push(@items,'add');
16022:             $changes{$newid} = 1;
16023:         } else {
16024:             my $error = &mt('Failed to acquire unique ID for new LTI configuration');
16025:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
16026:         }
16027:     }
16028:     if (ref($domconfig{$action}) eq 'HASH') {
16029:         my @todelete = &Apache::loncommon::get_env_multiple('form.lti_del');
16030:         if (@todelete) {
16031:             map { $deletions{$_} = 1; } @todelete;
16032:         }
16033:         my $maxnum = $env{'form.lti_maxnum'};
16034:         for (my $i=0; $i<$maxnum; $i++) {
16035:             my $itemid = $env{'form.lti_id_'.$i};
16036:             $itemid =~ s/\D+//g;
16037:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
16038:                 if ($deletions{$itemid}) {
16039:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'consumer'};
16040:                 } else {
16041:                     push(@items,$i);
16042:                     $itemids{$i} = $itemid;
16043:                 }
16044:             }
16045:         }
16046:     }
16047:     foreach my $idx (@items) {
16048:         my $itemid = $itemids{$idx};
16049:         next unless ($itemid);
16050:         my $position = $env{'form.lti_pos_'.$itemid};
16051:         $position =~ s/\D+//g;
16052:         if ($position ne '') {
16053:             $allpos[$position] = $itemid;
16054:         }
16055:         foreach my $item ('consumer','key','secret','lifetime','requser','crsinc') {
16056:             my $formitem = 'form.lti_'.$item.'_'.$idx;
16057:             $env{$formitem} =~ s/(`)/'/g;
16058:             if ($item eq 'lifetime') {
16059:                 $env{$formitem} =~ s/[^\d.]//g;
16060:             }
16061:             if ($env{$formitem} ne '') {
16062:                 if (($item eq 'key') || ($item eq 'secret')) {
16063:                     $encconfig{$itemid}{$item} = $env{$formitem};
16064:                 } else {
16065:                     $confhash{$itemid}{$item} = $env{$formitem};
16066:                     unless (($idx eq 'add') || ($changes{$itemid})) {
16067:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
16068:                             $changes{$itemid} = 1;
16069:                         }
16070:                     }
16071:                 }
16072:             }
16073:         }
16074:         if ($env{'form.lti_version_'.$idx} eq 'LTI-1p0') {
16075:             $confhash{$itemid}{'version'} = $env{'form.lti_version_'.$idx};
16076:         }
16077:         if ($confhash{$itemid}{'requser'}) {
16078:             if ($env{'form.lti_mapuser_'.$idx} eq 'sourcedid') {
16079:                 $confhash{$itemid}{'mapuser'} = 'lis_person_sourcedid';
16080:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'email') {
16081:                 $confhash{$itemid}{'mapuser'} = 'lis_person_contact_email_primary';
16082:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'other') {
16083:                 my $mapuser = $env{'form.lti_customuser_'.$idx};
16084:                 $mapuser =~ s/(`)/'/g;
16085:                 $mapuser =~ s/^\s+|\s+$//g;
16086:                 $confhash{$itemid}{'mapuser'} = $mapuser;
16087:             }
16088:             my @possmakeuser = &Apache::loncommon::get_env_multiple('form.lti_makeuser_'.$idx);
16089:             my @makeuser;
16090:             foreach my $ltirole (sort(@possmakeuser)) {
16091:                 if ($posslti{$ltirole}) {
16092:                     push(@makeuser,$ltirole);
16093:                 }
16094:             }
16095:             $confhash{$itemid}{'makeuser'} = \@makeuser;
16096:             if (@makeuser) {
16097:                 my $lcauth = $env{'form.lti_lcauth_'.$idx};
16098:                 if ($lcauth =~ /^(internal|krb4|krb5|localauth)$/) {
16099:                     $confhash{$itemid}{'lcauth'} = $lcauth;
16100:                     if ($lcauth ne 'internal') {
16101:                         my $lcauthparm = $env{'form.lti_lcauthparm_'.$idx};
16102:                         $lcauthparm =~ s/^(\s+|\s+)$//g;
16103:                         $lcauthparm =~ s/`//g;
16104:                         if ($lcauthparm ne '') {
16105:                             $confhash{$itemid}{'lcauthparm'} = $lcauthparm;
16106:                         }
16107:                     }
16108:                 } else {
16109:                     $confhash{$itemid}{'lcauth'} = 'lti';
16110:                 }
16111:             }
16112:             my @possinstdata =  &Apache::loncommon::get_env_multiple('form.lti_instdata_'.$idx);
16113:             if (@possinstdata) {
16114:                 foreach my $field (@possinstdata) {
16115:                     if (exists($fieldtitles{$field})) {
16116:                         push(@{$confhash{$itemid}{'instdata'}});
16117:                     }
16118:                 }
16119:             }
16120:             if ($env{'form.lti_callback_'.$idx}) {
16121:                 if ($env{'form.lti_callbackparam_'.$idx}) {
16122:                     my $callback = $env{'form.lti_callbackparam_'.$idx};
16123:                     $callback =~ s/^\s+|\s+$//g;
16124:                     $confhash{$itemid}{'callback'} = $callback;
16125:                 }
16126:             }
16127:             foreach my $field ('topmenu','inlinemenu') {
16128:                 if ($env{'form.lti_'.$field.'_'.$idx}) {
16129:                     $confhash{$itemid}{$field} = 1;
16130:                 }
16131:             }
16132:             if ($env{'form.lti_topmenu_'.$idx} || $env{'form.lti_inlinemenu_'.$idx}) {
16133:                 $confhash{$itemid}{lcmenu} = [];
16134:                 my @possmenu = &Apache::loncommon::get_env_multiple('form.lti_menuitem_'.$idx);
16135:                 foreach my $field (@possmenu) {
16136:                     if (exists($menutitles{$field})) {
16137:                         if ($field eq 'grades') {
16138:                             next unless ($env{'form.lti_inlinemenu_'.$idx});
16139:                         }
16140:                         push(@{$confhash{$itemid}{lcmenu}},$field);
16141:                     }
16142:                 }
16143:             }
16144:             if ($confhash{$itemid}{'crsinc'}) {
16145:                 if (($env{'form.lti_mapcrs_'.$idx} eq 'course_offering_sourcedid') ||
16146:                     ($env{'form.lti_mapcrs_'.$idx} eq 'context_id'))  {
16147:                     $confhash{$itemid}{'mapcrs'} = $env{'form.lti_mapcrs_'.$idx};
16148:                 } elsif ($env{'form.lti_mapcrs_'.$idx} eq 'other') {
16149:                     my $mapcrs = $env{'form.lti_mapcrsfield_'.$idx}; 
16150:                     $mapcrs =~ s/(`)/'/g;
16151:                     $mapcrs =~ s/^\s+|\s+$//g;
16152:                     $confhash{$itemid}{'mapcrs'} = $mapcrs;
16153:                 }
16154:                 my @posstypes = &Apache::loncommon::get_env_multiple('form.lti_mapcrstype_'.$idx);
16155:                 my @crstypes;
16156:                 foreach my $type (sort(@posstypes)) {
16157:                     if ($posscrstype{$type}) {
16158:                         push(@crstypes,$type);
16159:                     }
16160:                 }
16161:                 $confhash{$itemid}{'mapcrstype'} = \@crstypes;
16162:                 if ($env{'form.lti_storecrs_'.$idx}) {
16163:                     $confhash{$itemid}{'storecrs'} = 1;
16164:                 }       
16165:                 if ($env{'form.lti_makecrs_'.$idx}) {
16166:                     $confhash{$itemid}{'makecrs'} = 1;
16167:                 }
16168:                 foreach my $ltirole (@lticourseroles) {
16169:                     my $possrole = $env{'form.lti_maprole_'.$ltirole.'_'.$idx};
16170:                     if (grep(/^\Q$possrole\E$/,@courseroles)) {
16171:                         $confhash{$itemid}{'maproles'}{$ltirole} = $possrole;
16172:                     }
16173:                 }
16174:                 my @possenroll = &Apache::loncommon::get_env_multiple('form.lti_selfenroll_'.$idx);
16175:                 my @selfenroll;
16176:                 foreach my $type (sort(@possenroll)) {
16177:                     if ($posslticrs{$type}) {
16178:                         push(@selfenroll,$type);
16179:                     }
16180:                 }
16181:                 $confhash{$itemid}{'selfenroll'} = \@selfenroll;
16182:                 if ($env{'form.lti_crssec_'.$idx}) {
16183:                     if ($env{'form.lti_crssecsrc_'.$idx} eq 'course_section_sourcedid') {
16184:                         $confhash{$itemid}{'section'} = $env{'form.lti_crssecsrc_'.$idx};
16185:                     } elsif ($env{'form.lti_crssecsrc_'.$idx} eq 'other') {
16186:                         my $section = $env{'form.lti_customsection_'.$idx};
16187:                         $section =~ s/(`)/'/g;
16188:                         $section =~ s/^\s+|\s+$//g;
16189:                         if ($section ne '') {
16190:                             $confhash{$itemid}{'section'} = $section;
16191:                         }
16192:                     }
16193:                 }
16194:                 foreach my $field ('passback','roster') {
16195:                     if ($env{'form.lti_'.$field.'_'.$idx}) {
16196:                         $confhash{$itemid}{$field} = 1;
16197:                     }
16198:                 }
16199:                 if ($env{'form.lti_passback_'.$idx}) {
16200:                     if ($env{'form.lti_passbackformat_'.$idx} eq '1.0') {
16201:                         $confhash{$itemid}{'passbackformat'} = '1.0';
16202:                     } else {
16203:                         $confhash{$itemid}{'passbackformat'} = '1.1';
16204:                     }
16205:                 }
16206:             }
16207:             unless (($idx eq 'add') || ($changes{$itemid})) {
16208:                 if ($confhash{$itemid}{'crsinc'}) {
16209:                     foreach my $field ('mapcrs','storecrs','makecrs','section','passback','roster') {
16210:                         if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
16211:                             $changes{$itemid} = 1;
16212:                         }
16213:                     }
16214:                     unless ($changes{$itemid}) {
16215:                         if ($domconfig{$action}{$itemid}{'passback'} eq $confhash{$itemid}{'passback'}) {
16216:                             if ($domconfig{$action}{$itemid}{'passbackformat'} ne $confhash{$itemid}{'passbackformat'}) {
16217:                                 $changes{$itemid} = 1;
16218:                             }
16219:                         }
16220:                     }
16221:                     foreach my $field ('mapcrstype','selfenroll') {
16222:                         unless ($changes{$itemid}) {
16223:                             if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
16224:                                 if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16225:                                     my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
16226:                                                                                    $confhash{$itemid}{$field});
16227:                                     if (@diffs) {
16228:                                         $changes{$itemid} = 1;
16229:                                     }
16230:                                 } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
16231:                                     $changes{$itemid} = 1;
16232:                                 }
16233:                             } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16234:                                 if (@{$confhash{$itemid}{$field}} > 0) {
16235:                                     $changes{$itemid} = 1;
16236:                                 }
16237:                             }
16238:                         }
16239:                     }
16240:                     unless ($changes{$itemid}) {
16241:                         if (ref($domconfig{$action}{$itemid}{'maproles'}) eq 'HASH') {
16242:                             if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
16243:                                 foreach my $ltirole (keys(%{$domconfig{$action}{$itemid}{'maproles'}})) {
16244:                                     if ($domconfig{$action}{$itemid}{'maproles'}{$ltirole} ne 
16245:                                         $confhash{$itemid}{'maproles'}{$ltirole}) {
16246:                                         $changes{$itemid} = 1;
16247:                                         last;
16248:                                     }
16249:                                 }
16250:                                 unless ($changes{$itemid}) {
16251:                                     foreach my $ltirole (keys(%{$confhash{$itemid}{'maproles'}})) {
16252:                                         if ($confhash{$itemid}{'maproles'}{$ltirole} ne 
16253:                                             $domconfig{$action}{$itemid}{'maproles'}{$ltirole}) {
16254:                                             $changes{$itemid} = 1;
16255:                                             last;
16256:                                         }
16257:                                     }
16258:                                 }
16259:                             } elsif (keys(%{$domconfig{$action}{$itemid}{'maproles'}}) > 0) {
16260:                                 $changes{$itemid} = 1;
16261:                             }
16262:                         } elsif (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
16263:                             unless ($changes{$itemid}) {
16264:                                 if (keys(%{$confhash{$itemid}{'maproles'}}) > 0) {
16265:                                     $changes{$itemid} = 1;
16266:                                 }
16267:                             }
16268:                         }
16269:                     }
16270:                 }
16271:                 unless ($changes{$itemid}) {
16272:                     foreach my $field ('mapuser','lcauth','lcauthparm','topmenu','inlinemenu','callback') {
16273:                         if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
16274:                             $changes{$itemid} = 1;
16275:                         }
16276:                     }
16277:                     unless ($changes{$itemid}) {
16278:                         foreach my $field ('makeuser','lcmenu') {
16279:                             if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
16280:                                 if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16281:                                     my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
16282:                                                                                    $confhash{$itemid}{$field});
16283:                                     if (@diffs) {
16284:                                         $changes{$itemid} = 1;
16285:                                     }
16286:                                 } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
16287:                                     $changes{$itemid} = 1;
16288:                                 }
16289:                             } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16290:                                 if (@{$confhash{$itemid}{$field}} > 0) {
16291:                                     $changes{$itemid} = 1;
16292:                                 }
16293:                             }
16294:                         }
16295:                     }
16296:                 }
16297:             }
16298:         }
16299:     }
16300:     if (@allpos > 0) {
16301:         my $idx = 0;
16302:         foreach my $itemid (@allpos) {
16303:             if ($itemid ne '') {
16304:                 $confhash{$itemid}{'order'} = $idx;
16305:                 if (ref($domconfig{$action}) eq 'HASH') {
16306:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
16307:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
16308:                             $changes{$itemid} = 1;
16309:                         }
16310:                     }
16311:                 }
16312:                 $idx ++;
16313:             }
16314:         }
16315:     }
16316:     my %ltihash = (
16317:                       $action => { %confhash }
16318:                   );
16319:     my %ltienchash = (
16320:                          $action => { %encconfig }
16321:                      );
16322:     if (keys(%secchanges)) {
16323:         $ltihash{'ltisec'} = \%newltisec;
16324:         if ($secchanges{'linkprot'}) {
16325:             if ($is_home) {
16326:                 $ltienchash{'linkprot'} = \%newltienc;
16327:             }
16328:         }
16329:     }
16330:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,$dom);
16331:     if ($putresult eq 'ok') {
16332:         my %keystore;
16333:         if (keys(%secchanges)) {
16334:             if ($secchanges{'private'}) {
16335:                 my $who = &escape($env{'user.name'}.':'.$env{'user.domain'});
16336:                 foreach my $hostid (keys(%newkeyset)) {
16337:                     my $storehash = {
16338:                                        key => $newkeyset{$hostid},
16339:                                        who => $env{'user.name'}.':'.$env{'user.domain'},
16340:                                     };
16341:                     $keystore{$hostid} = &Apache::lonnet::store_dom($storehash,'lti','private',
16342:                                                                     $dom,$hostid);
16343:                 }
16344:             }
16345:             if (ref($lastactref) eq 'HASH') {
16346:                 if (($secchanges{'encrypt'}) || ($secchanges{'private'})) {
16347:                     $lastactref->{'domdefaults'} = 1;
16348:                 }
16349:             }
16350:         }
16351:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
16352:         if ((keys(%changes) == 0) && (keys(%secchanges) == 0)) {
16353:             return &mt('No changes made.');
16354:         }
16355:         $resulttext = &mt('Changes made:').'<ul>';
16356:         if (keys(%secchanges) > 0) {
16357:             foreach my $item (keys(%secchanges)) {
16358:                 if ($item eq 'encrypt') {
16359:                     my %encrypted = (
16360:                               crs  => {
16361:                                         on => &mt('Encryption of stored link protection secrets defined in courses enabled'),
16362:                                         off => &mt('Encryption of stored link protection secrets defined in courses disabled'),
16363:                                       },
16364:                               dom => {
16365:                                        on => &mt('Encryption of stored link protection secrets defined in domain enabled'),
16366:                                        off => &mt('Encryption of stored link protection secrets defined in domain disabled'),
16367:                                      },
16368:                               consumers => {
16369:                                              on => &mt('Encryption of stored consumer secrets defined in domain enabled'),
16370:                                              off => &mt('Encryption of stored consumer secrets defined in domain disabled'),
16371:                                            },
16372:                             );
16373:                     foreach my $type ('crs','dom','consumers') {
16374:                         my $shown = $encrypted{$type}{'off'};
16375:                         if (ref($newltisec{$item}) eq 'HASH') {
16376:                             if ($newltisec{$item}{$type}) {
16377:                                 $shown = $encrypted{$type}{'on'}; 
16378:                             }
16379:                         }
16380:                         $resulttext .= '<li>'.$shown.'</li>';
16381:                     } 
16382:                 } elsif ($item eq 'rules') {
16383:                      my %titles = &Apache::lonlocal::texthash(
16384:                                       min   => 'Minimum password length',
16385:                                       max   => 'Maximum password length',
16386:                                       chars => 'Required characters',
16387:                      );
16388:                      foreach my $rule ('min','max') {
16389:                          if ($newltisec{rules}{$rule} eq '') {
16390:                              if ($rule eq 'min') {
16391:                                  $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
16392:                                                 ' '.&mt('Default of [_1] will be used',
16393:                                                             $Apache::lonnet::passwdmin).'</li>';
16394:                              } else {
16395:                                  $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
16396:                              }
16397:                          } else {
16398:                              $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$newltisec{rules}{$rule}).'</li>';
16399:                          }
16400:                      }
16401:                      if (ref($newltisec{'rules'}{'chars'}) eq 'ARRAY') {
16402:                          if (@{$newltisec{'rules'}{'chars'}} > 0) {
16403:                              my %rulenames = &Apache::lonlocal::texthash(
16404:                                                  uc => 'At least one upper case letter',
16405:                                                  lc => 'At least one lower case letter',
16406:                                                  num => 'At least one number',
16407:                                                  spec => 'At least one non-alphanumeric',
16408:                                              );
16409:                              my $needed = '<ul><li>'.
16410:                                           join('</li><li>',map {$rulenames{$_} } @{$newltisec{'rules'}{'chars'}}).
16411:                                           '</li></ul>';
16412:                              $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
16413:                          } else {
16414:                              $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
16415:                          }
16416:                      } else {
16417:                          $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
16418:                      }
16419:                 } elsif ($item eq 'private') {
16420:                     if (keys(%newkeyset)) {
16421:                         foreach my $hostid (sort(keys(%newkeyset))) {
16422:                             if ($keystore{$hostid} eq 'ok') {
16423:                                 $resulttext .= '<li>'.&mt('Encryption key for storage of shared secrets saved for [_1]',$hostid).'</li>';
16424:                             }
16425:                         }
16426:                     }
16427:                 } elsif ($item eq 'linkprot') {
16428:                     $resulttext .= $linkprotoutput;
16429:                 }
16430:             }
16431:         }
16432:         if (keys(%changes) > 0) {
16433:             my $cachetime = 24*60*60;
16434:             my %ltiall = %confhash;
16435:             foreach my $id (keys(%ltiall)) {
16436:                 if (ref($encconfig{$id}) eq 'HASH') {
16437:                     foreach my $item ('key','secret') {
16438:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
16439:                     }
16440:                 }
16441:             }
16442:             &Apache::lonnet::do_cache_new('lti',$dom,\%ltiall,$cachetime);
16443:             if (ref($lastactref) eq 'HASH') {
16444:                 $lastactref->{'lti'} = 1;
16445:             }
16446:             my %bynum;
16447:             foreach my $itemid (sort(keys(%changes))) {
16448:                 my $position = $confhash{$itemid}{'order'};
16449:                 $bynum{$position} = $itemid;
16450:             }
16451:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
16452:                 my $itemid = $bynum{$pos};
16453:                 if (ref($confhash{$itemid}) ne 'HASH') {
16454:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
16455:                 } else {
16456:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'consumer'}.'</b><ul>';
16457:                     my $position = $pos + 1;
16458:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
16459:                     foreach my $item ('version','lifetime') {
16460:                         if ($confhash{$itemid}{$item} ne '') {
16461:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
16462:                         }
16463:                     }
16464:                     if ($encconfig{$itemid}{'key'} ne '') {
16465:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
16466:                     }
16467:                     if ($encconfig{$itemid}{'secret'} ne '') {
16468:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
16469:                         my $num = length($encconfig{$itemid}{'secret'});
16470:                         $resulttext .= ('*'x$num).'</li>';
16471:                     }
16472:                     if ($confhash{$itemid}{'requser'}) {
16473:                         if ($confhash{$itemid}{'callback'}) {
16474:                             $resulttext .= '<li>'.&mt('Callback setting').': '.$confhash{$itemid}{'callback'}.'</li>';
16475:                         } else {
16476:                             $resulttext .= '<li>'.&mt('Callback to logout LON-CAPA on log out from Consumer').'</li>';
16477:                         }
16478:                         if ($confhash{$itemid}{'mapuser'}) {
16479:                             my $shownmapuser;
16480:                             if ($confhash{$itemid}{'mapuser'} eq 'lis_person_sourcedid') {
16481:                                 $shownmapuser = $lt{'sourcedid'}.' (lis_person_sourcedid)';
16482:                             } elsif ($confhash{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') {
16483:                                 $shownmapuser = $lt{'email'}.' (lis_person_contact_email_primary)';
16484:                             } else {
16485:                                 $shownmapuser = &mt('Other').' ('.$confhash{$itemid}{'mapuser'}.')';
16486:                             }
16487:                             $resulttext .= '<li>'.&mt('LON-CAPA username').': '.$shownmapuser.'</li>';
16488:                         }
16489:                         if (ref($confhash{$itemid}{'makeuser'}) eq 'ARRAY') {
16490:                             if (@{$confhash{$itemid}{'makeuser'}} > 0) { 
16491:                                 $resulttext .= '<li>'.&mt('Following roles may create user accounts: [_1]',
16492:                                                           join(', ',@{$confhash{$itemid}{'makeuser'}})).'<br />';
16493:                                 if ($confhash{$itemid}{'lcauth'} eq 'lti') {
16494:                                     $resulttext .= &mt('New users will only be able to authenticate via LTI').'</li>';
16495:                                 } else {
16496:                                     $resulttext .= &mt('New users will be assigned LON-CAPA authentication: [_1]',
16497:                                                        $confhash{$itemid}{'lcauth'});
16498:                                     if ($confhash{$itemid}{'lcauth'} eq 'internal') {
16499:                                         $resulttext .= '; '.&mt('a randomly generated password will be created');
16500:                                     } elsif ($confhash{$itemid}{'lcauth'} eq 'localauth') {
16501:                                         if ($confhash{$itemid}{'lcauthparm'} ne '') {
16502:                                             $resulttext .= ' '.&mt('with argument: [_1]',$confhash{$itemid}{'lcauthparm'});
16503:                                         }
16504:                                     } else {
16505:                                         $resulttext .= '; '.&mt('Kerberos domain: [_1]',$confhash{$itemid}{'lcauthparm'});
16506:                                     }
16507:                                 }
16508:                                 $resulttext .= '</li>';
16509:                             } else {
16510:                                 $resulttext .= '<li>'.&mt('User account creation not permitted.').'</li>';
16511:                             }
16512:                         }
16513:                         if (ref($confhash{$itemid}{'instdata'}) eq 'ARRAY') {
16514:                             if (@{$confhash{$itemid}{'instdata'}} > 0) {
16515:                                 $resulttext .= '<li>'.&mt('Institutional data will be used when creating a new user for: [_1]',
16516:                                                           join(', ',map { $fieldtitles{$_}; } @{$confhash{$itemid}{'instdata'}})).'</li>';
16517:                             } else {
16518:                                 $resulttext .= '<li>'.&mt('No institutional data used when creating a new user.').'</li>';
16519:                             }
16520:                         }
16521:                         foreach my $item ('topmenu','inlinemenu') {
16522:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
16523:                             if ($confhash{$itemid}{$item}) {
16524:                                 $resulttext .= &mt('Yes');
16525:                             } else {
16526:                                 $resulttext .= &mt('No');
16527:                             }
16528:                             $resulttext .= '</li>';
16529:                         }
16530:                         if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
16531:                             if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
16532:                                 $resulttext .= '<li>'.&mt('Menu items:').' '.
16533:                                                join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>';
16534:                             } else {
16535:                                 $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>';
16536:                             }
16537:                         }
16538:                         if ($confhash{$itemid}{'crsinc'}) {
16539:                             if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
16540:                                 my $rolemaps;
16541:                                 foreach my $role (@ltiroles) {
16542:                                     if ($confhash{$itemid}{'maproles'}{$role}) {
16543:                                         $rolemaps .= ('&nbsp;'x2).$role.'='.
16544:                                                      &Apache::lonnet::plaintext($confhash{$itemid}{'maproles'}{$role},
16545:                                                                                 'Course').',';
16546:                                     }
16547:                                 }
16548:                                 if ($rolemaps) {
16549:                                     $rolemaps =~ s/,$//;
16550:                                     $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
16551:                                 }
16552:                             }
16553:                             if ($confhash{$itemid}{'mapcrs'}) {
16554:                                 $resulttext .= '<li>'.&mt('Unique course identifier').': '.$confhash{$itemid}{'mapcrs'}.'</li>';
16555:                             }
16556:                             if (ref($confhash{$itemid}{'mapcrstype'}) eq 'ARRAY') {
16557:                                 if (@{$confhash{$itemid}{'mapcrstype'}} > 0) {
16558:                                     $resulttext .= '<li>'.&mt('Mapping for the following LON-CAPA course types: [_1]',
16559:                                                    join(', ',map { $coursetypetitles{$_}; } @coursetypes)).
16560:                                                    '</li>';
16561:                                 } else {
16562:                                     $resulttext .= '<li>'.&mt('No mapping to LON-CAPA courses').'</li>';
16563:                                 }
16564:                             }
16565:                             if ($confhash{$itemid}{'storecrs'}) {
16566:                                 $resulttext .= '<li>'.&mt('Store mapping of course identifier to LON-CAPA CourseID').': '.$confhash{$itemid}{'storecrs'}.'</li>';
16567:                             }
16568:                             if ($confhash{$itemid}{'makecrs'}) {
16569:                                 $resulttext .= '<li>'.&mt('Instructor may create course (if absent).').'</li>';
16570:                             } else {
16571:                                 $resulttext .= '<li>'.&mt('Instructor may not create course (if absent).').'</li>';
16572:                             }
16573:                             if (ref($confhash{$itemid}{'selfenroll'}) eq 'ARRAY') {
16574:                                 if (@{$confhash{$itemid}{'selfenroll'}} > 0) {
16575:                                     $resulttext .= '<li>'.&mt('Self-enrollment for following roles: [_1]',
16576:                                                               join(', ',@{$confhash{$itemid}{'selfenroll'}})).
16577:                                                    '</li>';
16578:                                 } else {
16579:                                     $resulttext .= '<li>'.&mt('Self-enrollment not permitted').'</li>';
16580:                                 }
16581:                             }
16582:                             if ($confhash{$itemid}{'section'}) {
16583:                                 if ($confhash{$itemid}{'section'} eq 'course_section_sourcedid') {
16584:                                     $resulttext .= '<li>'.&mt('User section from standard field:').
16585:                                                          ' (course_section_sourcedid)'.'</li>';  
16586:                                 } else {
16587:                                     $resulttext .= '<li>'.&mt('User section from:').' '.
16588:                                                           $confhash{$itemid}{'section'}.'</li>';
16589:                                 }
16590:                             } else {
16591:                                 $resulttext .= '<li>'.&mt('No section assignment').'</li>';
16592:                             }
16593:                             foreach my $item ('passback','roster','topmenu','inlinemenu') {
16594:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
16595:                                 if ($confhash{$itemid}{$item}) {
16596:                                     $resulttext .= &mt('Yes');
16597:                                     if ($item eq 'passback') {
16598:                                         if ($confhash{$itemid}{'passbackformat'} eq '1.0') {
16599:                                             $resulttext .= '&nbsp;('.&mt('Outcomes Extension (1.0)').')';
16600:                                         } elsif ($confhash{$itemid}{'passbackformat'} eq '1.1') {
16601:                                             $resulttext .= '&nbsp;('.&mt('Outcomes Service (1.1)').')';
16602:                                         }
16603:                                     }
16604:                                 } else {
16605:                                     $resulttext .= &mt('No');
16606:                                 }
16607:                                 $resulttext .= '</li>';
16608:                             }
16609:                             if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
16610:                                 if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
16611:                                     $resulttext .= '<li>'.&mt('Menu items:').' '.
16612:                                                    join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>'; 
16613:                                 } else {
16614:                                     $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>'; 
16615:                                 }
16616:                             }
16617:                         }
16618:                     }
16619:                     $resulttext .= '</ul></li>';
16620:                 }
16621:             }
16622:         }
16623:         $resulttext .= '</ul>';
16624:     } else {
16625:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
16626:     }
16627:     if ($errors) {
16628:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
16629:                        $errors.'</ul>';
16630:     }
16631:     return $resulttext;
16632: }
16633: 
16634: sub get_lti_id {
16635:     my ($domain,$consumer) = @_;
16636:     # get lock on lti db
16637:     my $lockhash = {
16638:                       lock => $env{'user.name'}.
16639:                               ':'.$env{'user.domain'},
16640:                    };
16641:     my $tries = 0;
16642:     my $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
16643:     my ($id,$error);
16644: 
16645:     while (($gotlock ne 'ok') && ($tries<10)) {
16646:         $tries ++;
16647:         sleep (0.1);
16648:         $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
16649:     }
16650:     if ($gotlock eq 'ok') {
16651:         my %currids = &Apache::lonnet::dump_dom('lti',$domain);
16652:         if ($currids{'lock'}) {
16653:             delete($currids{'lock'});
16654:             if (keys(%currids)) {
16655:                 my @curr = sort { $a <=> $b } keys(%currids);
16656:                 if ($curr[-1] =~ /^\d+$/) {
16657:                     $id = 1 + $curr[-1];
16658:                 }
16659:             } else {
16660:                 $id = 1;
16661:             }
16662:             if ($id) {
16663:                 unless (&Apache::lonnet::newput_dom('lti',{ $id => $consumer },$domain) eq 'ok') {
16664:                     $error = 'nostore';
16665:                 }
16666:             } else {
16667:                 $error = 'nonumber';
16668:             }
16669:         }
16670:         my $dellockoutcome = &Apache::lonnet::del_dom('lti',['lock'],$domain);
16671:     } else {
16672:         $error = 'nolock';
16673:     }
16674:     return ($id,$error);
16675: }
16676: 
16677: sub modify_autoenroll {
16678:     my ($dom,$lastactref,%domconfig) = @_;
16679:     my ($resulttext,%changes);
16680:     my %currautoenroll;
16681:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
16682:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
16683:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
16684:         }
16685:     }
16686:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
16687:     my %title = ( run => 'Auto-enrollment active',
16688:                   sender => 'Sender for notification messages',
16689:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
16690:                   autofailsafe => 'Failsafe for no drops if institutional data missing for a section');
16691:     my @offon = ('off','on');
16692:     my $sender_uname = $env{'form.sender_uname'};
16693:     my $sender_domain = $env{'form.sender_domain'};
16694:     if ($sender_domain eq '') {
16695:         $sender_uname = '';
16696:     } elsif ($sender_uname eq '') {
16697:         $sender_domain = '';
16698:     }
16699:     my $coowners = $env{'form.autoassign_coowners'};
16700:     my $autofailsafe = $env{'form.autoenroll_autofailsafe'};
16701:     $autofailsafe =~ s{^\s+|\s+$}{}g;
16702:     if ($autofailsafe =~ /\D/) {
16703:         undef($autofailsafe);
16704:     }
16705:     my $failsafe = $env{'form.autoenroll_failsafe'};
16706:     unless (($failsafe eq 'zero') || ($failsafe eq 'any')) {
16707:         $failsafe = 'off';
16708:         undef($autofailsafe);
16709:     }
16710:     my %autoenrollhash =  (
16711:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
16712:                                        'sender_uname' => $sender_uname,
16713:                                        'sender_domain' => $sender_domain,
16714:                                        'co-owners' => $coowners,
16715:                                        'autofailsafe' => $autofailsafe,
16716:                                        'failsafe' => $failsafe,
16717:                                 }
16718:                      );
16719:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
16720:                                              $dom);
16721:     if ($putresult eq 'ok') {
16722:         if (exists($currautoenroll{'run'})) {
16723:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
16724:                  $changes{'run'} = 1;
16725:              }
16726:         } elsif ($autorun) {
16727:             if ($env{'form.autoenroll_run'} ne '1') {
16728:                  $changes{'run'} = 1;
16729:             }
16730:         }
16731:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
16732:             $changes{'sender'} = 1;
16733:         }
16734:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
16735:             $changes{'sender'} = 1;
16736:         }
16737:         if ($currautoenroll{'co-owners'} ne '') {
16738:             if ($currautoenroll{'co-owners'} ne $coowners) {
16739:                 $changes{'coowners'} = 1;
16740:             }
16741:         } elsif ($coowners) {
16742:             $changes{'coowners'} = 1;
16743:         }
16744:         if ($currautoenroll{'autofailsafe'} ne $autofailsafe) {
16745:             $changes{'autofailsafe'} = 1;
16746:         }
16747:         if ($currautoenroll{'failsafe'} ne $failsafe) {
16748:             $changes{'failsafe'} = 1;
16749:         }
16750:         if (keys(%changes) > 0) {
16751:             $resulttext = &mt('Changes made:').'<ul>';
16752:             if ($changes{'run'}) {
16753:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
16754:             }
16755:             if ($changes{'sender'}) {
16756:                 if ($sender_uname eq '' || $sender_domain eq '') {
16757:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
16758:                 } else {
16759:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
16760:                 }
16761:             }
16762:             if ($changes{'coowners'}) {
16763:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
16764:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
16765:                 if (ref($lastactref) eq 'HASH') {
16766:                     $lastactref->{'domainconfig'} = 1;
16767:                 }
16768:             }
16769:             if ($changes{'autofailsafe'}) {
16770:                 if ($autofailsafe ne '') {
16771:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$autofailsafe).'</li>';
16772:                 } else {
16773:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
16774:                 }
16775:             }
16776:             if ($changes{'failsafe'}) {
16777:                 if ($failsafe eq 'off') {
16778:                     unless ($changes{'autofailsafe'}) {
16779:                         $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
16780:                     }
16781:                 } elsif ($failsafe eq 'zero') {
16782:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero').'</li>';
16783:                 } else {
16784:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero or greater').'</li>';
16785:                 }
16786:             }
16787:             if (($changes{'autofailsafe'}) || ($changes{'failsafe'})) {
16788:                 &Apache::lonnet::get_domain_defaults($dom,1);
16789:                 if (ref($lastactref) eq 'HASH') {
16790:                     $lastactref->{'domdefaults'} = 1;
16791:                 }
16792:             }
16793:             $resulttext .= '</ul>';
16794:         } else {
16795:             $resulttext = &mt('No changes made to auto-enrollment settings');
16796:         }
16797:     } else {
16798:         $resulttext = '<span class="LC_error">'.
16799: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
16800:     }
16801:     return $resulttext;
16802: }
16803: 
16804: sub modify_autoupdate {
16805:     my ($dom,%domconfig) = @_;
16806:     my ($resulttext,%currautoupdate,%fields,%changes);
16807:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
16808:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
16809:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
16810:         }
16811:     }
16812:     my @offon = ('off','on');
16813:     my %title = &Apache::lonlocal::texthash (
16814:                     run        => 'Auto-update:',
16815:                     classlists => 'Updates to user information in classlists?',
16816:                     unexpired  => 'Skip updates for users without active or future roles?',
16817:                     lastactive => 'Skip updates for inactive users?',
16818:                 );
16819:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16820:     my %fieldtitles = &Apache::lonlocal::texthash (
16821:                         id => 'Student/Employee ID',
16822:                         permanentemail => 'E-mail address',
16823:                         lastname => 'Last Name',
16824:                         firstname => 'First Name',
16825:                         middlename => 'Middle Name',
16826:                         generation => 'Generation',
16827:                       );
16828:     $othertitle = &mt('All users');
16829:     if (keys(%{$usertypes}) >  0) {
16830:         $othertitle = &mt('Other users');
16831:     }
16832:     foreach my $key (keys(%env)) {
16833:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
16834:             my ($usertype,$item) = ($1,$2);
16835:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
16836:                 if ($usertype eq 'default') {   
16837:                     push(@{$fields{$1}},$2);
16838:                 } elsif (ref($types) eq 'ARRAY') {
16839:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
16840:                         push(@{$fields{$1}},$2);
16841:                     }
16842:                 }
16843:             }
16844:         }
16845:     }
16846:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
16847:     @lockablenames = sort(@lockablenames);
16848:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
16849:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
16850:         if (@changed) {
16851:             $changes{'lockablenames'} = 1;
16852:         }
16853:     } else {
16854:         if (@lockablenames) {
16855:             $changes{'lockablenames'} = 1;
16856:         }
16857:     }
16858:     my %updatehash = (
16859:                       autoupdate => { run => $env{'form.autoupdate_run'},
16860:                                       classlists => $env{'form.classlists'},
16861:                                       unexpired  => $env{'form.unexpired'},
16862:                                       fields => {%fields},
16863:                                       lockablenames => \@lockablenames,
16864:                                     }
16865:                      );
16866:     my $lastactivedays;
16867:     if ($env{'form.lastactive'}) {
16868:         $lastactivedays = $env{'form.lastactivedays'};
16869:         $lastactivedays =~ s/^\s+|\s+$//g;
16870:         unless ($lastactivedays =~ /^\d+$/) {
16871:             undef($lastactivedays);
16872:             $env{'form.lastactive'} = 0;
16873:         }
16874:     }
16875:     $updatehash{'autoupdate'}{'lastactive'} = $lastactivedays;
16876:     foreach my $key (keys(%currautoupdate)) {
16877:         if (($key eq 'run') || ($key eq 'classlists') || ($key eq 'unexpired') || ($key eq 'lastactive')) {
16878:             if (exists($updatehash{autoupdate}{$key})) {
16879:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
16880:                     $changes{$key} = 1;
16881:                 }
16882:             }
16883:         } elsif ($key eq 'fields') {
16884:             if (ref($currautoupdate{$key}) eq 'HASH') {
16885:                 foreach my $item (@{$types},'default') {
16886:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
16887:                         my $change = 0;
16888:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
16889:                             if (!exists($fields{$item})) {
16890:                                 $change = 1;
16891:                                 last;
16892:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
16893:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
16894:                                     $change = 1;
16895:                                     last;
16896:                                 }
16897:                             }
16898:                         }
16899:                         if ($change) {
16900:                             push(@{$changes{$key}},$item);
16901:                         }
16902:                     } 
16903:                 }
16904:             }
16905:         } elsif ($key eq 'lockablenames') {
16906:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
16907:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
16908:                 if (@changed) {
16909:                     $changes{'lockablenames'} = 1;
16910:                 }
16911:             } else {
16912:                 if (@lockablenames) {
16913:                     $changes{'lockablenames'} = 1;
16914:                 }
16915:             }
16916:         }
16917:     }
16918:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
16919:         if (@lockablenames) {
16920:             $changes{'lockablenames'} = 1;
16921:         }
16922:     }
16923:     unless (grep(/^unexpired$/,keys(%currautoupdate))) {
16924:         if ($updatehash{'autoupdate'}{'unexpired'}) {
16925:             $changes{'unexpired'} = 1;
16926:         }
16927:     }
16928:     unless (grep(/^lastactive$/,keys(%currautoupdate))) {
16929:         if ($updatehash{'autoupdate'}{'lastactive'} ne '') {
16930:             $changes{'lastactive'} = 1;
16931:         }
16932:     }
16933:     foreach my $item (@{$types},'default') {
16934:         if (defined($fields{$item})) {
16935:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
16936:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
16937:                     my $change = 0;
16938:                     if (ref($fields{$item}) eq 'ARRAY') {
16939:                         foreach my $type (@{$fields{$item}}) {
16940:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
16941:                                 $change = 1;
16942:                                 last;
16943:                             }
16944:                         }
16945:                     }
16946:                     if ($change) {
16947:                         push(@{$changes{'fields'}},$item);
16948:                     }
16949:                 } else {
16950:                     push(@{$changes{'fields'}},$item);
16951:                 }
16952:             } else {
16953:                 push(@{$changes{'fields'}},$item);
16954:             }
16955:         }
16956:     }
16957:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
16958:                                              $dom);
16959:     if ($putresult eq 'ok') {
16960:         if (keys(%changes) > 0) {
16961:             $resulttext = &mt('Changes made:').'<ul>';
16962:             foreach my $key (sort(keys(%changes))) {
16963:                 if ($key eq 'lockablenames') {
16964:                     $resulttext .= '<li>';
16965:                     if (@lockablenames) {
16966:                         $usertypes->{'default'} = $othertitle;
16967:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
16968:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
16969:                     } else {
16970:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
16971:                     }
16972:                     $resulttext .= '</li>';
16973:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
16974:                     foreach my $item (@{$changes{$key}}) {
16975:                         my @newvalues;
16976:                         foreach my $type (@{$fields{$item}}) {
16977:                             push(@newvalues,$fieldtitles{$type});
16978:                         }
16979:                         my $newvaluestr;
16980:                         if (@newvalues > 0) {
16981:                             $newvaluestr = join(', ',@newvalues);
16982:                         } else {
16983:                             $newvaluestr = &mt('none');
16984:                         }
16985:                         if ($item eq 'default') {
16986:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
16987:                         } else {
16988:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
16989:                         }
16990:                     }
16991:                 } else {
16992:                     my $newvalue;
16993:                     if ($key eq 'run') {
16994:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
16995:                     } elsif ($key eq 'lastactive') {
16996:                         $newvalue = $offon[$env{'form.lastactive'}];
16997:                         unless ($lastactivedays eq '') {
16998:                             $newvalue .= '; '.&mt('inactive = no activity in last [quant,_1,day]',$lastactivedays);
16999:                         }
17000:                     } else {
17001:                         $newvalue = $offon[$env{'form.'.$key}];
17002:                     }
17003:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
17004:                 }
17005:             }
17006:             $resulttext .= '</ul>';
17007:         } else {
17008:             $resulttext = &mt('No changes made to autoupdates');
17009:         }
17010:     } else {
17011:         $resulttext = '<span class="LC_error">'.
17012: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
17013:     }
17014:     return $resulttext;
17015: }
17016: 
17017: sub modify_autocreate {
17018:     my ($dom,%domconfig) = @_;
17019:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
17020:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
17021:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
17022:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
17023:         }
17024:     }
17025:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
17026:                  req => 'Auto-creation of validated requests for official courses',
17027:                  xmldc => 'Identity of course creator of courses from XML files',
17028:                );
17029:     my @types = ('xml','req');
17030:     foreach my $item (@types) {
17031:         $newvals{$item} = $env{'form.autocreate_'.$item};
17032:         $newvals{$item} =~ s/\D//g;
17033:         $newvals{$item} = 0 if ($newvals{$item} eq '');
17034:     }
17035:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
17036:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
17037:     unless (exists($domcoords{$newvals{'xmldc'}})) {
17038:         $newvals{'xmldc'} = '';
17039:     } 
17040:     %autocreatehash =  (
17041:                         autocreate => { xml => $newvals{'xml'},
17042:                                         req => $newvals{'req'},
17043:                                       }
17044:                        );
17045:     if ($newvals{'xmldc'} ne '') {
17046:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
17047:     }
17048:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
17049:                                              $dom);
17050:     if ($putresult eq 'ok') {
17051:         my @items = @types;
17052:         if ($newvals{'xml'}) {
17053:             push(@items,'xmldc');
17054:         }
17055:         foreach my $item (@items) {
17056:             if (exists($currautocreate{$item})) {
17057:                 if ($currautocreate{$item} ne $newvals{$item}) {
17058:                     $changes{$item} = 1;
17059:                 }
17060:             } elsif ($newvals{$item}) {
17061:                 $changes{$item} = 1;
17062:             }
17063:         }
17064:         if (keys(%changes) > 0) {
17065:             my @offon = ('off','on'); 
17066:             $resulttext = &mt('Changes made:').'<ul>';
17067:             foreach my $item (@types) {
17068:                 if ($changes{$item}) {
17069:                     my $newtxt = $offon[$newvals{$item}];
17070:                     $resulttext .= '<li>'.
17071:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
17072:                                        '<b>','</b>').
17073:                                    '</li>';
17074:                 }
17075:             }
17076:             if ($changes{'xmldc'}) {
17077:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
17078:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
17079:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
17080:             }
17081:             $resulttext .= '</ul>';
17082:         } else {
17083:             $resulttext = &mt('No changes made to auto-creation settings');
17084:         }
17085:     } else {
17086:         $resulttext = '<span class="LC_error">'.
17087:             &mt('An error occurred: [_1]',$putresult).'</span>';
17088:     }
17089:     return $resulttext;
17090: }
17091: 
17092: sub modify_directorysrch {
17093:     my ($dom,$lastactref,%domconfig) = @_;
17094:     my ($resulttext,%changes);
17095:     my %currdirsrch;
17096:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
17097:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
17098:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
17099:         }
17100:     }
17101:     my %title = ( available => 'Institutional directory search available',
17102:                   localonly => 'Other domains can search institution',
17103:                   lcavailable => 'LON-CAPA directory search available',
17104:                   lclocalonly => 'Other domains can search LON-CAPA domain',
17105:                   searchby => 'Search types',
17106:                   searchtypes => 'Search latitude');
17107:     my @offon = ('off','on');
17108:     my @otherdoms = ('Yes','No');
17109: 
17110:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
17111:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
17112:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
17113: 
17114:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
17115:     if (keys(%{$usertypes}) == 0) {
17116:         @cansearch = ('default');
17117:     } else {
17118:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
17119:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
17120:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
17121:                     push(@{$changes{'cansearch'}},$type);
17122:                 }
17123:             }
17124:             foreach my $type (@cansearch) {
17125:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
17126:                     push(@{$changes{'cansearch'}},$type);
17127:                 }
17128:             }
17129:         } else {
17130:             push(@{$changes{'cansearch'}},@cansearch);
17131:         }
17132:     }
17133: 
17134:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
17135:         foreach my $by (@{$currdirsrch{'searchby'}}) {
17136:             if (!grep(/^\Q$by\E$/,@searchby)) {
17137:                 push(@{$changes{'searchby'}},$by);
17138:             }
17139:         }
17140:         foreach my $by (@searchby) {
17141:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
17142:                 push(@{$changes{'searchby'}},$by);
17143:             }
17144:         }
17145:     } else {
17146:         push(@{$changes{'searchby'}},@searchby);
17147:     }
17148: 
17149:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
17150:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
17151:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
17152:                 push(@{$changes{'searchtypes'}},$type);
17153:             }
17154:         }
17155:         foreach my $type (@searchtypes) {
17156:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
17157:                 push(@{$changes{'searchtypes'}},$type);
17158:             }
17159:         }
17160:     } else {
17161:         if (exists($currdirsrch{'searchtypes'})) {
17162:             foreach my $type (@searchtypes) {  
17163:                 if ($type ne $currdirsrch{'searchtypes'}) { 
17164:                     push(@{$changes{'searchtypes'}},$type);
17165:                 }
17166:             }
17167:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
17168:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
17169:             }   
17170:         } else {
17171:             push(@{$changes{'searchtypes'}},@searchtypes); 
17172:         }
17173:     }
17174: 
17175:     my %dirsrch_hash =  (
17176:             directorysrch => { available => $env{'form.dirsrch_available'},
17177:                                cansearch => \@cansearch,
17178:                                localonly => $env{'form.dirsrch_instlocalonly'},
17179:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
17180:                                lcavailable => $env{'form.dirsrch_domavailable'},
17181:                                searchby => \@searchby,
17182:                                searchtypes => \@searchtypes,
17183:                              }
17184:             );
17185:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
17186:                                              $dom);
17187:     if ($putresult eq 'ok') {
17188:         if (exists($currdirsrch{'available'})) {
17189:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
17190:                  $changes{'available'} = 1;
17191:              }
17192:         } else {
17193:             if ($env{'form.dirsrch_available'} eq '1') {
17194:                 $changes{'available'} = 1;
17195:             }
17196:         }
17197:         if (exists($currdirsrch{'lcavailable'})) {
17198:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
17199:                 $changes{'lcavailable'} = 1;
17200:             }
17201:         } else {
17202:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
17203:                 $changes{'lcavailable'} = 1;
17204:             }
17205:         }
17206:         if (exists($currdirsrch{'localonly'})) {
17207:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
17208:                 $changes{'localonly'} = 1;
17209:             }
17210:         } else {
17211:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
17212:                 $changes{'localonly'} = 1;
17213:             }
17214:         }
17215:         if (exists($currdirsrch{'lclocalonly'})) {
17216:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
17217:                 $changes{'lclocalonly'} = 1;
17218:             }
17219:         } else {
17220:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
17221:                 $changes{'lclocalonly'} = 1;
17222:             }
17223:         }
17224:         if (keys(%changes) > 0) {
17225:             $resulttext = &mt('Changes made:').'<ul>';
17226:             if ($changes{'available'}) {
17227:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
17228:             }
17229:             if ($changes{'lcavailable'}) {
17230:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
17231:             }
17232:             if ($changes{'localonly'}) {
17233:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
17234:             }
17235:             if ($changes{'lclocalonly'}) {
17236:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
17237:             }
17238:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
17239:                 my $chgtext;
17240:                 if (ref($usertypes) eq 'HASH') {
17241:                     if (keys(%{$usertypes}) > 0) {
17242:                         foreach my $type (@{$types}) {
17243:                             if (grep(/^\Q$type\E$/,@cansearch)) {
17244:                                 $chgtext .= $usertypes->{$type}.'; ';
17245:                             }
17246:                         }
17247:                         if (grep(/^default$/,@cansearch)) {
17248:                             $chgtext .= $othertitle;
17249:                         } else {
17250:                             $chgtext =~ s/\; $//;
17251:                         }
17252:                         $resulttext .=
17253:                             '<li>'.
17254:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
17255:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
17256:                             '</li>';
17257:                     }
17258:                 }
17259:             }
17260:             if (ref($changes{'searchby'}) eq 'ARRAY') {
17261:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
17262:                 my $chgtext;
17263:                 foreach my $type (@{$titleorder}) {
17264:                     if (grep(/^\Q$type\E$/,@searchby)) {
17265:                         if (defined($searchtitles->{$type})) {
17266:                             $chgtext .= $searchtitles->{$type}.'; ';
17267:                         }
17268:                     }
17269:                 }
17270:                 $chgtext =~ s/\; $//;
17271:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
17272:             }
17273:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
17274:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
17275:                 my $chgtext;
17276:                 foreach my $type (@{$srchtypeorder}) {
17277:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
17278:                         if (defined($srchtypes_desc->{$type})) {
17279:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
17280:                         }
17281:                     }
17282:                 }
17283:                 $chgtext =~ s/\; $//;
17284:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
17285:             }
17286:             $resulttext .= '</ul>';
17287:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
17288:             if (ref($lastactref) eq 'HASH') {
17289:                 $lastactref->{'directorysrch'} = 1;
17290:             }
17291:         } else {
17292:             $resulttext = &mt('No changes made to directory search settings');
17293:         }
17294:     } else {
17295:         $resulttext = '<span class="LC_error">'.
17296:                       &mt('An error occurred: [_1]',$putresult).'</span>';
17297:     }
17298:     return $resulttext;
17299: }
17300: 
17301: sub modify_contacts {
17302:     my ($dom,$lastactref,%domconfig) = @_;
17303:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
17304:     if (ref($domconfig{'contacts'}) eq 'HASH') {
17305:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
17306:             $currsetting{$key} = $domconfig{'contacts'}{$key};
17307:         }
17308:     }
17309:     my (%others,%to,%bcc,%includestr,%includeloc);
17310:     my @contacts = ('supportemail','adminemail');
17311:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
17312:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
17313:     my @toggles = ('reporterrors','reportupdates','reportstatus');
17314:     my @lonstatus = ('threshold','sysmail','weights','excluded');
17315:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
17316:     foreach my $type (@mailings) {
17317:         @{$newsetting{$type}} = 
17318:             &Apache::loncommon::get_env_multiple('form.'.$type);
17319:         foreach my $item (@contacts) {
17320:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
17321:                 $contacts_hash{contacts}{$type}{$item} = 1;
17322:             } else {
17323:                 $contacts_hash{contacts}{$type}{$item} = 0;
17324:             }
17325:         }
17326:         $others{$type} = $env{'form.'.$type.'_others'};
17327:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
17328:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17329:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
17330:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
17331:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
17332:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
17333:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
17334:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
17335:             }
17336:         }
17337:     }
17338:     foreach my $item (@contacts) {
17339:         $to{$item} = $env{'form.'.$item};
17340:         $contacts_hash{'contacts'}{$item} = $to{$item};
17341:     }
17342:     foreach my $item (@toggles) {
17343:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
17344:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
17345:         }
17346:     }
17347:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
17348:     foreach my $item (@lonstatus) {
17349:         if ($item eq 'excluded') {
17350:             my (%serverhomes,@excluded);
17351:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
17352:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
17353:             if (@possexcluded) {
17354:                 foreach my $id (sort(@possexcluded)) {
17355:                     if ($serverhomes{$id}) {
17356:                         push(@excluded,$id);
17357:                     }
17358:                 }
17359:             }
17360:             if (@excluded) {
17361:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
17362:             }
17363:         } elsif ($item eq 'weights') {
17364:             foreach my $type ('E','W','N','U') {
17365:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
17366:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
17367:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
17368:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
17369:                             $env{'form.error'.$item.'_'.$type};
17370:                     }
17371:                 }
17372:             }
17373:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
17374:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
17375:             if ($env{'form.error'.$item} =~ /^\d+$/) {
17376:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
17377:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
17378:                 }
17379:             }
17380:         }
17381:     }
17382:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
17383:         foreach my $field (@{$fields}) {
17384:             if (ref($possoptions->{$field}) eq 'ARRAY') {
17385:                 my $value = $env{'form.helpform_'.$field};
17386:                 $value =~ s/^\s+|\s+$//g;
17387:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
17388:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
17389:                     if ($field eq 'screenshot') {
17390:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
17391:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
17392:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
17393:                         }
17394:                     }
17395:                 }
17396:             }
17397:         }
17398:     }
17399:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
17400:     my (@statuses,%usertypeshash,@overrides);
17401:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
17402:         @statuses = @{$types};
17403:         if (ref($usertypes) eq 'HASH') {
17404:             %usertypeshash = %{$usertypes};
17405:         }
17406:     }
17407:     if (@statuses) {
17408:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
17409:         foreach my $type (@possoverrides) {
17410:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
17411:                 push(@overrides,$type);
17412:             }
17413:         }
17414:         if (@overrides) {
17415:             foreach my $type (@overrides) {
17416:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
17417:                 foreach my $item (@contacts) {
17418:                     if (grep(/^\Q$item\E$/,@standard)) {
17419:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
17420:                         $newsetting{'override_'.$type}{$item} = 1;
17421:                     } else {
17422:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
17423:                         $newsetting{'override_'.$type}{$item} = 0;
17424:                     }
17425:                 }
17426:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
17427:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
17428:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
17429:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
17430:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
17431:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
17432:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
17433:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
17434:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
17435:                 }
17436:             }     
17437:         }
17438:     }
17439:     if (keys(%currsetting) > 0) {
17440:         foreach my $item (@contacts) {
17441:             if ($to{$item} ne $currsetting{$item}) {
17442:                 $changes{$item} = 1;
17443:             }
17444:         }
17445:         foreach my $type (@mailings) {
17446:             foreach my $item (@contacts) {
17447:                 if (ref($currsetting{$type}) eq 'HASH') {
17448:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
17449:                         push(@{$changes{$type}},$item);
17450:                     }
17451:                 } else {
17452:                     push(@{$changes{$type}},@{$newsetting{$type}});
17453:                 }
17454:             }
17455:             if ($others{$type} ne $currsetting{$type}{'others'}) {
17456:                 push(@{$changes{$type}},'others');
17457:             }
17458:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17459:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
17460:                     push(@{$changes{$type}},'bcc'); 
17461:                 }
17462:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
17463:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
17464:                     push(@{$changes{$type}},'include');
17465:                 }
17466:             }
17467:         }
17468:         if (ref($fields) eq 'ARRAY') {
17469:             if (ref($currsetting{'helpform'}) eq 'HASH') {
17470:                 foreach my $field (@{$fields}) {
17471:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
17472:                         push(@{$changes{'helpform'}},$field);
17473:                     }
17474:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
17475:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
17476:                             push(@{$changes{'helpform'}},'maxsize');
17477:                         }
17478:                     }
17479:                 }
17480:             } else {
17481:                 foreach my $field (@{$fields}) {
17482:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
17483:                         push(@{$changes{'helpform'}},$field);
17484:                     }
17485:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
17486:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
17487:                             push(@{$changes{'helpform'}},'maxsize');
17488:                         }
17489:                     }
17490:                 }
17491:             }
17492:         }
17493:         if (@statuses) {
17494:             if (ref($currsetting{'overrides'}) eq 'HASH') { 
17495:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
17496:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
17497:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
17498:                             foreach my $item (@contacts,'bcc','others','include') {
17499:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) { 
17500:                                     push(@{$changes{'overrides'}},$key);
17501:                                     last;
17502:                                 }
17503:                             }
17504:                         } else {
17505:                             push(@{$changes{'overrides'}},$key);
17506:                         }
17507:                     }
17508:                 }
17509:                 foreach my $key (@overrides) {
17510:                     unless (exists($currsetting{'overrides'}{$key})) {
17511:                         push(@{$changes{'overrides'}},$key);
17512:                     }
17513:                 }
17514:             } else {
17515:                 foreach my $key (@overrides) {
17516:                     push(@{$changes{'overrides'}},$key); 
17517:                 }
17518:             }
17519:         }
17520:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
17521:             foreach my $key ('excluded','weights','threshold','sysmail') {
17522:                 if ($key eq 'excluded') {
17523:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
17524:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
17525:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
17526:                             (@{$currsetting{'lonstatus'}{$key}})) {
17527:                             my @diffs =
17528:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
17529:                                                                    $currsetting{'lonstatus'}{$key});
17530:                             if (@diffs) {
17531:                                 push(@{$changes{'lonstatus'}},$key);
17532:                             }
17533:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
17534:                             push(@{$changes{'lonstatus'}},$key);
17535:                         }
17536:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
17537:                              (@{$currsetting{'lonstatus'}{$key}})) {
17538:                         push(@{$changes{'lonstatus'}},$key);
17539:                     }
17540:                 } elsif ($key eq 'weights') {
17541:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
17542:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
17543:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
17544:                             foreach my $type ('E','W','N','U') {
17545:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
17546:                                         $currsetting{'lonstatus'}{$key}{$type}) {
17547:                                     push(@{$changes{'lonstatus'}},$key);
17548:                                     last;
17549:                                 }
17550:                             }
17551:                         } else {
17552:                             foreach my $type ('E','W','N','U') {
17553:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
17554:                                     push(@{$changes{'lonstatus'}},$key);
17555:                                     last;
17556:                                 }
17557:                             }
17558:                         }
17559:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
17560:                         foreach my $type ('E','W','N','U') {
17561:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
17562:                                 push(@{$changes{'lonstatus'}},$key);
17563:                                 last;
17564:                             }
17565:                         }
17566:                     }
17567:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
17568:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
17569:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
17570:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
17571:                                 push(@{$changes{'lonstatus'}},$key);
17572:                             }
17573:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
17574:                             push(@{$changes{'lonstatus'}},$key);
17575:                         }
17576:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
17577:                         push(@{$changes{'lonstatus'}},$key);
17578:                     }
17579:                 }
17580:             }
17581:         } else {
17582:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
17583:                 foreach my $key ('excluded','weights','threshold','sysmail') {
17584:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
17585:                         push(@{$changes{'lonstatus'}},$key);
17586:                     }
17587:                 }
17588:             }
17589:         }
17590:     } else {
17591:         my %default;
17592:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
17593:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
17594:         $default{'errormail'} = 'adminemail';
17595:         $default{'packagesmail'} = 'adminemail';
17596:         $default{'helpdeskmail'} = 'supportemail';
17597:         $default{'otherdomsmail'} = 'supportemail';
17598:         $default{'lonstatusmail'} = 'adminemail';
17599:         $default{'requestsmail'} = 'adminemail';
17600:         $default{'updatesmail'} = 'adminemail';
17601:         $default{'hostipmail'} = 'adminemail';
17602:         foreach my $item (@contacts) {
17603:            if ($to{$item} ne $default{$item}) {
17604:                $changes{$item} = 1;
17605:            }
17606:         }
17607:         foreach my $type (@mailings) {
17608:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
17609:                 push(@{$changes{$type}},@{$newsetting{$type}});
17610:             }
17611:             if ($others{$type} ne '') {
17612:                 push(@{$changes{$type}},'others');
17613:             }
17614:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17615:                 if ($bcc{$type} ne '') {
17616:                     push(@{$changes{$type}},'bcc');
17617:                 }
17618:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
17619:                     push(@{$changes{$type}},'include');
17620:                 }
17621:             }
17622:         }
17623:         if (ref($fields) eq 'ARRAY') {
17624:             foreach my $field (@{$fields}) {
17625:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
17626:                     push(@{$changes{'helpform'}},$field);
17627:                 }
17628:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
17629:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
17630:                         push(@{$changes{'helpform'}},'maxsize');
17631:                     }
17632:                 }
17633:             }
17634:         }
17635:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
17636:             foreach my $key ('excluded','weights','threshold','sysmail') {
17637:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
17638:                     push(@{$changes{'lonstatus'}},$key);
17639:                 }
17640:             }
17641:         }
17642:     }
17643:     foreach my $item (@toggles) {
17644:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
17645:             $changes{$item} = 1;
17646:         } elsif ((!$env{'form.'.$item}) &&
17647:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
17648:             $changes{$item} = 1;
17649:         }
17650:     }
17651:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
17652:                                              $dom);
17653:     if ($putresult eq 'ok') {
17654:         if (keys(%changes) > 0) {
17655:             &Apache::loncommon::devalidate_domconfig_cache($dom);
17656:             if (ref($lastactref) eq 'HASH') {
17657:                 $lastactref->{'domainconfig'} = 1;
17658:             }
17659:             my ($titles,$short_titles)  = &contact_titles();
17660:             $resulttext = &mt('Changes made:').'<ul>';
17661:             foreach my $item (@contacts) {
17662:                 if ($changes{$item}) {
17663:                     $resulttext .= '<li>'.$titles->{$item}.
17664:                                     &mt(' set to: ').
17665:                                     '<span class="LC_cusr_emph">'.
17666:                                     $to{$item}.'</span></li>';
17667:                 }
17668:             }
17669:             foreach my $type (@mailings) {
17670:                 if (ref($changes{$type}) eq 'ARRAY') {
17671:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17672:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
17673:                     } else {
17674:                         $resulttext .= '<li>'.$titles->{$type}.': ';
17675:                     }
17676:                     my @text;
17677:                     foreach my $item (@{$newsetting{$type}}) {
17678:                         push(@text,$short_titles->{$item});
17679:                     }
17680:                     if ($others{$type} ne '') {
17681:                         push(@text,$others{$type});
17682:                     }
17683:                     if (@text) {
17684:                         $resulttext .= '<span class="LC_cusr_emph">'.
17685:                                        join(', ',@text).'</span>';
17686:                     }
17687:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17688:                         if ($bcc{$type} ne '') {
17689:                             my $bcctext;
17690:                             if (@text) {
17691:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
17692:                             } else {
17693:                                 $bcctext = '(Bcc)';
17694:                             }
17695:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
17696:                         } elsif (!@text) {
17697:                             $resulttext .= &mt('No one');
17698:                         }   
17699:                         if ($includestr{$type} ne '') {
17700:                             if ($includeloc{$type} eq 'b') {
17701:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
17702:                             } elsif ($includeloc{$type} eq 's') {
17703:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
17704:                             }
17705:                         }
17706:                     } elsif (!@text) {
17707:                         $resulttext .= &mt('No recipients');
17708:                     }
17709:                     $resulttext .= '</li>';
17710:                 }
17711:             }
17712:             if (ref($changes{'overrides'}) eq 'ARRAY') {
17713:                 my @deletions;
17714:                 foreach my $type (@{$changes{'overrides'}}) {
17715:                     if ($usertypeshash{$type}) {
17716:                         if (grep(/^\Q$type\E/,@overrides)) {
17717:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
17718:                                                       $usertypeshash{$type}).'<ul><li>';
17719:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
17720:                                 my @text;
17721:                                 foreach my $item (@contacts) {
17722:                                     if ($newsetting{'override_'.$type}{$item}) { 
17723:                                         push(@text,$short_titles->{$item});
17724:                                     }
17725:                                 }
17726:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
17727:                                     push(@text,$newsetting{'override_'.$type}{'others'});
17728:                                 }
17729:   
17730:                                 if (@text) {
17731:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
17732:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
17733:                                 }
17734:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
17735:                                     my $bcctext;
17736:                                     if (@text) {
17737:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
17738:                                     } else {
17739:                                         $bcctext = '(Bcc)';
17740:                                     }
17741:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
17742:                                 } elsif (!@text) {
17743:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
17744:                                 }
17745:                                 $resulttext .= '</li>';
17746:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
17747:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
17748:                                     if ($loc eq 'b') {
17749:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
17750:                                     } elsif ($loc eq 's') {
17751:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
17752:                                     }
17753:                                 }
17754:                             }
17755:                             $resulttext .= '</li></ul></li>';
17756:                         } else {
17757:                             push(@deletions,$usertypeshash{$type});
17758:                         }
17759:                     }
17760:                 }
17761:                 if (@deletions) {
17762:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
17763:                                               join(', ',@deletions)).'</li>';
17764:                 }
17765:             }
17766:             my @offon = ('off','on');
17767:             my $corelink = &core_link_msu();
17768:             if ($changes{'reporterrors'}) {
17769:                 $resulttext .= '<li>'.
17770:                                &mt('E-mail error reports to [_1] set to "'.
17771:                                    $offon[$env{'form.reporterrors'}].'".',
17772:                                    $corelink).
17773:                                '</li>';
17774:             }
17775:             if ($changes{'reportupdates'}) {
17776:                 $resulttext .= '<li>'.
17777:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
17778:                                     $offon[$env{'form.reportupdates'}].'".',
17779:                                     $corelink).
17780:                                 '</li>';
17781:             }
17782:             if ($changes{'reportstatus'}) {
17783:                 $resulttext .= '<li>'.
17784:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
17785:                                     $offon[$env{'form.reportstatus'}].'".',
17786:                                     $corelink).
17787:                                 '</li>';
17788:             }
17789:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
17790:                 $resulttext .= '<li>'.
17791:                                &mt('Nightly status check e-mail settings').':<ul>';
17792:                 my (%defval,%use_def,%shown);
17793:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
17794:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
17795:                 $defval{'weights'} =
17796:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
17797:                 $defval{'excluded'} = &mt('None');
17798:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
17799:                     foreach my $item ('threshold','sysmail','weights','excluded') {
17800:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
17801:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
17802:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
17803:                             } elsif ($item eq 'weights') {
17804:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
17805:                                     foreach my $type ('E','W','N','U') {
17806:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
17807:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
17808:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
17809:                                         } else {
17810:                                             $shown{$item} .= $lonstatus_defs->{$type};
17811:                                         }
17812:                                         $shown{$item} .= ', ';
17813:                                     }
17814:                                     $shown{$item} =~ s/, $//;
17815:                                 } else {
17816:                                     $shown{$item} = $defval{$item};
17817:                                 }
17818:                             } elsif ($item eq 'excluded') {
17819:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
17820:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
17821:                                 } else {
17822:                                     $shown{$item} = $defval{$item};
17823:                                 }
17824:                             }
17825:                         } else {
17826:                             $shown{$item} = $defval{$item};
17827:                         }
17828:                     }
17829:                 } else {
17830:                     foreach my $item ('threshold','weights','excluded','sysmail') {
17831:                         $shown{$item} = $defval{$item};
17832:                     }
17833:                 }
17834:                 foreach my $item ('threshold','weights','excluded','sysmail') {
17835:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
17836:                                           $shown{$item}).'</li>';
17837:                 }
17838:                 $resulttext .= '</ul></li>';
17839:             }
17840:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
17841:                 my (@optional,@required,@unused,$maxsizechg);
17842:                 foreach my $field (@{$changes{'helpform'}}) {
17843:                     if ($field eq 'maxsize') {
17844:                         $maxsizechg = 1;
17845:                         next;
17846:                     }
17847:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
17848:                         push(@optional,$field);
17849:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
17850:                         push(@unused,$field);
17851:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
17852:                         push(@required,$field);
17853:                     }
17854:                 }
17855:                 if (@optional) {
17856:                     $resulttext .= '<li>'.
17857:                                    &mt('Help form fields changed to "Optional": [_1].',
17858:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
17859:                                    '</li>';
17860:                 }
17861:                 if (@required) {
17862:                     $resulttext .= '<li>'.
17863:                                    &mt('Help form fields changed to "Required": [_1].',
17864:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
17865:                                    '</li>';
17866:                 }
17867:                 if (@unused) {
17868:                     $resulttext .= '<li>'.
17869:                                    &mt('Help form fields changed to "Not shown": [_1].',
17870:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
17871:                                    '</li>';
17872:                 }
17873:                 if ($maxsizechg) {
17874:                     $resulttext .= '<li>'.
17875:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
17876:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
17877:                                    '</li>';
17878:                 }
17879:             }
17880:             $resulttext .= '</ul>';
17881:         } else {
17882:             $resulttext = &mt('No changes made to contacts and form settings');
17883:         }
17884:     } else {
17885:         $resulttext = '<span class="LC_error">'.
17886:             &mt('An error occurred: [_1].',$putresult).'</span>';
17887:     }
17888:     return $resulttext;
17889: }
17890: 
17891: sub modify_privacy {
17892:     my ($dom,%domconfig) = @_;
17893:     my ($resulttext,%current,%changes);
17894:     if (ref($domconfig{'privacy'}) eq 'HASH') {
17895:         %current = %{$domconfig{'privacy'}};
17896:     }
17897:     my @fields = ('lastname','firstname','middlename','generation','permanentemail','id');
17898:     my @items = ('domain','author','course','community');
17899:     my %names = &Apache::lonlocal::texthash (
17900:                    domain => 'Assigned domain role(s)',
17901:                    author => 'Assigned co-author role(s)',
17902:                    course => 'Assigned course role(s)',
17903:                    community => 'Assigned community role',
17904:                 );
17905:     my %roles = &Apache::lonlocal::texthash (
17906:                    domain => 'Domain role',
17907:                    author => 'Co-author role',
17908:                    course => 'Course role',
17909:                    community => 'Community role',
17910:                 );
17911:     my %titles = &Apache::lonlocal::texthash (
17912:                   approval => 'Approval for role in different domain',
17913:                   othdom   => 'User information available in other domain',
17914:                   priv     => 'Information viewable by privileged user in same domain',
17915:                   unpriv   => 'Information viewable by unprivileged user in same domain',
17916:                   instdom  => 'Other domain shares institution/provider',
17917:                   extdom   => 'Other domain has different institution/provider',
17918:                   none     => 'Not allowed',
17919:                   user     => 'User authorizes',
17920:                   domain   => 'Domain Coordinator authorizes',
17921:                   auto     => 'Unrestricted',
17922:     );
17923:     my %fieldnames = &Apache::lonlocal::texthash (
17924:                         id => 'Student/Employee ID',
17925:                         permanentemail => 'E-mail address',
17926:                         lastname => 'Last Name',
17927:                         firstname => 'First Name',
17928:                         middlename => 'Middle Name',
17929:                         generation => 'Generation',
17930:     );
17931:     my ($othertitle,$usertypes,$types) =
17932:         &Apache::loncommon::sorted_inst_types($dom);
17933:     my (%by_ip,%by_location,@intdoms,@instdoms);
17934:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
17935: 
17936:     my %privacyhash = (
17937:                        'approval' => {
17938:                                        instdom => {},
17939:                                        extdom  => {},
17940:                                      },
17941:                        'othdom'   => {},
17942:                        'priv'     => {},
17943:                        'unpriv'   => {},
17944:                       );
17945:     foreach my $item (@items) {
17946:         if (@instdoms > 1) {
17947:             if ($env{'form.privacy_approval_instdom'.$item} =~ /^(none|user|domain|auto)$/) {
17948:                 $privacyhash{'approval'}{'instdom'}{$item} = $env{'form.privacy_approval_instdom_'.$item};
17949:             }
17950:             if (ref($current{'approval'}) eq 'HASH') {
17951:                 if (ref($current{'approval'}{'instdom'}) eq 'HASH') {
17952:                     unless ($privacyhash{'approval'}{'instdom'}{$item} eq $current{'approval'}{'instdom'}{$item}) {
17953:                         $changes{'approval'} = 1;
17954:                     }
17955:                 }
17956:             } elsif ($privacyhash{'approval'}{'instdom'}{$item} ne 'auto') {
17957:                 $changes{'approval'} = 1;
17958:             }
17959:         }
17960:         if (keys(%by_location) > 0) {
17961:             if ($env{'form.privacy_approval_extdom_'.$item} =~ /^(none|user|domain|auto)$/) {
17962:                 $privacyhash{'approval'}{'extdom'}{$item} = $env{'form.privacy_approval_extdom_'.$item};
17963:             }
17964:             if (ref($current{'approval'}) eq 'HASH') {
17965:                 if (ref($current{'approval'}{'extdom'}) eq 'HASH') {
17966:                     unless ($privacyhash{'approval'}{'extdom'}{$item} eq $current{'approval'}{'extdom'}{$item}) {
17967:                         $changes{'approval'} = 1;
17968:                     }
17969:                 }
17970:             } elsif ($privacyhash{'approval'}{'extdom'}{$item} ne 'auto') {
17971:                 $changes{'approval'} = 1;
17972:             }
17973:         }
17974:         foreach my $status ('priv','unpriv') {
17975:             my @possibles = sort(&Apache::loncommon::get_env_multiple('form.privacy_'.$status.'_'.$item));
17976:             my @newvalues;
17977:             foreach my $field (@possibles) {
17978:                 if (grep(/^\Q$field\E$/,@fields)) {
17979:                     $privacyhash{$status}{$item}{$field} = 1;
17980:                     push(@newvalues,$field);
17981:                 }
17982:             }
17983:             @newvalues = sort(@newvalues);
17984:             if (ref($current{$status}) eq 'HASH') {
17985:                 if (ref($current{$status}{$item}) eq 'HASH') {
17986:                     my @currvalues = sort(keys(%{$current{$status}{$item}}));
17987:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
17988:                     if (@diffs > 0) {
17989:                         $changes{$status} = 1;
17990:                     }
17991:                 }
17992:             } else {
17993:                 my @stdfields;
17994:                 foreach my $field (@fields) {
17995:                     if ($field eq 'id') {
17996:                         next if ($status eq 'unpriv');
17997:                         next if (($status eq 'priv') && ($item eq 'community'));
17998:                     }
17999:                     push(@stdfields,$field);
18000:                 }
18001:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
18002:                 if (@diffs > 0) {
18003:                     $changes{$status} = 1;
18004:                 }
18005:             }
18006:         }
18007:     }
18008:     if ((@instdoms > 1) || (keys(%by_location) > 0)) {
18009:         my @statuses;
18010:         if (ref($types) eq 'ARRAY') {
18011:             @statuses = @{$types};
18012:         }
18013:         foreach my $type (@statuses,'default') {
18014:             my @possfields = &Apache::loncommon::get_env_multiple('form.privacy_othdom_'.$type);
18015:             my @newvalues;
18016:             foreach my $field (sort(@possfields)) {
18017:                 if (grep(/^\Q$field\E$/,@fields)) {
18018:                     $privacyhash{'othdom'}{$type}{$field} = 1;
18019:                     push(@newvalues,$field);
18020:                 }
18021:             }
18022:             @newvalues = sort(@newvalues);
18023:             if (ref($current{'othdom'}) eq 'HASH') {
18024:                 if (ref($current{'othdom'}{$type}) eq 'HASH') {
18025:                     my @currvalues = sort(keys(%{$current{'othdom'}{$type}}));
18026:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
18027:                     if (@diffs > 0) {
18028:                         $changes{'othdom'} = 1;
18029:                     }
18030:                 }
18031:             } else {
18032:                 my @stdfields = ('lastname','firstname','middlename','generation','permanentemail');
18033:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
18034:                 if (@diffs > 0) {
18035:                     $changes{'othdom'} = 1;
18036:                 }
18037:             }
18038:         }
18039:     }
18040:     my %confighash = (
18041:                         privacy => \%privacyhash,
18042:                      );
18043:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
18044:     if ($putresult eq 'ok') {
18045:         if (keys(%changes) > 0) {
18046:             $resulttext = &mt('Changes made: ').'<ul>';
18047:             foreach my $key ('approval','othdom','priv','unpriv') {
18048:                 if ($changes{$key}) {
18049:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
18050:                     if ($key eq 'approval') {
18051:                         if (keys(%{$privacyhash{$key}{instdom}})) {
18052:                             $resulttext .= '<li>'.$titles{'instdom'}.'<ul>';
18053:                             foreach my $item (@items) {
18054:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{instdom}{$item}}.'</li>';
18055:                             }
18056:                             $resulttext .= '</ul></li>';
18057:                         }
18058:                         if (keys(%{$privacyhash{$key}{extdom}})) {
18059:                             $resulttext .= '<li>'.$titles{'extdom'}.'<ul>';
18060:                             foreach my $item (@items) {
18061:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{extdom}{$item}}.'</li>';
18062:                             }
18063:                             $resulttext .= '</ul></li>';
18064:                         }
18065:                     } elsif ($key eq 'othdom') {
18066:                         my @statuses;
18067:                         if (ref($types) eq 'ARRAY') {
18068:                             @statuses = @{$types};
18069:                         }
18070:                         if (ref($privacyhash{$key}) eq 'HASH') {
18071:                             foreach my $status (@statuses,'default') {
18072:                                 if ($status eq 'default') {
18073:                                     $resulttext .= '<li>'.$othertitle.': ';
18074:                                 } elsif (ref($usertypes) eq 'HASH') {
18075:                                     $resulttext .= '<li>'.$usertypes->{$status}.': ';
18076:                                 } else {
18077:                                     next;
18078:                                 }
18079:                                 if (ref($privacyhash{$key}{$status}) eq 'HASH') {
18080:                                     if (keys(%{$privacyhash{$key}{$status}})) {
18081:                                         $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$status}}))));
18082:                                     } else {
18083:                                         $resulttext .= &mt('none');
18084:                                     }
18085:                                 }
18086:                                 $resulttext .= '</li>';
18087:                             }
18088:                         }
18089:                     } else {
18090:                         foreach my $item (@items) {
18091:                             if (ref($privacyhash{$key}{$item}) eq 'HASH') {
18092:                                 $resulttext .= '<li>'.$names{$item}.': ';
18093:                                 if (keys(%{$privacyhash{$key}{$item}})) {
18094:                                     $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$item}}))));
18095:                                 } else {
18096:                                     $resulttext .= &mt('none');
18097:                                 }
18098:                                 $resulttext .= '</li>';
18099:                             }
18100:                         }
18101:                     }
18102:                     $resulttext .= '</ul></li>';
18103:                 }
18104:             }
18105:         } else {
18106:             $resulttext = &mt('No changes made to user information settings');
18107:         }
18108:     } else {
18109:         $resulttext = '<span class="LC_error">'.
18110:             &mt('An error occurred: [_1]',$putresult).'</span>';
18111:     }
18112:     return $resulttext;
18113: }
18114: 
18115: sub modify_passwords {
18116:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
18117:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
18118:         $updatedefaults,$updateconf);
18119:     my $customfn = 'resetpw.html';
18120:     if (ref($domconfig{'passwords'}) eq 'HASH') {
18121:         %current = %{$domconfig{'passwords'}};
18122:     }
18123:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18124:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
18125:     if (ref($types) eq 'ARRAY') {
18126:         @oktypes = @{$types};
18127:     }
18128:     push(@oktypes,'default');
18129: 
18130:     my %titles = &Apache::lonlocal::texthash (
18131:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
18132:         intauth_check  => 'Check bcrypt cost if authenticated',
18133:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
18134:         permanent      => 'Permanent e-mail address',
18135:         critical       => 'Critical notification address',
18136:         notify         => 'Notification address',
18137:         min            => 'Minimum password length',
18138:         max            => 'Maximum password length',
18139:         chars          => 'Required characters',
18140:         expire         => 'Password expiration (days)',
18141:         numsaved       => 'Number of previous passwords to save',
18142:         reset          => 'Resetting Forgotten Password',
18143:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
18144:         rules          => 'Rules for LON-CAPA Passwords',
18145:         crsownerchg    => 'Course Owner Changing Student Passwords',
18146:         username       => 'Username',
18147:         email          => 'E-mail address',
18148:     );
18149: 
18150: #
18151: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
18152: #
18153:     my (%curr_defaults,%save_defaults);
18154:     if (ref($domconfig{'defaults'}) eq 'HASH') {
18155:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
18156:             if ($key =~ /^intauth_(cost|check|switch)$/) {
18157:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
18158:             } else {
18159:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
18160:             }
18161:         }
18162:     }
18163:     my %staticdefaults = (
18164:         'resetlink'      => 2,
18165:         'resetcase'      => \@oktypes,
18166:         'resetprelink'   => 'both',
18167:         'resetemail'     => ['critical','notify','permanent'],
18168:         'intauth_cost'   => 10,
18169:         'intauth_check'  => 0,
18170:         'intauth_switch' => 0,
18171:     );
18172:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
18173:     foreach my $type (@oktypes) {
18174:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
18175:     }
18176:     my $linklife = $env{'form.passwords_link'};
18177:     $linklife =~ s/^\s+|\s+$//g;
18178:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
18179:         $newvalues{'resetlink'} = $linklife;
18180:         if ($current{'resetlink'}) {
18181:             if ($current{'resetlink'} ne $linklife) {
18182:                 $changes{'reset'} = 1;
18183:             }
18184:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18185:             if ($staticdefaults{'resetlink'} ne $linklife) {
18186:                 $changes{'reset'} = 1;
18187:             }
18188:         }
18189:     } elsif ($current{'resetlink'}) {
18190:         $changes{'reset'} = 1;
18191:     }
18192:     my @casesens;
18193:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
18194:     foreach my $case (sort(@posscase)) {
18195:         if (grep(/^\Q$case\E$/,@oktypes)) {
18196:             push(@casesens,$case);
18197:         }
18198:     }
18199:     $newvalues{'resetcase'} = \@casesens;
18200:     if (ref($current{'resetcase'}) eq 'ARRAY') {
18201:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
18202:         if (@diffs > 0) {
18203:             $changes{'reset'} = 1;
18204:         }
18205:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18206:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
18207:         if (@diffs > 0) {
18208:             $changes{'reset'} = 1;
18209:         }
18210:     }
18211:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
18212:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
18213:         if (exists($current{'resetprelink'})) {
18214:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
18215:                 $changes{'reset'} = 1;
18216:             }
18217:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18218:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
18219:                 $changes{'reset'} = 1;
18220:             }
18221:         }
18222:     } elsif ($current{'resetprelink'}) {
18223:         $changes{'reset'} = 1;
18224:     }
18225:     foreach my $type (@oktypes) {
18226:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
18227:         my @postlink;
18228:         foreach my $item (sort(@possplink)) {
18229:             if ($item =~ /^(email|username)$/) {
18230:                 push(@postlink,$item);
18231:             }
18232:         }
18233:         $newvalues{'resetpostlink'}{$type} = \@postlink;
18234:         unless ($changes{'reset'}) {
18235:             if (ref($current{'resetpostlink'}) eq 'HASH') {
18236:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
18237:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
18238:                     if (@diffs > 0) {
18239:                         $changes{'reset'} = 1;
18240:                     }
18241:                 } else {
18242:                     $changes{'reset'} = 1;
18243:                 }
18244:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18245:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
18246:                 if (@diffs > 0) {
18247:                     $changes{'reset'} = 1;
18248:                 }
18249:             }
18250:         }
18251:     }
18252:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
18253:     my @resetemail;
18254:     foreach my $item (sort(@possemailsrc)) {
18255:         if ($item =~ /^(permanent|critical|notify)$/) {
18256:             push(@resetemail,$item);
18257:         }
18258:     }
18259:     $newvalues{'resetemail'} = \@resetemail;
18260:     unless ($changes{'reset'}) {
18261:         if (ref($current{'resetemail'}) eq 'ARRAY') {
18262:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
18263:             if (@diffs > 0) {
18264:                 $changes{'reset'} = 1;
18265:             }
18266:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18267:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
18268:             if (@diffs > 0) {
18269:                 $changes{'reset'} = 1;
18270:             }
18271:         }
18272:     }
18273:     if ($env{'form.passwords_stdtext'} == 0) {
18274:         $newvalues{'resetremove'} = 1;
18275:         unless ($current{'resetremove'}) {
18276:             $changes{'reset'} = 1;
18277:         }
18278:     } elsif ($current{'resetremove'}) {
18279:         $changes{'reset'} = 1;
18280:     }
18281:     if ($env{'form.passwords_customfile.filename'} ne '') {
18282:         my $servadm = $r->dir_config('lonAdmEMail');
18283:         my ($configuserok,$author_ok,$switchserver) =
18284:             &config_check($dom,$confname,$servadm);
18285:         my $error;
18286:         if ($configuserok eq 'ok') {
18287:             if ($switchserver) {
18288:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
18289:             } else {
18290:                 if ($author_ok eq 'ok') {
18291:                     my ($result,$customurl) =
18292:                         &publishlogo($r,'upload','passwords_customfile',$dom,
18293:                                      $confname,'customtext/resetpw','','',$customfn);
18294:                     if ($result eq 'ok') {
18295:                         $newvalues{'resetcustom'} = $customurl;
18296:                         $changes{'reset'} = 1;
18297:                     } else {
18298:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
18299:                     }
18300:                 } else {
18301:                     $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);
18302:                 }
18303:             }
18304:         } else {
18305:             $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);
18306:         }
18307:         if ($error) {
18308:             &Apache::lonnet::logthis($error);
18309:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
18310:         }
18311:     } elsif ($current{'resetcustom'}) {
18312:         if ($env{'form.passwords_custom_del'}) {
18313:             $changes{'reset'} = 1;
18314:         } else {
18315:             $newvalues{'resetcustom'} = $current{'resetcustom'};
18316:         }
18317:     }
18318:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
18319:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
18320:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
18321:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
18322:             $changes{'intauth'} = 1;
18323:         }
18324:     } else {
18325:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
18326:     }
18327:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
18328:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
18329:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
18330:             $changes{'intauth'} = 1;
18331:         }
18332:     } else {
18333:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
18334:     }
18335:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
18336:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
18337:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
18338:             $changes{'intauth'} = 1;
18339:         }
18340:     } else {
18341:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
18342:     }
18343:     foreach my $item ('cost','check','switch') {
18344:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
18345:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
18346:             $updatedefaults = 1;
18347:         }
18348:     }
18349:     &password_rule_changes('passwords',\%newvalues,\%current,\%changes);
18350:     my %crsownerchg = (
18351:                         by => [],
18352:                         for => [],
18353:                       );
18354:     foreach my $item ('by','for') {
18355:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
18356:         foreach my $type (sort(@posstypes)) {
18357:             if (grep(/^\Q$type\E$/,@oktypes)) {
18358:                 push(@{$crsownerchg{$item}},$type);
18359:             }
18360:         }
18361:     }
18362:     $newvalues{'crsownerchg'} = \%crsownerchg;
18363:     if (ref($current{'crsownerchg'}) eq 'HASH') {
18364:         foreach my $item ('by','for') {
18365:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
18366:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
18367:                 if (@diffs > 0) {
18368:                     $changes{'crsownerchg'} = 1;
18369:                     last;
18370:                 }
18371:             }
18372:         }
18373:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
18374:         foreach my $item ('by','for') {
18375:             if (@{$crsownerchg{$item}} > 0) {
18376:                 $changes{'crsownerchg'} = 1;
18377:                 last;
18378:             }
18379:         }
18380:     }
18381: 
18382:     my %confighash = (
18383:                         defaults  => \%save_defaults,
18384:                         passwords => \%newvalues,
18385:                      );
18386:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
18387: 
18388:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
18389:     if ($putresult eq 'ok') {
18390:         if (keys(%changes) > 0) {
18391:             $resulttext = &mt('Changes made: ').'<ul>';
18392:             foreach my $key ('reset','intauth','rules','crsownerchg') {
18393:                 if ($changes{$key}) {
18394:                     unless ($key eq 'intauth') {
18395:                         $updateconf = 1;
18396:                     }
18397:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
18398:                     if ($key eq 'reset') {
18399:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
18400:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
18401:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
18402:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
18403:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
18404:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
18405:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
18406:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
18407:                             }
18408:                         } else {
18409:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
18410:                         }
18411:                         if ($confighash{'passwords'}{'resetlink'}) {
18412:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
18413:                         } else {
18414:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
18415:                                                   &mt('Will default to 2 hours').'</li>';
18416:                         }
18417:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
18418:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
18419:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
18420:                             } else {
18421:                                 my $casesens;
18422:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
18423:                                     if ($type eq 'default') {
18424:                                         $casesens .= $othertitle.', ';
18425:                                     } elsif ($usertypes->{$type} ne '') {
18426:                                         $casesens .= $usertypes->{$type}.', ';
18427:                                     }
18428:                                 }
18429:                                 $casesens =~ s/\Q, \E$//;
18430:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
18431:                             }
18432:                         } else {
18433:                             $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>';
18434:                         }
18435:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
18436:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
18437:                         } else {
18438:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
18439:                         }
18440:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
18441:                             my $output;
18442:                             if (ref($types) eq 'ARRAY') {
18443:                                 foreach my $type (@{$types}) {
18444:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
18445:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
18446:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
18447:                                         } else {
18448:                                             $output .= $usertypes->{$type}.' -- '.
18449:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
18450:                                         }
18451:                                     }
18452:                                 }
18453:                             }
18454:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
18455:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
18456:                                     $output .= $othertitle.' -- '.&mt('none');
18457:                                 } else {
18458:                                     $output .= $othertitle.' -- '.
18459:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
18460:                                 }
18461:                             }
18462:                             if ($output) {
18463:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
18464:                             } else {
18465:                                 $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>';
18466:                             }
18467:                         } else {
18468:                             $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>';
18469:                         }
18470:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
18471:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
18472:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
18473:                             } else {
18474:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
18475:                             }
18476:                         } else {
18477:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
18478:                         }
18479:                         if ($confighash{'passwords'}{'resetremove'}) {
18480:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
18481:                         } else {
18482:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
18483:                         }
18484:                         if ($confighash{'passwords'}{'resetcustom'}) {
18485:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
18486:                                                                             &mt('custom text'),600,500,undef,undef,
18487:                                                                             undef,undef,'background-color:#ffffff');
18488:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
18489:                         } else {
18490:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
18491:                         }
18492:                     } elsif ($key eq 'intauth') {
18493:                         foreach my $item ('cost','switch','check') {
18494:                             my $value = $save_defaults{$key.'_'.$item};
18495:                             if ($item eq 'switch') {
18496:                                 my %optiondesc = &Apache::lonlocal::texthash (
18497:                                                      0 => 'No',
18498:                                                      1 => 'Yes',
18499:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
18500:                                                  );
18501:                                 if ($value =~ /^(0|1|2)$/) {
18502:                                     $value = $optiondesc{$value};
18503:                                 } else {
18504:                                     $value = &mt('none -- defaults to No');
18505:                                 }
18506:                             } elsif ($item eq 'check') {
18507:                                 my %optiondesc = &Apache::lonlocal::texthash (
18508:                                                      0 => 'No',
18509:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
18510:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
18511:                                                  );
18512:                                 if ($value =~ /^(0|1|2)$/) {
18513:                                     $value = $optiondesc{$value};
18514:                                 } else {
18515:                                     $value = &mt('none -- defaults to No');
18516:                                 }
18517:                             }
18518:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
18519:                         }
18520:                     } elsif ($key eq 'rules') {
18521:                         foreach my $rule ('min','max','expire','numsaved') {
18522:                             if ($confighash{'passwords'}{$rule} eq '') {
18523:                                 if ($rule eq 'min') {
18524:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
18525:                                                    ' '.&mt('Default of [_1] will be used',
18526:                                                            $Apache::lonnet::passwdmin).'</li>';
18527:                                 } else {
18528:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
18529:                                 }
18530:                             } else {
18531:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
18532:                             }
18533:                         }
18534:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
18535:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
18536:                                 my %rulenames = &Apache::lonlocal::texthash(
18537:                                                      uc => 'At least one upper case letter',
18538:                                                      lc => 'At least one lower case letter',
18539:                                                      num => 'At least one number',
18540:                                                      spec => 'At least one non-alphanumeric',
18541:                                                    );
18542:                                 my $needed = '<ul><li>'.
18543:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
18544:                                              '</li></ul>'; 
18545:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
18546:                             } else {
18547:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
18548:                             }
18549:                         } else {
18550:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
18551:                         }
18552:                     } elsif ($key eq 'crsownerchg') {
18553:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
18554:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
18555:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
18556:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
18557:                             } else {
18558:                                 my %crsownerstr;
18559:                                 foreach my $item ('by','for') {
18560:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
18561:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
18562:                                             if ($type eq 'default') {
18563:                                                 $crsownerstr{$item} .= $othertitle.', ';
18564:                                             } elsif ($usertypes->{$type} ne '') {
18565:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
18566:                                             }
18567:                                         }
18568:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
18569:                                     }
18570:                                 }
18571:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
18572:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
18573:                             }
18574:                         } else {
18575:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
18576:                         }
18577:                     }
18578:                     $resulttext .= '</ul></li>';
18579:                 }
18580:             }
18581:             $resulttext .= '</ul>';
18582:         } else {
18583:             $resulttext = &mt('No changes made to password settings');
18584:         }
18585:         my $cachetime = 24*60*60;
18586:         if ($updatedefaults) {
18587:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18588:             if (ref($lastactref) eq 'HASH') {
18589:                 $lastactref->{'domdefaults'} = 1;
18590:             }
18591:         }
18592:         if ($updateconf) {
18593:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
18594:             if (ref($lastactref) eq 'HASH') {
18595:                 $lastactref->{'passwdconf'} = 1;
18596:             }
18597:         }
18598:     } else {
18599:         $resulttext = '<span class="LC_error">'.
18600:             &mt('An error occurred: [_1]',$putresult).'</span>';
18601:     }
18602:     if ($errors) {
18603:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
18604:                        $errors.'</ul></p>';
18605:     }
18606:     return $resulttext;
18607: }
18608: 
18609: sub password_rule_changes {
18610:     my ($prefix,$newvalues,$current,$changes) = @_;
18611:     return unless ((ref($newvalues) eq 'HASH') &&
18612:                    (ref($current) eq 'HASH') &&
18613:                    (ref($changes) eq 'HASH'));
18614:     my (@rules,%staticdefaults);
18615:     if ($prefix eq 'passwords') {
18616:         @rules = ('min','max','expire','numsaved');
18617:     } elsif ($prefix eq 'secrets') {
18618:         @rules = ('min','max');
18619:     }
18620:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
18621:     foreach my $rule (@rules) {
18622:         $env{'form.'.$prefix.'_'.$rule} =~ s/^\s+|\s+$//g;
18623:         my $ruleok;
18624:         if ($rule eq 'expire') {
18625:             if (($env{'form.'.$prefix.'_'.$rule} =~ /^\d+(|\.\d*)$/) &&
18626:                 ($env{'form.'.$prefix.'_'.$rule} ne '0')) {
18627:                 $ruleok = 1;
18628:             }
18629:         } elsif ($rule eq 'min') {
18630:             if ($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) {
18631:                 if ($env{'form.'.$prefix.'_'.$rule} >= $staticdefaults{$rule}) {
18632:                     $ruleok = 1;
18633:                 }
18634:             }
18635:         } elsif (($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) &&
18636:                  ($env{'form.'.$prefix.'_'.$rule} ne '0')) {
18637:             $ruleok = 1;
18638:         }
18639:         if ($ruleok) {
18640:             $newvalues->{$rule} = $env{'form.'.$prefix.'_'.$rule};
18641:             if (exists($current->{$rule})) {
18642:                 if ($newvalues->{$rule} ne $current->{$rule}) {
18643:                     $changes->{'rules'} = 1;
18644:                 }
18645:             } elsif ($rule eq 'min') {
18646:                 if ($staticdefaults{$rule} ne $newvalues->{$rule}) {
18647:                     $changes->{'rules'} = 1;
18648:                 }
18649:             } else {
18650:                 $changes->{'rules'} = 1;
18651:             }
18652:         } elsif (exists($current->{$rule})) {
18653:             $changes->{'rules'} = 1;
18654:         }
18655:     }
18656:     my @posschars = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_chars');
18657:     my @chars;
18658:     foreach my $item (sort(@posschars)) {
18659:         if ($item =~ /^(uc|lc|num|spec)$/) {
18660:             push(@chars,$item);
18661:         }
18662:     }
18663:     $newvalues->{'chars'} = \@chars;
18664:     unless ($changes->{'rules'}) {
18665:         if (ref($current->{'chars'}) eq 'ARRAY') {
18666:             my @diffs = &Apache::loncommon::compare_arrays($current->{'chars'},\@chars);
18667:             if (@diffs > 0) {
18668:                 $changes->{'rules'} = 1;
18669:             }
18670:         } else {
18671:             if (@chars > 0) {
18672:                 $changes->{'rules'} = 1;
18673:             }
18674:         }
18675:     }
18676:     return;
18677: }
18678: 
18679: sub modify_usercreation {
18680:     my ($dom,%domconfig) = @_;
18681:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
18682:     my $warningmsg;
18683:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
18684:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
18685:             if ($key eq 'cancreate') {
18686:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
18687:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
18688:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
18689:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18690:                         } else {
18691:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18692:                         }
18693:                     }
18694:                 }
18695:             } elsif ($key eq 'email_rule') {
18696:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
18697:             } else {
18698:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
18699:             }
18700:         }
18701:     }
18702:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
18703:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
18704:     my @contexts = ('author','course','requestcrs');
18705:     foreach my $item(@contexts) {
18706:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
18707:     }
18708:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
18709:         foreach my $item (@contexts) {
18710:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
18711:                 push(@{$changes{'cancreate'}},$item);
18712:             }
18713:         }
18714:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
18715:         foreach my $item (@contexts) {
18716:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
18717:                 if ($cancreate{$item} ne 'any') {
18718:                     push(@{$changes{'cancreate'}},$item);
18719:                 }
18720:             } else {
18721:                 if ($cancreate{$item} ne 'none') {
18722:                     push(@{$changes{'cancreate'}},$item);
18723:                 }
18724:             }
18725:         }
18726:     } else {
18727:         foreach my $item (@contexts)  {
18728:             push(@{$changes{'cancreate'}},$item);
18729:         }
18730:     }
18731: 
18732:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
18733:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
18734:             if (!grep(/^\Q$type\E$/,@username_rule)) {
18735:                 push(@{$changes{'username_rule'}},$type);
18736:             }
18737:         }
18738:         foreach my $type (@username_rule) {
18739:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
18740:                 push(@{$changes{'username_rule'}},$type);
18741:             }
18742:         }
18743:     } else {
18744:         push(@{$changes{'username_rule'}},@username_rule);
18745:     }
18746: 
18747:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
18748:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
18749:             if (!grep(/^\Q$type\E$/,@id_rule)) {
18750:                 push(@{$changes{'id_rule'}},$type);
18751:             }
18752:         }
18753:         foreach my $type (@id_rule) {
18754:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
18755:                 push(@{$changes{'id_rule'}},$type);
18756:             }
18757:         }
18758:     } else {
18759:         push(@{$changes{'id_rule'}},@id_rule);
18760:     }
18761: 
18762:     my @authen_contexts = ('author','course','domain');
18763:     my @authtypes = ('int','krb4','krb5','loc','lti');
18764:     my %authhash;
18765:     foreach my $item (@authen_contexts) {
18766:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
18767:         foreach my $auth (@authtypes) {
18768:             if (grep(/^\Q$auth\E$/,@authallowed)) {
18769:                 $authhash{$item}{$auth} = 1;
18770:             } else {
18771:                 $authhash{$item}{$auth} = 0;
18772:             }
18773:         }
18774:     }
18775:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
18776:         foreach my $item (@authen_contexts) {
18777:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
18778:                 foreach my $auth (@authtypes) {
18779:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
18780:                         push(@{$changes{'authtypes'}},$item);
18781:                         last;
18782:                     }
18783:                 }
18784:             }
18785:         }
18786:     } else {
18787:         foreach my $item (@authen_contexts) {
18788:             push(@{$changes{'authtypes'}},$item);
18789:         }
18790:     }
18791: 
18792:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
18793:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
18794:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
18795:     $save_usercreate{'id_rule'} = \@id_rule;
18796:     $save_usercreate{'username_rule'} = \@username_rule,
18797:     $save_usercreate{'authtypes'} = \%authhash;
18798: 
18799:     my %usercreation_hash =  (
18800:         usercreation     => \%save_usercreate,
18801:     );
18802: 
18803:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
18804:                                              $dom);
18805: 
18806:     if ($putresult eq 'ok') {
18807:         if (keys(%changes) > 0) {
18808:             $resulttext = &mt('Changes made:').'<ul>';
18809:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
18810:                 my %lt = &usercreation_types();
18811:                 foreach my $type (@{$changes{'cancreate'}}) {
18812:                     my $chgtext = $lt{$type}.', ';
18813:                     if ($cancreate{$type} eq 'none') {
18814:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
18815:                     } elsif ($cancreate{$type} eq 'any') {
18816:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
18817:                     } elsif ($cancreate{$type} eq 'official') {
18818:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
18819:                     } elsif ($cancreate{$type} eq 'unofficial') {
18820:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
18821:                     }
18822:                     $resulttext .= '<li>'.$chgtext.'</li>';
18823:                 }
18824:             }
18825:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
18826:                 my ($rules,$ruleorder) = 
18827:                     &Apache::lonnet::inst_userrules($dom,'username');
18828:                 my $chgtext = '<ul>';
18829:                 foreach my $type (@username_rule) {
18830:                     if (ref($rules->{$type}) eq 'HASH') {
18831:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
18832:                     }
18833:                 }
18834:                 $chgtext .= '</ul>';
18835:                 if (@username_rule > 0) {
18836:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
18837:                 } else {
18838:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
18839:                 }
18840:             }
18841:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
18842:                 my ($idrules,$idruleorder) = 
18843:                     &Apache::lonnet::inst_userrules($dom,'id');
18844:                 my $chgtext = '<ul>';
18845:                 foreach my $type (@id_rule) {
18846:                     if (ref($idrules->{$type}) eq 'HASH') {
18847:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
18848:                     }
18849:                 }
18850:                 $chgtext .= '</ul>';
18851:                 if (@id_rule > 0) {
18852:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
18853:                 } else {
18854:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
18855:                 }
18856:             }
18857:             my %authname = &authtype_names();
18858:             my %context_title = &context_names();
18859:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
18860:                 my $chgtext = '<ul>';
18861:                 foreach my $type (@{$changes{'authtypes'}}) {
18862:                     my @allowed;
18863:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
18864:                     foreach my $auth (@authtypes) {
18865:                         if ($authhash{$type}{$auth}) {
18866:                             push(@allowed,$authname{$auth});
18867:                         }
18868:                     }
18869:                     if (@allowed > 0) {
18870:                         $chgtext .= join(', ',@allowed).'</li>';
18871:                     } else {
18872:                         $chgtext .= &mt('none').'</li>';
18873:                     }
18874:                 }
18875:                 $chgtext .= '</ul>';
18876:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
18877:                 $resulttext .= '</li>';
18878:             }
18879:             $resulttext .= '</ul>';
18880:         } else {
18881:             $resulttext = &mt('No changes made to user creation settings');
18882:         }
18883:     } else {
18884:         $resulttext = '<span class="LC_error">'.
18885:             &mt('An error occurred: [_1]',$putresult).'</span>';
18886:     }
18887:     if ($warningmsg ne '') {
18888:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
18889:     }
18890:     return $resulttext;
18891: }
18892: 
18893: sub modify_selfcreation {
18894:     my ($dom,$lastactref,%domconfig) = @_;
18895:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
18896:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
18897:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18898:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
18899:     if (ref($typesref) eq 'ARRAY') {
18900:         @types = @{$typesref};
18901:     }
18902:     if (ref($usertypesref) eq 'HASH') {
18903:         %usertypes = %{$usertypesref};
18904:     }
18905:     $usertypes{'default'} = $othertitle;
18906: #
18907: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
18908: #
18909:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
18910:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
18911:             if ($key eq 'cancreate') {
18912:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
18913:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
18914:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
18915:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
18916:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
18917:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
18918:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
18919:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
18920:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18921:                         } else {
18922:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18923:                         }
18924:                     }
18925:                 }
18926:             } elsif ($key eq 'email_rule') {
18927:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
18928:             } else {
18929:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
18930:             }
18931:         }
18932:     }
18933: #
18934: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
18935: #
18936:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
18937:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
18938:             if ($key eq 'selfcreate') {
18939:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
18940:             } else {
18941:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
18942:             }
18943:         }
18944:     }
18945: #
18946: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
18947: #
18948:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
18949:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
18950:             if ($key eq 'inststatusguest') {
18951:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
18952:             } else {
18953:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
18954:             }
18955:         }
18956:     }
18957: 
18958:     my @contexts = ('selfcreate');
18959:     @{$cancreate{'selfcreate'}} = ();
18960:     %{$cancreate{'emailusername'}} = ();
18961:     if (@types) {
18962:         @{$cancreate{'statustocreate'}} = ();
18963:     }
18964:     %{$cancreate{'selfcreateprocessing'}} = ();
18965:     %{$cancreate{'shibenv'}} = ();
18966:     %{$cancreate{'emailverified'}} = ();
18967:     %{$cancreate{'emailoptions'}} = ();
18968:     %{$cancreate{'emaildomain'}} = ();
18969:     my %selfcreatetypes = (
18970:                              sso   => 'users authenticated by institutional single sign on',
18971:                              login => 'users authenticated by institutional log-in',
18972:                              email => 'users verified by e-mail',
18973:                           );
18974: #
18975: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
18976: # is permitted.
18977: #
18978:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
18979: 
18980:     my (@statuses,%email_rule);
18981:     foreach my $item ('login','sso','email') {
18982:         if ($item eq 'email') {
18983:             if ($env{'form.cancreate_email'}) {
18984:                 if (@types) {
18985:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
18986:                     foreach my $status (@poss_statuses) {
18987:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
18988:                             push(@statuses,$status);
18989:                         }
18990:                     }
18991:                     $save_inststatus{'inststatusguest'} = \@statuses;
18992:                 } else {
18993:                     push(@statuses,'default');
18994:                 }
18995:                 if (@statuses) {
18996:                     my %curr_rule;
18997:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
18998:                         foreach my $type (@statuses) {
18999:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
19000:                         }
19001:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
19002:                         foreach my $type (@statuses) {
19003:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
19004:                         }
19005:                     }
19006:                     push(@{$cancreate{'selfcreate'}},'email');
19007:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
19008:                     my %curremaildom;
19009:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
19010:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
19011:                     }
19012:                     foreach my $type (@statuses) {
19013:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
19014:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
19015:                         }
19016:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
19017:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
19018:                         }
19019:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
19020: #
19021: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
19022: #
19023:                             my $chosen = $1;
19024:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
19025:                                 my $emaildom;
19026:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
19027:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type}; 
19028:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
19029:                                     if (ref($curremaildom{$type}) eq 'HASH') {
19030:                                         if (exists($curremaildom{$type}{$chosen})) {
19031:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
19032:                                                 push(@{$changes{'cancreate'}},'emaildomain');
19033:                                             }
19034:                                         } elsif ($emaildom ne '') {
19035:                                             push(@{$changes{'cancreate'}},'emaildomain');
19036:                                         }
19037:                                     } elsif ($emaildom ne '') {
19038:                                         push(@{$changes{'cancreate'}},'emaildomain');
19039:                                     } 
19040:                                 }
19041:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
19042:                             } elsif ($chosen eq 'custom') {
19043:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
19044:                                 $email_rule{$type} = [];
19045:                                 if (ref($emailrules) eq 'HASH') {
19046:                                     foreach my $rule (@possemail_rules) {
19047:                                         if (exists($emailrules->{$rule})) {
19048:                                             push(@{$email_rule{$type}},$rule);
19049:                                         }
19050:                                     }
19051:                                 }
19052:                                 if (@{$email_rule{$type}}) {
19053:                                     $cancreate{'emailoptions'}{$type} = 'custom';
19054:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
19055:                                         if (@{$curr_rule{$type}} > 0) {
19056:                                             foreach my $rule (@{$curr_rule{$type}}) {
19057:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
19058:                                                     push(@{$changes{'email_rule'}},$type);
19059:                                                 }
19060:                                             }
19061:                                         }
19062:                                         foreach my $type (@{$email_rule{$type}}) {
19063:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
19064:                                                 push(@{$changes{'email_rule'}},$type);
19065:                                             }
19066:                                         }
19067:                                     } else {
19068:                                         push(@{$changes{'email_rule'}},$type);
19069:                                     }
19070:                                 }
19071:                             } else {
19072:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
19073:                             }
19074:                         }
19075:                     }
19076:                     if (@types) {
19077:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
19078:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
19079:                             if (@changed) {
19080:                                 push(@{$changes{'inststatus'}},'inststatusguest');
19081:                             }
19082:                         } else {
19083:                             push(@{$changes{'inststatus'}},'inststatusguest');
19084:                         }
19085:                     }
19086:                 } else {
19087:                     delete($env{'form.cancreate_email'});
19088:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
19089:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
19090:                             push(@{$changes{'inststatus'}},'inststatusguest');
19091:                         }
19092:                     }
19093:                 }
19094:             } else {
19095:                 $save_inststatus{'inststatusguest'} = [];
19096:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
19097:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
19098:                         push(@{$changes{'inststatus'}},'inststatusguest');
19099:                     }
19100:                 }
19101:             }
19102:         } else {
19103:             if ($env{'form.cancreate_'.$item}) {
19104:                 push(@{$cancreate{'selfcreate'}},$item);
19105:             }
19106:         }
19107:     }
19108:     my (%userinfo,%savecaptcha);
19109:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
19110: #
19111: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
19112: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
19113: #
19114: 
19115:     if ($env{'form.cancreate_email'}) {
19116:         push(@contexts,'emailusername');
19117:         if (@statuses) {
19118:             foreach my $type (@statuses) {
19119:                 if (ref($infofields) eq 'ARRAY') {
19120:                     foreach my $field (@{$infofields}) {
19121:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
19122:                             $cancreate{'emailusername'}{$type}{$field} = $1;
19123:                         }
19124:                     }
19125:                 }
19126:             }
19127:         }
19128: #
19129: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
19130: # queued requests for self-creation of account verified by e-mail.
19131: #
19132: 
19133:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
19134:         @approvalnotify = sort(@approvalnotify);
19135:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
19136:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
19137:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
19138:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
19139:                     push(@{$changes{'cancreate'}},'notify');
19140:                 }
19141:             } else {
19142:                 if ($cancreate{'notify'}{'approval'}) {
19143:                     push(@{$changes{'cancreate'}},'notify');
19144:                 }
19145:             }
19146:         } elsif ($cancreate{'notify'}{'approval'}) {
19147:             push(@{$changes{'cancreate'}},'notify');
19148:         }
19149: 
19150:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
19151:     }
19152: #  
19153: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
19154: # institutional log-in.
19155: #
19156:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
19157:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
19158:                ($domdefaults{'auth_def'} eq 'localauth'))) {
19159:             $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.').' '.
19160:                           &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.');
19161:         }
19162:     }
19163:     my @fields = ('lastname','firstname','middlename','generation',
19164:                   'permanentemail','id');
19165:     my @shibfields = (@fields,'inststatus');
19166:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19167: #
19168: # Where usernames may created for institutional log-in and/or institutional single sign on:
19169: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
19170: # may self-create accounts 
19171: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
19172: # which the user may supply, if institutional data is unavailable.
19173: #
19174:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
19175:         if (@types) {
19176:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
19177:             push(@contexts,'statustocreate');
19178:             foreach my $type (@types) {
19179:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
19180:                 foreach my $field (@fields) {
19181:                     if (grep(/^\Q$field\E$/,@modifiable)) {
19182:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
19183:                     } else {
19184:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
19185:                     }
19186:                 }
19187:             }
19188:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
19189:                 foreach my $type (@types) {
19190:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
19191:                         foreach my $field (@fields) {
19192:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
19193:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
19194:                                 push(@{$changes{'selfcreate'}},$type);
19195:                                 last;
19196:                             }
19197:                         }
19198:                     }
19199:                 }
19200:             } else {
19201:                 foreach my $type (@types) {
19202:                     push(@{$changes{'selfcreate'}},$type);
19203:                 }
19204:             }
19205:         }
19206:         foreach my $field (@shibfields) {
19207:             if ($env{'form.shibenv_'.$field} ne '') {
19208:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
19209:             }
19210:         }
19211:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
19212:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
19213:                 foreach my $field (@shibfields) {
19214:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
19215:                         push(@{$changes{'cancreate'}},'shibenv');
19216:                     }
19217:                 }
19218:             } else {
19219:                 foreach my $field (@shibfields) {
19220:                     if ($env{'form.shibenv_'.$field}) {
19221:                         push(@{$changes{'cancreate'}},'shibenv');
19222:                         last;
19223:                     }
19224:                 }
19225:             }
19226:         }
19227:     }
19228:     foreach my $item (@contexts) {
19229:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
19230:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
19231:                 if (ref($cancreate{$item}) eq 'ARRAY') {
19232:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
19233:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19234:                             push(@{$changes{'cancreate'}},$item);
19235:                         }
19236:                     }
19237:                 }
19238:             }
19239:             if (ref($cancreate{$item}) eq 'ARRAY') {
19240:                 foreach my $type (@{$cancreate{$item}}) {
19241:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
19242:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19243:                             push(@{$changes{'cancreate'}},$item);
19244:                         }
19245:                     }
19246:                 }
19247:             }
19248:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
19249:             if (ref($cancreate{$item}) eq 'HASH') {
19250:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
19251:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
19252:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
19253:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
19254:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19255:                                     push(@{$changes{'cancreate'}},$item);
19256:                                 }
19257:                             }
19258:                         }
19259:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
19260:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
19261:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19262:                                 push(@{$changes{'cancreate'}},$item);
19263:                             }
19264:                         }
19265:                     }
19266:                 }
19267:                 foreach my $type (keys(%{$cancreate{$item}})) {
19268:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
19269:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
19270:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
19271:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
19272:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19273:                                         push(@{$changes{'cancreate'}},$item);
19274:                                     }
19275:                                 }
19276:                             } else {
19277:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19278:                                     push(@{$changes{'cancreate'}},$item);
19279:                                 }
19280:                             }
19281:                         }
19282:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
19283:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
19284:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19285:                                 push(@{$changes{'cancreate'}},$item);
19286:                             }
19287:                         }
19288:                     }
19289:                 }
19290:             }
19291:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
19292:             if (ref($cancreate{$item}) eq 'ARRAY') {
19293:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
19294:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19295:                         push(@{$changes{'cancreate'}},$item);
19296:                     }
19297:                 }
19298:             }
19299:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
19300:             if (ref($cancreate{$item}) eq 'HASH') {
19301:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19302:                     push(@{$changes{'cancreate'}},$item);
19303:                 }
19304:             }
19305:         } elsif ($item eq 'emailusername') {
19306:             if (ref($cancreate{$item}) eq 'HASH') {
19307:                 foreach my $type (keys(%{$cancreate{$item}})) {
19308:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
19309:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
19310:                             if ($cancreate{$item}{$type}{$field}) {
19311:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19312:                                     push(@{$changes{'cancreate'}},$item);
19313:                                 }
19314:                                 last;
19315:                             }
19316:                         }
19317:                     }
19318:                 }
19319:             }
19320:         }
19321:     }
19322: #
19323: # Populate %save_usercreate hash with updates to self-creation configuration.
19324: #
19325:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
19326:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
19327:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
19328:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
19329:     if (ref($cancreate{'notify'}) eq 'HASH') {
19330:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
19331:     }
19332:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
19333:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
19334:     }
19335:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
19336:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
19337:     }
19338:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
19339:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
19340:     }
19341:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
19342:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
19343:     }
19344:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
19345:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
19346:     }
19347:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
19348:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
19349:     }
19350:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
19351:     $save_usercreate{'email_rule'} = \%email_rule;
19352: 
19353:     my %userconfig_hash = (
19354:             usercreation     => \%save_usercreate,
19355:             usermodification => \%save_usermodify,
19356:             inststatus       => \%save_inststatus,
19357:     );
19358: 
19359:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
19360:                                              $dom);
19361: #
19362: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
19363: #
19364:     if ($putresult eq 'ok') {
19365:         if (keys(%changes) > 0) {
19366:             $resulttext = &mt('Changes made:').'<ul>';
19367:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
19368:                 my %lt = &selfcreation_types();
19369:                 foreach my $type (@{$changes{'cancreate'}}) {
19370:                     my $chgtext = '';
19371:                     if ($type eq 'selfcreate') {
19372:                         if (@{$cancreate{$type}} == 0) {
19373:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
19374:                         } else {
19375:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
19376:                                         '<ul>';
19377:                             foreach my $case (@{$cancreate{$type}}) {
19378:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
19379:                             }
19380:                             $chgtext .= '</ul>';
19381:                             if (ref($cancreate{$type}) eq 'ARRAY') {
19382:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
19383:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
19384:                                         if (@{$cancreate{'statustocreate'}} == 0) {
19385:                                             $chgtext .= '<span class="LC_warning">'.
19386:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
19387:                                                         '</span><br />';
19388:                                         }
19389:                                     }
19390:                                 }
19391:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
19392:                                     if (!@statuses) {
19393:                                         $chgtext .= '<span class="LC_warning">'.
19394:                                                     &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.").
19395:                                                     '</span><br />';
19396: 
19397:                                     }
19398:                                 }
19399:                             }
19400:                         }
19401:                     } elsif ($type eq 'shibenv') {
19402:                         if (keys(%{$cancreate{$type}}) == 0) {
19403:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
19404:                         } else {
19405:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
19406:                                         '<ul>';
19407:                             foreach my $field (@shibfields) {
19408:                                 next if ($cancreate{$type}{$field} eq '');
19409:                                 if ($field eq 'inststatus') {
19410:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
19411:                                 } else {
19412:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
19413:                                 }
19414:                             }
19415:                             $chgtext .= '</ul>';
19416:                         }
19417:                     } elsif ($type eq 'statustocreate') {
19418:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
19419:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
19420:                             if (@{$cancreate{'selfcreate'}} > 0) {
19421:                                 if (@{$cancreate{'statustocreate'}} == 0) {
19422:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
19423:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
19424:                                         $chgtext .= '<br />'.
19425:                                                     '<span class="LC_warning">'.
19426:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
19427:                                                     '</span>';
19428:                                     }
19429:                                 } elsif (keys(%usertypes) > 0) {
19430:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
19431:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
19432:                                     } else {
19433:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
19434:                                     }
19435:                                     $chgtext .= '<ul>';
19436:                                     foreach my $case (@{$cancreate{$type}}) {
19437:                                         if ($case eq 'default') {
19438:                                             $chgtext .= '<li>'.$othertitle.'</li>';
19439:                                         } else {
19440:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
19441:                                         }
19442:                                     }
19443:                                     $chgtext .= '</ul>';
19444:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
19445:                                         $chgtext .= '<span class="LC_warning">'.
19446:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
19447:                                                     '</span>';
19448:                                     }
19449:                                 }
19450:                             } else {
19451:                                 if (@{$cancreate{$type}} == 0) {
19452:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
19453:                                 } else {
19454:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
19455:                                 }
19456:                             }
19457:                             $chgtext .= '<br />';
19458:                         }
19459:                     } elsif ($type eq 'selfcreateprocessing') {
19460:                         my %choices = &Apache::lonlocal::texthash (
19461:                                                                     automatic => 'Automatic approval',
19462:                                                                     approval  => 'Queued for approval',
19463:                                                                   );
19464:                         if (@types) {
19465:                             if (@statuses) {
19466:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:'). 
19467:                                             '<ul>';
19468:                                 foreach my $status (@statuses) {
19469:                                     if ($status eq 'default') {
19470:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
19471:                                     } else {
19472:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
19473:                                     }
19474:                                 }
19475:                                 $chgtext .= '</ul>';
19476:                             }
19477:                         } else {
19478:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
19479:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
19480:                         }
19481:                     } elsif ($type eq 'emailverified') {
19482:                         my %options = &Apache::lonlocal::texthash (
19483:                                                                     all   => 'Same as e-mail',
19484:                                                                     first => 'Omit @domain',
19485:                                                                     free  => 'Free to choose',
19486:                                                                   );
19487:                         if (@types) {
19488:                             if (@statuses) {
19489:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
19490:                                             '<ul>';
19491:                                 foreach my $status (@statuses) {
19492:                                     if ($status eq 'default') {
19493:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
19494:                                     } else {
19495:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
19496:                                     }
19497:                                 }
19498:                                 $chgtext .= '</ul>';
19499:                             }
19500:                         } else {
19501:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
19502:                                             $options{$cancreate{'emailverified'}{'default'}});
19503:                         }
19504:                     } elsif ($type eq 'emailoptions') {
19505:                         my %options = &Apache::lonlocal::texthash (
19506:                                                                     any     => 'Any e-mail',
19507:                                                                     inst    => 'Institutional only',
19508:                                                                     noninst => 'Non-institutional only',
19509:                                                                     custom  => 'Custom restrictions',
19510:                                                                   );
19511:                         if (@types) {
19512:                             if (@statuses) {
19513:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
19514:                                             '<ul>';
19515:                                 foreach my $status (@statuses) {
19516:                                     if ($type eq 'default') {
19517:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
19518:                                     } else {
19519:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
19520:                                     }
19521:                                 }
19522:                                 $chgtext .= '</ul>';
19523:                             }
19524:                         } else {
19525:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
19526:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
19527:                             } else {
19528:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
19529:                                                 $options{$cancreate{'emailoptions'}{'default'}});
19530:                             }
19531:                         }
19532:                     } elsif ($type eq 'emaildomain') {
19533:                         my $output;
19534:                         if (@statuses) {
19535:                             foreach my $type (@statuses) {
19536:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
19537:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
19538:                                         if ($type eq 'default') {
19539:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19540:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
19541:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
19542:                                             } else {
19543:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
19544:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
19545:                                             }
19546:                                         } else {
19547:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19548:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
19549:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
19550:                                             } else {
19551:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
19552:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>'; 
19553:                                             }
19554:                                         }
19555:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
19556:                                         if ($type eq 'default') {
19557:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19558:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
19559:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
19560:                                             } else {
19561:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
19562:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
19563:                                             }
19564:                                         } else {
19565:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19566:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
19567:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
19568:                                             } else {
19569:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
19570:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';   
19571:                                             }
19572:                                         }
19573:                                     }
19574:                                 }
19575:                             }
19576:                         }
19577:                         if ($output ne '') {
19578:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
19579:                                         '<ul>'.$output.'</ul>';
19580:                         }
19581:                     } elsif ($type eq 'captcha') {
19582:                         if ($savecaptcha{$type} eq 'notused') {
19583:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
19584:                         } else {
19585:                             my %captchas = &captcha_phrases();
19586:                             if ($captchas{$savecaptcha{$type}}) {
19587:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
19588:                             } else {
19589:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
19590:                             }
19591:                         }
19592:                     } elsif ($type eq 'recaptchakeys') {
19593:                         my ($privkey,$pubkey);
19594:                         if (ref($savecaptcha{$type}) eq 'HASH') {
19595:                             $pubkey = $savecaptcha{$type}{'public'};
19596:                             $privkey = $savecaptcha{$type}{'private'};
19597:                         }
19598:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
19599:                         if (!$pubkey) {
19600:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
19601:                         } else {
19602:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
19603:                         }
19604:                         if (!$privkey) {
19605:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
19606:                         } else {
19607:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
19608:                         }
19609:                         $chgtext .= '</ul>';
19610:                     } elsif ($type eq 'recaptchaversion') {
19611:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
19612:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
19613:                         }
19614:                     } elsif ($type eq 'emailusername') {
19615:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
19616:                             if (@statuses) {
19617:                                 foreach my $type (@statuses) {
19618:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
19619:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
19620:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
19621:                                                     '<ul>';
19622:                                             foreach my $field (@{$infofields}) {
19623:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
19624:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
19625:                                                 }
19626:                                             }
19627:                                             $chgtext .= '</ul>';
19628:                                         } else {
19629:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
19630:                                         }
19631:                                     } else {
19632:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
19633:                                     }
19634:                                 }
19635:                             }
19636:                         }
19637:                     } elsif ($type eq 'notify') {
19638:                         my $numapprove = 0;
19639:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
19640:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
19641:                                 if ($cancreate{'notify'}{'approval'}) {
19642:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
19643:                                     $numapprove ++;
19644:                                 }
19645:                             }
19646:                         }
19647:                         unless ($numapprove) {
19648:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
19649:                         }
19650:                     }
19651:                     if ($chgtext) {
19652:                         $resulttext .= '<li>'.$chgtext.'</li>';
19653:                     }
19654:                 }
19655:             }
19656:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
19657:                 my ($emailrules,$emailruleorder) =
19658:                     &Apache::lonnet::inst_userrules($dom,'email');
19659:                 foreach my $type (@{$changes{'email_rule'}}) {
19660:                     if (ref($email_rule{$type}) eq 'ARRAY') {
19661:                         my $chgtext = '<ul>';
19662:                         foreach my $rule (@{$email_rule{$type}}) {
19663:                             if (ref($emailrules->{$rule}) eq 'HASH') {
19664:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
19665:                             }
19666:                         }
19667:                         $chgtext .= '</ul>';
19668:                         my $typename;
19669:                         if (@types) {
19670:                             if ($type eq 'default') {
19671:                                 $typename = $othertitle;
19672:                             } else {
19673:                                 $typename = $usertypes{$type};
19674:                             } 
19675:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
19676:                         }
19677:                         if (@{$email_rule{$type}} > 0) {
19678:                             $resulttext .= '<li>'.
19679:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
19680:                                                $usertypes{$type}).
19681:                                            $chgtext.
19682:                                            '</li>';
19683:                         } else {
19684:                             $resulttext .= '<li>'.
19685:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
19686:                                            '</li>'.
19687:                                            &mt('(Affiliation: [_1])',$typename);
19688:                         }
19689:                     }
19690:                 }
19691:             }
19692:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
19693:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
19694:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
19695:                         my $chgtext = '<ul>';
19696:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
19697:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
19698:                         }
19699:                         $chgtext .= '</ul>';
19700:                         $resulttext .= '<li>'.
19701:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
19702:                                           $chgtext.
19703:                                        '</li>';
19704:                     } else {
19705:                         $resulttext .= '<li>'.
19706:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
19707:                                        '</li>';
19708:                     }
19709:                 }
19710:             }
19711:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
19712:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
19713:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19714:                 foreach my $type (@{$changes{'selfcreate'}}) {
19715:                     my $typename = $type;
19716:                     if (keys(%usertypes) > 0) {
19717:                         if ($usertypes{$type} ne '') {
19718:                             $typename = $usertypes{$type};
19719:                         }
19720:                     }
19721:                     my @modifiable;
19722:                     $resulttext .= '<li>'.
19723:                                     &mt('Self-creation of account by users with status: [_1]',
19724:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
19725:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
19726:                     foreach my $field (@fields) {
19727:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
19728:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
19729:                         }
19730:                     }
19731:                     if (@modifiable > 0) {
19732:                         $resulttext .= join(', ',@modifiable);
19733:                     } else {
19734:                         $resulttext .= &mt('none');
19735:                     }
19736:                     $resulttext .= '</li>';
19737:                 }
19738:                 $resulttext .= '</ul></li>';
19739:             }
19740:             $resulttext .= '</ul>';
19741:             my $cachetime = 24*60*60;
19742:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
19743:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19744:             if (ref($lastactref) eq 'HASH') {
19745:                 $lastactref->{'domdefaults'} = 1;
19746:             }
19747:         } else {
19748:             $resulttext = &mt('No changes made to self-creation settings');
19749:         }
19750:     } else {
19751:         $resulttext = '<span class="LC_error">'.
19752:             &mt('An error occurred: [_1]',$putresult).'</span>';
19753:     }
19754:     if ($warningmsg ne '') {
19755:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
19756:     }
19757:     return $resulttext;
19758: }
19759: 
19760: sub process_captcha {
19761:     my ($container,$changes,$newsettings,$currsettings) = @_;
19762:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
19763:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
19764:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
19765:         $newsettings->{'captcha'} = 'original';
19766:     }
19767:     my %current;
19768:     if (ref($currsettings) eq 'HASH') {
19769:         %current = %{$currsettings};
19770:     }
19771:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
19772:         if ($container eq 'cancreate') {
19773:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19774:                 push(@{$changes->{'cancreate'}},'captcha');
19775:             } elsif (!defined($changes->{'cancreate'})) {
19776:                 $changes->{'cancreate'} = ['captcha'];
19777:             }
19778:         } elsif ($container eq 'passwords') {
19779:             $changes->{'reset'} = 1;
19780:         } else {
19781:             $changes->{'captcha'} = 1;
19782:         }
19783:     }
19784:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
19785:     if ($newsettings->{'captcha'} eq 'recaptcha') {
19786:         $newpub = $env{'form.'.$container.'_recaptchapub'};
19787:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
19788:         $newpub =~ s/[^\w\-]//g;
19789:         $newpriv =~ s/[^\w\-]//g;
19790:         $newsettings->{'recaptchakeys'} = {
19791:                                              public  => $newpub,
19792:                                              private => $newpriv,
19793:                                           };
19794:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
19795:         $newversion =~ s/\D//g;
19796:         if ($newversion ne '2') {
19797:             $newversion = 1;
19798:         }
19799:         $newsettings->{'recaptchaversion'} = $newversion;
19800:     }
19801:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
19802:         $currpub = $current{'recaptchakeys'}{'public'};
19803:         $currpriv = $current{'recaptchakeys'}{'private'};
19804:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
19805:             $newsettings->{'recaptchakeys'} = {
19806:                                                  public  => '',
19807:                                                  private => '',
19808:                                               }
19809:         }
19810:     }
19811:     if ($current{'captcha'} eq 'recaptcha') {
19812:         $currversion = $current{'recaptchaversion'};
19813:         if ($currversion ne '2') {
19814:             $currversion = 1;
19815:         }
19816:     }
19817:     if ($currversion ne $newversion) {
19818:         if ($container eq 'cancreate') {
19819:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19820:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
19821:             } elsif (!defined($changes->{'cancreate'})) {
19822:                 $changes->{'cancreate'} = ['recaptchaversion'];
19823:             }
19824:         } elsif ($container eq 'passwords') {
19825:             $changes->{'reset'} = 1;
19826:         } else {
19827:             $changes->{'recaptchaversion'} = 1;
19828:         }
19829:     }
19830:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
19831:         if ($container eq 'cancreate') {
19832:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19833:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
19834:             } elsif (!defined($changes->{'cancreate'})) {
19835:                 $changes->{'cancreate'} = ['recaptchakeys'];
19836:             }
19837:         } elsif ($container eq 'passwords') {
19838:             $changes->{'reset'} = 1;
19839:         } else {
19840:             $changes->{'recaptchakeys'} = 1;
19841:         }
19842:     }
19843:     return;
19844: }
19845: 
19846: sub modify_usermodification {
19847:     my ($dom,%domconfig) = @_;
19848:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
19849:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
19850:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
19851:             if ($key eq 'selfcreate') {
19852:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
19853:             } else {  
19854:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
19855:             }
19856:         }
19857:     }
19858:     my @contexts = ('author','course');
19859:     my %context_title = (
19860:                            author => 'In author context',
19861:                            course => 'In course context',
19862:                         );
19863:     my @fields = ('lastname','firstname','middlename','generation',
19864:                   'permanentemail','id');
19865:     my %roles = (
19866:                   author => ['ca','aa'],
19867:                   course => ['st','ep','ta','in','cr'],
19868:                 );
19869:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19870:     foreach my $context (@contexts) {
19871:         foreach my $role (@{$roles{$context}}) {
19872:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
19873:             foreach my $item (@fields) {
19874:                 if (grep(/^\Q$item\E$/,@modifiable)) {
19875:                     $modifyhash{$context}{$role}{$item} = 1;
19876:                 } else {
19877:                     $modifyhash{$context}{$role}{$item} = 0;
19878:                 }
19879:             }
19880:         }
19881:         if (ref($curr_usermodification{$context}) eq 'HASH') {
19882:             foreach my $role (@{$roles{$context}}) {
19883:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
19884:                     foreach my $field (@fields) {
19885:                         if ($modifyhash{$context}{$role}{$field} ne 
19886:                                 $curr_usermodification{$context}{$role}{$field}) {
19887:                             push(@{$changes{$context}},$role);
19888:                             last;
19889:                         }
19890:                     }
19891:                 }
19892:             }
19893:         } else {
19894:             foreach my $context (@contexts) {
19895:                 foreach my $role (@{$roles{$context}}) {
19896:                     push(@{$changes{$context}},$role);
19897:                 }
19898:             }
19899:         }
19900:     }
19901:     my %usermodification_hash =  (
19902:                                    usermodification => \%modifyhash,
19903:                                  );
19904:     my $putresult = &Apache::lonnet::put_dom('configuration',
19905:                                              \%usermodification_hash,$dom);
19906:     if ($putresult eq 'ok') {
19907:         if (keys(%changes) > 0) {
19908:             $resulttext = &mt('Changes made: ').'<ul>';
19909:             foreach my $context (@contexts) {
19910:                 if (ref($changes{$context}) eq 'ARRAY') {
19911:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
19912:                     if (ref($changes{$context}) eq 'ARRAY') {
19913:                         foreach my $role (@{$changes{$context}}) {
19914:                             my $rolename;
19915:                             if ($role eq 'cr') {
19916:                                 $rolename = &mt('Custom');
19917:                             } else {
19918:                                 $rolename = &Apache::lonnet::plaintext($role);
19919:                             }
19920:                             my @modifiable;
19921:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
19922:                             foreach my $field (@fields) {
19923:                                 if ($modifyhash{$context}{$role}{$field}) {
19924:                                     push(@modifiable,$fieldtitles{$field});
19925:                                 }
19926:                             }
19927:                             if (@modifiable > 0) {
19928:                                 $resulttext .= join(', ',@modifiable);
19929:                             } else {
19930:                                 $resulttext .= &mt('none'); 
19931:                             }
19932:                             $resulttext .= '</li>';
19933:                         }
19934:                         $resulttext .= '</ul></li>';
19935:                     }
19936:                 }
19937:             }
19938:             $resulttext .= '</ul>';
19939:         } else {
19940:             $resulttext = &mt('No changes made to user modification settings');
19941:         }
19942:     } else {
19943:         $resulttext = '<span class="LC_error">'.
19944:             &mt('An error occurred: [_1]',$putresult).'</span>';
19945:     }
19946:     return $resulttext;
19947: }
19948: 
19949: sub modify_defaults {
19950:     my ($dom,$lastactref,%domconfig) = @_;
19951:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
19952:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
19953:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
19954:                  'portal_def');
19955:     my @authtypes = ('internal','krb4','krb5','localauth','lti');
19956:     foreach my $item (@items) {
19957:         $newvalues{$item} = $env{'form.'.$item};
19958:         if ($item eq 'auth_def') {
19959:             if ($newvalues{$item} ne '') {
19960:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
19961:                     push(@errors,$item);
19962:                 }
19963:             }
19964:         } elsif ($item eq 'lang_def') {
19965:             if ($newvalues{$item} ne '') {
19966:                 if ($newvalues{$item} =~ /^(\w+)/) {
19967:                     my $langcode = $1;
19968:                     if ($langcode ne 'x_chef') {
19969:                         if (code2language($langcode) eq '') {
19970:                             push(@errors,$item);
19971:                         }
19972:                     }
19973:                 } else {
19974:                     push(@errors,$item);
19975:                 }
19976:             }
19977:         } elsif ($item eq 'timezone_def') {
19978:             if ($newvalues{$item} ne '') {
19979:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
19980:                     push(@errors,$item);   
19981:                 }
19982:             }
19983:         } elsif ($item eq 'datelocale_def') {
19984:             if ($newvalues{$item} ne '') {
19985:                 my @datelocale_ids = DateTime::Locale->ids();
19986:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
19987:                     push(@errors,$item);
19988:                 }
19989:             }
19990:         } elsif ($item eq 'portal_def') {
19991:             if ($newvalues{$item} ne '') {
19992:                 unless ($newvalues{$item} =~ /^https?\:\/\/(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])\/?$/) {
19993:                     push(@errors,$item);
19994:                 }
19995:             }
19996:         }
19997:         if (grep(/^\Q$item\E$/,@errors)) {
19998:             $newvalues{$item} = $domdefaults{$item};
19999:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
20000:             $changes{$item} = 1;
20001:         }
20002:         $domdefaults{$item} = $newvalues{$item};
20003:     }
20004:     my %staticdefaults = (
20005:                            'intauth_cost'   => 10,
20006:                            'intauth_check'  => 0,
20007:                            'intauth_switch' => 0,
20008:                          );
20009:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
20010:         if (exists($domdefaults{$item})) {
20011:             $newvalues{$item} = $domdefaults{$item};
20012:         } else {
20013:             $newvalues{$item} = $staticdefaults{$item};
20014:         }
20015:     }
20016:     my ($unamemaprules,$ruleorder);
20017:     my @possunamemaprules = &Apache::loncommon::get_env_multiple('form.unamemap_rule');
20018:     if (@possunamemaprules) {
20019:         ($unamemaprules,$ruleorder) =
20020:             &Apache::lonnet::inst_userrules($dom,'unamemap');
20021:         if ((ref($unamemaprules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
20022:             if (@{$ruleorder} > 0) {
20023:                 my %possrules;
20024:                 map { $possrules{$_} = 1; } @possunamemaprules;
20025:                 foreach my $rule (@{$ruleorder}) {
20026:                     if ($possrules{$rule}) {
20027:                         push(@{$newvalues{'unamemap_rule'}},$rule);
20028:                     }
20029:                 }
20030:             }
20031:         }
20032:     }
20033:     if (ref($domdefaults{'unamemap_rule'}) eq 'ARRAY') {
20034:         if (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
20035:             my @rulediffs = &Apache::loncommon::compare_arrays($domdefaults{'unamemap_rule'},
20036:                                                                $newvalues{'unamemap_rule'});
20037:             if (@rulediffs) {
20038:                 $changes{'unamemap_rule'} = 1;
20039:                 $domdefaults{'unamemap_rule'} = $newvalues{'unamemap_rule'};
20040:             }
20041:         } elsif (@{$domdefaults{'unamemap_rule'}} > 0) {
20042:             $changes{'unamemap_rule'} = 1;
20043:             delete($domdefaults{'unamemap_rule'});
20044:         }
20045:     } elsif (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
20046:         if (@{$newvalues{'unamemap_rule'}} > 0) {
20047:             $changes{'unamemap_rule'} = 1;
20048:             $domdefaults{'unamemap_rule'} = $newvalues{'unamemap_rule'};
20049:         }
20050:     }
20051:     my %defaults_hash = (
20052:                          defaults => \%newvalues,
20053:                         );
20054:     my $title = &defaults_titles();
20055: 
20056:     my $currinststatus;
20057:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
20058:         $currinststatus = $domconfig{'inststatus'};
20059:     } else {
20060:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
20061:         $currinststatus = {
20062:                              inststatustypes => $usertypes,
20063:                              inststatusorder => $types,
20064:                              inststatusguest => [],
20065:                           };
20066:     }
20067:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
20068:     my @allpos;
20069:     my %alltypes;
20070:     my @inststatusguest;
20071:     if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
20072:         foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
20073:             unless (grep(/^\Q$type\E$/,@todelete)) {
20074:                 push(@inststatusguest,$type);
20075:             }
20076:         }
20077:     }
20078:     my ($currtitles,$currorder);
20079:     if (ref($currinststatus) eq 'HASH') {
20080:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
20081:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
20082:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
20083:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
20084:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
20085:                     }
20086:                 }
20087:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
20088:                     my $position = $env{'form.inststatus_pos_'.$type};
20089:                     $position =~ s/\D+//g;
20090:                     $allpos[$position] = $type;
20091:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
20092:                     $alltypes{$type} =~ s/`//g;
20093:                 }
20094:             }
20095:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
20096:             $currtitles =~ s/,$//;
20097:         }
20098:     }
20099:     if ($env{'form.addinststatus'}) {
20100:         my $newtype = $env{'form.addinststatus'};
20101:         $newtype =~ s/\W//g;
20102:         unless (exists($alltypes{$newtype})) {
20103:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
20104:             $alltypes{$newtype} =~ s/`//g; 
20105:             my $position = $env{'form.addinststatus_pos'};
20106:             $position =~ s/\D+//g;
20107:             if ($position ne '') {
20108:                 $allpos[$position] = $newtype;
20109:             }
20110:         }
20111:     }
20112:     my @orderedstatus;
20113:     foreach my $type (@allpos) {
20114:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
20115:             push(@orderedstatus,$type);
20116:         }
20117:     }
20118:     foreach my $type (keys(%alltypes)) {
20119:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
20120:             delete($alltypes{$type});
20121:         }
20122:     }
20123:     $defaults_hash{'inststatus'} = {
20124:                                      inststatustypes => \%alltypes,
20125:                                      inststatusorder => \@orderedstatus,
20126:                                      inststatusguest => \@inststatusguest,
20127:                                    };
20128:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
20129:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
20130:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
20131:         }
20132:     }
20133:     if ($currorder ne join(',',@orderedstatus)) {
20134:         $changes{'inststatus'}{'inststatusorder'} = 1;
20135:     }
20136:     my $newtitles;
20137:     foreach my $item (@orderedstatus) {
20138:         $newtitles .= $alltypes{$item}.',';
20139:     }
20140:     $newtitles =~ s/,$//;
20141:     if ($currtitles ne $newtitles) {
20142:         $changes{'inststatus'}{'inststatustypes'} = 1;
20143:     }
20144:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
20145:                                              $dom);
20146:     if ($putresult eq 'ok') {
20147:         if (keys(%changes) > 0) {
20148:             $resulttext = &mt('Changes made:').'<ul>';
20149:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
20150:             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";
20151:             foreach my $item (sort(keys(%changes))) {
20152:                 if ($item eq 'inststatus') {
20153:                     if (ref($changes{'inststatus'}) eq 'HASH') {
20154:                         if (@orderedstatus) {
20155:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
20156:                             foreach my $type (@orderedstatus) { 
20157:                                 $resulttext .= $alltypes{$type}.', ';
20158:                             }
20159:                             $resulttext =~ s/, $//;
20160:                             $resulttext .= '</li>';
20161:                         } else {
20162:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>'; 
20163:                         }
20164:                     }
20165:                 } elsif ($item eq 'unamemap_rule') {
20166:                     if (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
20167:                         my @rulenames;
20168:                         if (ref($unamemaprules) eq 'HASH') {
20169:                             foreach my $rule (@{$newvalues{'unamemap_rule'}}) {
20170:                                 if (ref($unamemaprules->{$rule}) eq 'HASH') {
20171:                                     push(@rulenames,$unamemaprules->{$rule}->{'name'});
20172:                                 }
20173:                             }
20174:                         }
20175:                         if (@rulenames) {
20176:                             $resulttext .= '<li>'.&mt('Mapping for missing usernames includes: [_1]',
20177:                                                      '<ul><li>'.join('</li><li>',@rulenames).'</li></ul>').
20178:                                            '</li>';
20179:                         } else {
20180:                             $resulttext .= '<li>'.&mt('No mapping for missing usernames via standard log-in').'</li>';
20181:                         }
20182:                     } else {
20183:                         $resulttext .= '<li>'.&mt('Mapping for missing usernames via standard log-in deleted').'</li>';
20184:                     }
20185:                 } else {
20186:                     my $value = $env{'form.'.$item};
20187:                     if ($value eq '') {
20188:                         $value = &mt('none');
20189:                     } elsif ($item eq 'auth_def') {
20190:                         my %authnames = &authtype_names();
20191:                         my %shortauth = (
20192:                                           internal   => 'int',
20193:                                           krb4       => 'krb4',
20194:                                           krb5       => 'krb5',
20195:                                           localauth  => 'loc',
20196:                                           lti        => 'lti',
20197:                         );
20198:                         $value = $authnames{$shortauth{$value}};
20199:                     }
20200:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
20201:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
20202:                 }
20203:             }
20204:             $resulttext .= '</ul>';
20205:             $mailmsgtext .= "\n";
20206:             my $cachetime = 24*60*60;
20207:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20208:             if (ref($lastactref) eq 'HASH') {
20209:                 $lastactref->{'domdefaults'} = 1;
20210:             }
20211:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
20212:                 my $notify = 1;
20213:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
20214:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
20215:                         $notify = 0;
20216:                     }
20217:                 }
20218:                 if ($notify) {
20219:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
20220:                                                "LON-CAPA Domain Settings Change - $dom",
20221:                                                $mailmsgtext);
20222:                 }
20223:             }
20224:         } else {
20225:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
20226:         }
20227:     } else {
20228:         $resulttext = '<span class="LC_error">'.
20229:             &mt('An error occurred: [_1]',$putresult).'</span>';
20230:     }
20231:     if (@errors > 0) {
20232:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
20233:         foreach my $item (@errors) {
20234:             $resulttext .= ' "'.$title->{$item}.'",';
20235:         }
20236:         $resulttext =~ s/,$//;
20237:     }
20238:     return $resulttext;
20239: }
20240: 
20241: sub modify_scantron {
20242:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
20243:     my ($resulttext,%confhash,%changes,$errors);
20244:     my $custom = 'custom.tab';
20245:     my $default = 'default.tab';
20246:     my $servadm = $r->dir_config('lonAdmEMail');
20247:     my ($configuserok,$author_ok,$switchserver) =
20248:         &config_check($dom,$confname,$servadm);
20249:     if ($env{'form.scantronformat.filename'} ne '') {
20250:         my $error;
20251:         if ($configuserok eq 'ok') {
20252:             if ($switchserver) {
20253:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
20254:             } else {
20255:                 if ($author_ok eq 'ok') {
20256:                     my ($result,$scantronurl) =
20257:                         &publishlogo($r,'upload','scantronformat',$dom,
20258:                                      $confname,'scantron','','',$custom);
20259:                     if ($result eq 'ok') {
20260:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
20261:                         $changes{'scantronformat'} = 1;
20262:                     } else {
20263:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
20264:                     }
20265:                 } else {
20266:                     $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);
20267:                 }
20268:             }
20269:         } else {
20270:             $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);
20271:         }
20272:         if ($error) {
20273:             &Apache::lonnet::logthis($error);
20274:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
20275:         }
20276:     }
20277:     if (ref($domconfig{'scantron'}) eq 'HASH') {
20278:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
20279:             if ($env{'form.scantronformat_del'}) {
20280:                 $confhash{'scantron'}{'scantronformat'} = '';
20281:                 $changes{'scantronformat'} = 1;
20282:             } else {
20283:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
20284:             }
20285:         }
20286:     }
20287:     my @options = ('hdr','pad','rem');
20288:     my @fields = &scantroncsv_fields();
20289:     my %titles = &scantronconfig_titles();
20290:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
20291:     my ($newdat,$currdat,%newcol,%currcol);
20292:     if (grep(/^dat$/,@formats)) {
20293:         $confhash{'scantron'}{config}{dat} = 1;
20294:         $newdat = 1;
20295:     } else {
20296:         $newdat = 0;
20297:     }
20298:     if (grep(/^csv$/,@formats)) {
20299:         my %bynum;
20300:         foreach my $field (@fields) {
20301:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
20302:                 my $posscol = $1;
20303:                 if (($posscol < 20) && (!$bynum{$posscol})) {
20304:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
20305:                     $bynum{$posscol} = $field;
20306:                     $newcol{$field} = $posscol;
20307:                 }
20308:             }
20309:         }
20310:         if (keys(%newcol)) {
20311:             foreach my $option (@options) {
20312:                 if ($env{'form.scantroncsv_'.$option}) {
20313:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
20314:                 }
20315:             }
20316:         }
20317:     }
20318:     $currdat = 1;
20319:     if (ref($domconfig{'scantron'}) eq 'HASH') {
20320:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
20321:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
20322:                 $currdat = 0;
20323:             }
20324:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
20325:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
20326:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
20327:                 }
20328:             }
20329:         }
20330:     }
20331:     if ($currdat != $newdat) {
20332:         $changes{'config'} = 1;
20333:     } else {
20334:         foreach my $field (@fields) {
20335:             if ($currcol{$field} ne '') {
20336:                 if ($currcol{$field} ne $newcol{$field}) {
20337:                     $changes{'config'} = 1;
20338:                     last;
20339:                 }
20340:             } elsif ($newcol{$field} ne '') {
20341:                 $changes{'config'} = 1;
20342:                 last;
20343:             }
20344:         }
20345:     }
20346:     if (keys(%confhash) > 0) {
20347:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
20348:                                                  $dom);
20349:         if ($putresult eq 'ok') {
20350:             if (keys(%changes) > 0) {
20351:                 if (ref($confhash{'scantron'}) eq 'HASH') {
20352:                     $resulttext = &mt('Changes made:').'<ul>';
20353:                     if ($changes{'scantronformat'}) {
20354:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
20355:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
20356:                         } else {
20357:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
20358:                         }
20359:                     }
20360:                     if ($changes{'config'}) {
20361:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
20362:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
20363:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
20364:                             }
20365:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
20366:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
20367:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
20368:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
20369:                                         foreach my $field (@fields) {
20370:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
20371:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
20372:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
20373:                                             }
20374:                                         }
20375:                                         $resulttext .= '</ul></li>';
20376:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
20377:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
20378:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
20379:                                                 foreach my $option (@options) {
20380:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
20381:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
20382:                                                     }
20383:                                                 }
20384:                                                 $resulttext .= '</ul></li>';
20385:                                             }
20386:                                         }
20387:                                     }
20388:                                 }
20389:                             }
20390:                         } else {
20391:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
20392:                         }
20393:                     }
20394:                     $resulttext .= '</ul>';
20395:                 } else {
20396:                     $resulttext = &mt('Changes made to bubblesheet format file.');
20397:                 }
20398:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
20399:                 if (ref($lastactref) eq 'HASH') {
20400:                     $lastactref->{'domainconfig'} = 1;
20401:                 }
20402:             } else {
20403:                 $resulttext = &mt('No changes made to bubblesheet format settings');
20404:             }
20405:         } else {
20406:             $resulttext = '<span class="LC_error">'.
20407:                 &mt('An error occurred: [_1]',$putresult).'</span>';
20408:         }
20409:     } else {
20410:         $resulttext = &mt('No changes made to bubblesheet format file'); 
20411:     }
20412:     if ($errors) {
20413:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
20414:                        $errors.'</ul></p>';
20415:     }
20416:     return $resulttext;
20417: }
20418: 
20419: sub modify_coursecategories {
20420:     my ($dom,$lastactref,%domconfig) = @_;
20421:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
20422:         $cathash);
20423:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
20424:     my @catitems = ('unauth','auth');
20425:     my @cattypes = ('std','domonly','codesrch','none');
20426:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
20427:         $cathash = $domconfig{'coursecategories'}{'cats'};
20428:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
20429:             $changes{'togglecats'} = 1;
20430:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
20431:         }
20432:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
20433:             $changes{'categorize'} = 1;
20434:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
20435:         }
20436:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
20437:             $changes{'togglecatscomm'} = 1;
20438:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
20439:         }
20440:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
20441:             $changes{'categorizecomm'} = 1;
20442:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
20443: 
20444:         }
20445:         if ($domconfig{'coursecategories'}{'togglecatsplace'} ne $env{'form.togglecatsplace'}) {
20446:             $changes{'togglecatsplace'} = 1;
20447:             $domconfig{'coursecategories'}{'togglecatsplace'} = $env{'form.togglecatsplace'};
20448:         }
20449:         if ($domconfig{'coursecategories'}{'categorizeplace'} ne $env{'form.categorizeplace'}) {
20450:             $changes{'categorizeplace'} = 1;
20451:             $domconfig{'coursecategories'}{'categorizeplace'} = $env{'form.categorizeplace'};
20452:         }
20453:         foreach my $item (@catitems) {
20454:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
20455:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
20456:                     $changes{$item} = 1;
20457:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
20458:                 }
20459:             }
20460:         }
20461:     } else {
20462:         $changes{'togglecats'} = 1;
20463:         $changes{'categorize'} = 1;
20464:         $changes{'togglecatscomm'} = 1;
20465:         $changes{'categorizecomm'} = 1;
20466:         $changes{'togglecatsplace'} = 1;
20467:         $changes{'categorizeplace'} = 1;
20468:         $domconfig{'coursecategories'} = {
20469:                                              togglecats => $env{'form.togglecats'},
20470:                                              categorize => $env{'form.categorize'},
20471:                                              togglecatscomm => $env{'form.togglecatscomm'},
20472:                                              categorizecomm => $env{'form.categorizecomm'},
20473:                                              togglecatsplace => $env{'form.togglecatsplace'},
20474:                                              categorizeplace => $env{'form.categorizeplace'},
20475:                                          };
20476:         foreach my $item (@catitems) {
20477:             if ($env{'form.coursecat_'.$item} ne 'std') {
20478:                 $changes{$item} = 1;
20479:             }
20480:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
20481:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
20482:             }
20483:         }
20484:     }
20485:     if (ref($cathash) eq 'HASH') {
20486:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
20487:             push (@deletecategory,'instcode::0');
20488:         }
20489:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
20490:             push(@deletecategory,'communities::0');
20491:         }
20492:         if (($domconfig{'coursecategories'}{'cats'}{'placement::0'} ne '')  && ($env{'form.placement'} == 0)) {
20493:             push(@deletecategory,'placement::0');
20494:         }
20495:     }
20496:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
20497:     if (ref($cathash) eq 'HASH') {
20498:         if (@deletecategory > 0) {
20499:             #FIXME Need to remove category from all courses using a deleted category 
20500:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
20501:             foreach my $item (@deletecategory) {
20502:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
20503:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
20504:                     $deletions{$item} = 1;
20505:                     &recurse_cat_deletes($item,$cathash,\%deletions);
20506:                 }
20507:             }
20508:         }
20509:         foreach my $item (keys(%{$cathash})) {
20510:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
20511:             if ($cathash->{$item} ne $env{'form.'.$item}) {
20512:                 $reorderings{$item} = 1;
20513:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
20514:             }
20515:             if ($env{'form.addcategory_name_'.$item} ne '') {
20516:                 my $newcat = $env{'form.addcategory_name_'.$item};
20517:                 my $newdepth = $depth+1;
20518:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
20519:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
20520:                 $adds{$newitem} = 1; 
20521:             }
20522:             if ($env{'form.subcat_'.$item} ne '') {
20523:                 my $newcat = $env{'form.subcat_'.$item};
20524:                 my $newdepth = $depth+1;
20525:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
20526:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
20527:                 $adds{$newitem} = 1;
20528:             }
20529:         }
20530:     }
20531:     if ($env{'form.instcode'} eq '1') {
20532:         if (ref($cathash) eq 'HASH') {
20533:             my $newitem = 'instcode::0';
20534:             if ($cathash->{$newitem} eq '') {  
20535:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
20536:                 $adds{$newitem} = 1;
20537:             }
20538:         } else {
20539:             my $newitem = 'instcode::0';
20540:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
20541:             $adds{$newitem} = 1;
20542:         }
20543:     }
20544:     if ($env{'form.communities'} eq '1') {
20545:         if (ref($cathash) eq 'HASH') {
20546:             my $newitem = 'communities::0';
20547:             if ($cathash->{$newitem} eq '') {
20548:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
20549:                 $adds{$newitem} = 1;
20550:             }
20551:         } else {
20552:             my $newitem = 'communities::0';
20553:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
20554:             $adds{$newitem} = 1;
20555:         }
20556:     }
20557:     if ($env{'form.placement'} eq '1') {
20558:         if (ref($cathash) eq 'HASH') {
20559:             my $newitem = 'placement::0';
20560:             if ($cathash->{$newitem} eq '') {
20561:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
20562:                 $adds{$newitem} = 1;
20563:             }
20564:         } else {
20565:             my $newitem = 'placement::0';
20566:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
20567:             $adds{$newitem} = 1;
20568:         }
20569:     }
20570:     if ($env{'form.addcategory_name'} ne '') {
20571:         if (($env{'form.addcategory_name'} ne 'instcode') &&
20572:             ($env{'form.addcategory_name'} ne 'communities') &&
20573:             ($env{'form.addcategory_name'} ne 'placement')) {
20574:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
20575:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
20576:             $adds{$newitem} = 1;
20577:         }
20578:     }
20579:     my $putresult;
20580:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
20581:         if (keys(%deletions) > 0) {
20582:             foreach my $key (keys(%deletions)) {
20583:                 if ($predelallitems{$key} ne '') {
20584:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
20585:                 }
20586:             }
20587:         }
20588:         my (@chkcats,@chktrails,%chkallitems);
20589:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
20590:         if (ref($chkcats[0]) eq 'ARRAY') {
20591:             my $depth = 0;
20592:             my $chg = 0;
20593:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
20594:                 my $name = $chkcats[0][$i];
20595:                 my $item;
20596:                 if ($name eq '') {
20597:                     $chg ++;
20598:                 } else {
20599:                     $item = &escape($name).'::0';
20600:                     if ($chg) {
20601:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
20602:                     }
20603:                     $depth ++; 
20604:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
20605:                     $depth --;
20606:                 }
20607:             }
20608:         }
20609:     }
20610:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
20611:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
20612:         if ($putresult eq 'ok') {
20613:             my %title = (
20614:                          togglecats     => 'Show/Hide a course in catalog',
20615:                          categorize     => 'Assign a category to a course',
20616:                          togglecatscomm => 'Show/Hide a community in catalog',
20617:                          categorizecomm => 'Assign a category to a community',
20618:                         );
20619:             my %level = (
20620:                          dom  => 'set in Domain ("Modify Course/Community")',
20621:                          crs  => 'set in Course ("Course Configuration")',
20622:                          comm => 'set in Community ("Community Configuration")',
20623:                          none     => 'No catalog',
20624:                          std      => 'Standard catalog',
20625:                          domonly  => 'Domain-only catalog',
20626:                          codesrch => 'Code search form',
20627:                         );
20628:             $resulttext = &mt('Changes made:').'<ul>';
20629:             if ($changes{'togglecats'}) {
20630:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
20631:             }
20632:             if ($changes{'categorize'}) {
20633:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
20634:             }
20635:             if ($changes{'togglecatscomm'}) {
20636:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
20637:             }
20638:             if ($changes{'categorizecomm'}) {
20639:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
20640:             }
20641:             if ($changes{'unauth'}) {
20642:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
20643:             }
20644:             if ($changes{'auth'}) {
20645:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
20646:             }
20647:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
20648:                 my $cathash;
20649:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
20650:                     $cathash = $domconfig{'coursecategories'}{'cats'};
20651:                 } else {
20652:                     $cathash = {};
20653:                 } 
20654:                 my (@cats,@trails,%allitems);
20655:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
20656:                 if (keys(%deletions) > 0) {
20657:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
20658:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
20659:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
20660:                     }
20661:                     $resulttext .= '</ul></li>';
20662:                 }
20663:                 if (keys(%reorderings) > 0) {
20664:                     my %sort_by_trail;
20665:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
20666:                     foreach my $key (keys(%reorderings)) {
20667:                         if ($allitems{$key} ne '') {
20668:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
20669:                         }
20670:                     }
20671:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
20672:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
20673:                     }
20674:                     $resulttext .= '</ul></li>';
20675:                 }
20676:                 if (keys(%adds) > 0) {
20677:                     my %sort_by_trail;
20678:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
20679:                     foreach my $key (keys(%adds)) {
20680:                         if ($allitems{$key} ne '') {
20681:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
20682:                         }
20683:                     }
20684:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
20685:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
20686:                     }
20687:                     $resulttext .= '</ul></li>';
20688:                 }
20689:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
20690:                 if (ref($lastactref) eq 'HASH') {
20691:                     $lastactref->{'cats'} = 1;
20692:                 }
20693:             }
20694:             $resulttext .= '</ul>';
20695:             if ($changes{'unauth'} || $changes{'auth'}) {
20696:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
20697:                 if ($changes{'auth'}) {
20698:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
20699:                 }
20700:                 if ($changes{'unauth'}) {
20701:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
20702:                 }
20703:                 my $cachetime = 24*60*60;
20704:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20705:                 if (ref($lastactref) eq 'HASH') {
20706:                     $lastactref->{'domdefaults'} = 1;
20707:                 }
20708:             }
20709:         } else {
20710:             $resulttext = '<span class="LC_error">'.
20711:                           &mt('An error occurred: [_1]',$putresult).'</span>';
20712:         }
20713:     } else {
20714:         $resulttext = &mt('No changes made to course and community categories');
20715:     }
20716:     return $resulttext;
20717: }
20718: 
20719: sub modify_serverstatuses {
20720:     my ($dom,%domconfig) = @_;
20721:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
20722:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
20723:         %currserverstatus = %{$domconfig{'serverstatuses'}};
20724:     }
20725:     my @pages = &serverstatus_pages();
20726:     foreach my $type (@pages) {
20727:         $newserverstatus{$type}{'namedusers'} = '';
20728:         $newserverstatus{$type}{'machines'} = '';
20729:         if (defined($env{'form.'.$type.'_namedusers'})) {
20730:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
20731:             my @okusers;
20732:             foreach my $user (@users) {
20733:                 my ($uname,$udom) = split(/:/,$user);
20734:                 if (($udom =~ /^$match_domain$/) &&   
20735:                     (&Apache::lonnet::domain($udom)) &&
20736:                     ($uname =~ /^$match_username$/)) {
20737:                     if (!grep(/^\Q$user\E/,@okusers)) {
20738:                         push(@okusers,$user);
20739:                     }
20740:                 }
20741:             }
20742:             if (@okusers > 0) {
20743:                  @okusers = sort(@okusers);
20744:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
20745:             }
20746:         }
20747:         if (defined($env{'form.'.$type.'_machines'})) {
20748:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
20749:             my @okmachines;
20750:             foreach my $ip (@machines) {
20751:                 my @parts = split(/\./,$ip);
20752:                 next if (@parts < 4);
20753:                 my $badip = 0;
20754:                 for (my $i=0; $i<4; $i++) {
20755:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
20756:                         $badip = 1;
20757:                         last;
20758:                     }
20759:                 }
20760:                 if (!$badip) {
20761:                     push(@okmachines,$ip);     
20762:                 }
20763:             }
20764:             @okmachines = sort(@okmachines);
20765:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
20766:         }
20767:     }
20768:     my %serverstatushash =  (
20769:                                 serverstatuses => \%newserverstatus,
20770:                             );
20771:     foreach my $type (@pages) {
20772:         foreach my $setting ('namedusers','machines') {
20773:             my (@current,@new);
20774:             if (ref($currserverstatus{$type}) eq 'HASH') {
20775:                 if ($currserverstatus{$type}{$setting} ne '') { 
20776:                     @current = split(/,/,$currserverstatus{$type}{$setting});
20777:                 }
20778:             }
20779:             if ($newserverstatus{$type}{$setting} ne '') {
20780:                 @new = split(/,/,$newserverstatus{$type}{$setting});
20781:             }
20782:             if (@current > 0) {
20783:                 if (@new > 0) {
20784:                     foreach my $item (@current) {
20785:                         if (!grep(/^\Q$item\E$/,@new)) {
20786:                             $changes{$type}{$setting} = 1;
20787:                             last;
20788:                         }
20789:                     }
20790:                     foreach my $item (@new) {
20791:                         if (!grep(/^\Q$item\E$/,@current)) {
20792:                             $changes{$type}{$setting} = 1;
20793:                             last;
20794:                         }
20795:                     }
20796:                 } else {
20797:                     $changes{$type}{$setting} = 1;
20798:                 }
20799:             } elsif (@new > 0) {
20800:                 $changes{$type}{$setting} = 1;
20801:             }
20802:         }
20803:     }
20804:     if (keys(%changes) > 0) {
20805:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
20806:         my $putresult = &Apache::lonnet::put_dom('configuration',
20807:                                                  \%serverstatushash,$dom);
20808:         if ($putresult eq 'ok') {
20809:             $resulttext .= &mt('Changes made:').'<ul>';
20810:             foreach my $type (@pages) {
20811:                 if (ref($changes{$type}) eq 'HASH') {
20812:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
20813:                     if ($changes{$type}{'namedusers'}) {
20814:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
20815:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
20816:                         } else {
20817:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
20818:                         }
20819:                     }
20820:                     if ($changes{$type}{'machines'}) {
20821:                         if ($newserverstatus{$type}{'machines'} eq '') {
20822:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
20823:                         } else {
20824:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
20825:                         }
20826: 
20827:                     }
20828:                     $resulttext .= '</ul></li>';
20829:                 }
20830:             }
20831:             $resulttext .= '</ul>';
20832:         } else {
20833:             $resulttext = '<span class="LC_error">'.
20834:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
20835: 
20836:         }
20837:     } else {
20838:         $resulttext = &mt('No changes made to access to server status pages');
20839:     }
20840:     return $resulttext;
20841: }
20842: 
20843: sub modify_helpsettings {
20844:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
20845:     my ($resulttext,$errors,%changes,%helphash);
20846:     my %defaultchecked = ('submitbugs' => 'on');
20847:     my @offon = ('off','on');
20848:     my @toggles = ('submitbugs');
20849:     my %current = ('submitbugs' => '',
20850:                    'adhoc'      => {},
20851:                   );
20852:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
20853:         %current = %{$domconfig{'helpsettings'}};
20854:     }
20855:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20856:     foreach my $item (@toggles) {
20857:         if ($defaultchecked{$item} eq 'on') { 
20858:             if ($current{$item} eq '') {
20859:                 if ($env{'form.'.$item} eq '0') {
20860:                     $changes{$item} = 1;
20861:                 }
20862:             } elsif ($current{$item} ne $env{'form.'.$item}) {
20863:                 $changes{$item} = 1;
20864:             }
20865:         } elsif ($defaultchecked{$item} eq 'off') {
20866:             if ($current{$item} eq '') {
20867:                 if ($env{'form.'.$item} eq '1') {
20868:                     $changes{$item} = 1;
20869:                 }
20870:             } elsif ($current{$item} ne $env{'form.'.$item}) {
20871:                 $changes{$item} = 1;
20872:             }
20873:         }
20874:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
20875:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
20876:         }
20877:     }
20878:     my $maxnum = $env{'form.helproles_maxnum'};
20879:     my $confname = $dom.'-domainconfig';
20880:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
20881:     my (@allpos,%newsettings,%changedprivs,$newrole);
20882:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
20883:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
20884:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
20885:     my %lt = &Apache::lonlocal::texthash(
20886:                     s      => 'system',
20887:                     d      => 'domain',
20888:                     order  => 'Display order',
20889:                     access => 'Role usage',
20890:                     all    => 'All with domain helpdesk or helpdesk assistant role',
20891:                     dh     => 'All with domain helpdesk role',
20892:                     da     => 'All with domain helpdesk assistant role',
20893:                     none   => 'None',
20894:                     status => 'Determined based on institutional status',
20895:                     inc    => 'Include all, but exclude specific personnel',
20896:                     exc    => 'Exclude all, but include specific personnel',
20897:     );
20898:     for (my $num=0; $num<=$maxnum; $num++) {
20899:         my ($prefix,$identifier,$rolename,%curr);
20900:         if ($num == $maxnum) {
20901:             next unless ($env{'form.newcusthelp'} == $maxnum);
20902:             $identifier = 'custhelp'.$num;
20903:             $prefix = 'helproles_'.$num;
20904:             $rolename = $env{'form.custhelpname'.$num};
20905:             $rolename=~s/[^A-Za-z0-9]//gs;
20906:             next if ($rolename eq '');
20907:             next if (exists($existing{'rolesdef_'.$rolename}));
20908:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
20909:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
20910:                                                      $newprivs{'c'},$confname,$dom);
20911:             if ($result ne 'ok') {
20912:                 $errors .= '<li><span class="LC_error">'.
20913:                            &mt('An error occurred storing the new custom role: [_1]',
20914:                            $result).'</span></li>';
20915:                 next;
20916:             } else {
20917:                 $changedprivs{$rolename} = \%newprivs;
20918:                 $newrole = $rolename;
20919:             }
20920:         } else {
20921:             $prefix = 'helproles_'.$num;
20922:             $rolename = $env{'form.'.$prefix};
20923:             next if ($rolename eq '');
20924:             next unless (exists($existing{'rolesdef_'.$rolename}));
20925:             $identifier = 'custhelp'.$num;
20926:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
20927:             my %currprivs;
20928:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
20929:                 split(/\_/,$existing{'rolesdef_'.$rolename});
20930:             foreach my $level ('c','d','s') {
20931:                 if ($newprivs{$level} ne $currprivs{$level}) {
20932:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
20933:                                                              $newprivs{'c'},$confname,$dom);
20934:                     if ($result ne 'ok') {
20935:                         $errors .= '<li><span class="LC_error">'.
20936:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
20937:                                        $rolename,$result).'</span></li>';
20938:                     } else {
20939:                         $changedprivs{$rolename} = \%newprivs;
20940:                     }
20941:                     last;
20942:                 }
20943:             }
20944:             if (ref($current{'adhoc'}) eq 'HASH') {
20945:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
20946:                     %curr = %{$current{'adhoc'}{$rolename}};
20947:                 }
20948:             }
20949:         }
20950:         my $newpos = $env{'form.'.$prefix.'_pos'};
20951:         $newpos =~ s/\D+//g;
20952:         $allpos[$newpos] = $rolename;
20953:         my $newdesc = $env{'form.'.$prefix.'_desc'};
20954:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
20955:         if ($curr{'desc'}) {
20956:             if ($curr{'desc'} ne $newdesc) {
20957:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
20958:                 $newsettings{$rolename}{'desc'} = $newdesc;
20959:             }
20960:         } elsif ($newdesc ne '') {
20961:             $changes{'customrole'}{$rolename}{'desc'} = 1;
20962:             $newsettings{$rolename}{'desc'} = $newdesc;
20963:         }
20964:         my $access = $env{'form.'.$prefix.'_access'};
20965:         if (grep(/^\Q$access\E$/,@accesstypes)) {
20966:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
20967:             if ($access eq 'status') {
20968:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
20969:                 if (scalar(@statuses) == 0) {
20970:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
20971:                 } else {
20972:                     my (@shownstatus,$numtypes);
20973:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
20974:                     if (ref($types) eq 'ARRAY') {
20975:                         $numtypes = scalar(@{$types});
20976:                         foreach my $type (sort(@statuses)) {
20977:                             if ($type eq 'default') {
20978:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
20979:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
20980:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
20981:                                 push(@shownstatus,$usertypes->{$type});
20982:                             }
20983:                         }
20984:                     }
20985:                     if (grep(/^default$/,@statuses)) {
20986:                         push(@shownstatus,$othertitle);
20987:                     }
20988:                     if (scalar(@shownstatus) == 1+$numtypes) {
20989:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
20990:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
20991:                     } else {
20992:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
20993:                         if (ref($curr{'status'}) eq 'ARRAY') {
20994:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
20995:                             if (@diffs) {
20996:                                 $changes{'customrole'}{$rolename}{$access} = 1;
20997:                             }
20998:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
20999:                             $changes{'customrole'}{$rolename}{$access} = 1;
21000:                         }
21001:                     }
21002:                 }
21003:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
21004:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
21005:                 my @newspecstaff;
21006:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
21007:                 foreach my $person (sort(@personnel)) {
21008:                     if ($domhelpdesk{$person}) {
21009:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
21010:                     }
21011:                 }
21012:                 if (ref($curr{$access}) eq 'ARRAY') {
21013:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
21014:                     if (@diffs) {
21015:                         $changes{'customrole'}{$rolename}{$access} = 1;
21016:                     }
21017:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
21018:                     $changes{'customrole'}{$rolename}{$access} = 1;
21019:                 }
21020:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
21021:                     my ($uname,$udom) = split(/:/,$person);
21022:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
21023:                 }
21024:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
21025:             }
21026:         } else {
21027:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
21028:         }
21029:         unless ($curr{'access'} eq $access) {
21030:             $changes{'customrole'}{$rolename}{'access'} = 1;
21031:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
21032:         }
21033:     }
21034:     if (@allpos > 0) {
21035:         my $idx = 0;
21036:         foreach my $rolename (@allpos) {
21037:             if ($rolename ne '') {
21038:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
21039:                 if (ref($current{'adhoc'}) eq 'HASH') {
21040:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
21041:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
21042:                             $changes{'customrole'}{$rolename}{'order'} = 1;
21043:                             $newsettings{$rolename}{'order'} = $idx+1;
21044:                         }
21045:                     }
21046:                 }
21047:                 $idx ++;
21048:             }
21049:         }
21050:     }
21051:     my $putresult;
21052:     if (keys(%changes) > 0) {
21053:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
21054:         if ($putresult eq 'ok') {
21055:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
21056:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
21057:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
21058:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
21059:                 }
21060:             }
21061:             my $cachetime = 24*60*60;
21062:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21063:             if (ref($lastactref) eq 'HASH') {
21064:                 $lastactref->{'domdefaults'} = 1;
21065:             }
21066:         } else {
21067:             $errors .= '<li><span class="LC_error">'.
21068:                        &mt('An error occurred storing the settings: [_1]',
21069:                            $putresult).'</span></li>';
21070:         }
21071:     }
21072:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
21073:         $resulttext = &mt('Changes made:').'<ul>';
21074:         my (%shownprivs,@levelorder);
21075:         @levelorder = ('c','d','s');
21076:         if ((keys(%changes)) && ($putresult eq 'ok')) {
21077:             foreach my $item (sort(keys(%changes))) {
21078:                 if ($item eq 'submitbugs') {
21079:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
21080:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
21081:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
21082:                 } elsif ($item eq 'customrole') {
21083:                     if (ref($changes{'customrole'}) eq 'HASH') {
21084:                         my @keyorder = ('order','desc','access','status','exc','inc');
21085:                         my %keytext = &Apache::lonlocal::texthash(
21086:                                                                    order  => 'Order',
21087:                                                                    desc   => 'Role description',
21088:                                                                    access => 'Role usage',
21089:                                                                    status => 'Allowed institutional types',
21090:                                                                    exc    => 'Allowed personnel',
21091:                                                                    inc    => 'Disallowed personnel',
21092:                         );
21093:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
21094:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
21095:                                 if ($role eq $newrole) {
21096:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
21097:                                                               $role).'<ul>';
21098:                                 } else {
21099:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
21100:                                                               $role).'<ul>';
21101:                                 }
21102:                                 foreach my $key (@keyorder) {
21103:                                     if ($changes{'customrole'}{$role}{$key}) {
21104:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
21105:                                                                   $keytext{$key},$newsettings{$role}{$key}).
21106:                                                        '</li>';
21107:                                     }
21108:                                 }
21109:                                 if (ref($changedprivs{$role}) eq 'HASH') {
21110:                                     $shownprivs{$role} = 1;
21111:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
21112:                                     foreach my $level (@levelorder) {
21113:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
21114:                                             next if ($item eq '');
21115:                                             my ($priv) = split(/\&/,$item,2);
21116:                                             if (&Apache::lonnet::plaintext($priv)) {
21117:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
21118:                                                 unless ($level eq 'c') {
21119:                                                     $resulttext .= ' ('.$lt{$level}.')';
21120:                                                 }
21121:                                                 $resulttext .= '</li>';
21122:                                             }
21123:                                         }
21124:                                     }
21125:                                     $resulttext .= '</ul>';
21126:                                 }
21127:                                 $resulttext .= '</ul></li>';
21128:                             }
21129:                         }
21130:                     }
21131:                 }
21132:             }
21133:         }
21134:         if (keys(%changedprivs)) {
21135:             foreach my $role (sort(keys(%changedprivs))) {
21136:                 unless ($shownprivs{$role}) {
21137:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
21138:                                               $role).'<ul>'.
21139:                                    '<li>'.&mt('Privileges set to :').'<ul>';
21140:                     foreach my $level (@levelorder) {
21141:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
21142:                             next if ($item eq '');
21143:                             my ($priv) = split(/\&/,$item,2);
21144:                             if (&Apache::lonnet::plaintext($priv)) {
21145:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
21146:                                 unless ($level eq 'c') {
21147:                                     $resulttext .= ' ('.$lt{$level}.')';
21148:                                 }
21149:                                 $resulttext .= '</li>';
21150:                             }
21151:                         }
21152:                     }
21153:                     $resulttext .= '</ul></li></ul></li>';
21154:                 }
21155:             }
21156:         }
21157:         $resulttext .= '</ul>';
21158:     } else {
21159:         $resulttext = &mt('No changes made to help settings');
21160:     }
21161:     if ($errors) {
21162:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
21163:                                     $errors.'</ul>';
21164:     }
21165:     return $resulttext;
21166: }
21167: 
21168: sub modify_coursedefaults {
21169:     my ($dom,$lastactref,%domconfig) = @_;
21170:     my ($resulttext,$errors,%changes,%defaultshash);
21171:     my %defaultchecked = (
21172:                            'canuse_pdfforms' => 'off',
21173:                            'uselcmath'       => 'on',
21174:                            'usejsme'         => 'on',
21175:                            'inline_chem'     => 'on',
21176:                            'ltiauth'         => 'off',
21177:                          );
21178:     my @toggles = ('canuse_pdfforms','uselcmath','usejsme','inline_chem','ltiauth');
21179:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
21180:                    'uploadquota_community','uploadquota_textbook','uploadquota_placement',
21181:                    'mysqltables_official','mysqltables_unofficial','mysqltables_community',
21182:                    'mysqltables_textbook','mysqltables_placement');
21183:     my @types = ('official','unofficial','community','textbook','placement');
21184:     my %staticdefaults = (
21185:                            anonsurvey_threshold => 10,
21186:                            uploadquota          => 500,
21187:                            postsubmit           => 60,
21188:                            mysqltables          => 172800,
21189:                          );
21190:     my %texoptions = (
21191:                         MathJax  => 'MathJax',
21192:                         mimetex  => &mt('Convert to Images'),
21193:                         tth      => &mt('TeX to HTML'),
21194:                      );
21195:     $defaultshash{'coursedefaults'} = {};
21196: 
21197:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
21198:         if ($domconfig{'coursedefaults'} eq '') {
21199:             $domconfig{'coursedefaults'} = {};
21200:         }
21201:     }
21202: 
21203:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
21204:         foreach my $item (@toggles) {
21205:             if ($defaultchecked{$item} eq 'on') {
21206:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
21207:                     ($env{'form.'.$item} eq '0')) {
21208:                     $changes{$item} = 1;
21209:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
21210:                     $changes{$item} = 1;
21211:                 }
21212:             } elsif ($defaultchecked{$item} eq 'off') {
21213:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
21214:                     ($env{'form.'.$item} eq '1')) {
21215:                     $changes{$item} = 1;
21216:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
21217:                     $changes{$item} = 1;
21218:                 }
21219:             }
21220:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
21221:         }
21222:         foreach my $item (@numbers) {
21223:             my ($currdef,$newdef);
21224:             $newdef = $env{'form.'.$item};
21225:             if ($item eq 'anonsurvey_threshold') {
21226:                 $currdef = $domconfig{'coursedefaults'}{$item};
21227:                 $newdef =~ s/\D//g;
21228:                 if ($newdef eq '' || $newdef < 1) {
21229:                     $newdef = 1;
21230:                 }
21231:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
21232:             } else {
21233:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
21234:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
21235:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
21236:                 }
21237:                 $newdef =~ s/[^\w.\-]//g;
21238:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
21239:             }
21240:             if ($currdef ne $newdef) {
21241:                 if ($item eq 'anonsurvey_threshold') {
21242:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
21243:                         $changes{$item} = 1;
21244:                     }
21245:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
21246:                     my $setting = $1;
21247:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
21248:                         $changes{$setting} = 1;
21249:                     }
21250:                 }
21251:             }
21252:         }
21253:         my $texengine;
21254:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
21255:             $texengine = $env{'form.texengine'};
21256:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
21257:             if ($currdef eq '') {
21258:                 unless ($texengine eq $Apache::lonnet::deftex) {
21259:                     $changes{'texengine'} = 1;
21260:                 }
21261:             } elsif ($currdef ne $texengine) {
21262:                 $changes{'texengine'} = 1;
21263:             }
21264:         }
21265:         if ($texengine ne '') {
21266:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
21267:         }
21268:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
21269:         my @currclonecode;
21270:         if (ref($currclone) eq 'HASH') {
21271:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
21272:                 @currclonecode = @{$currclone->{'instcode'}};
21273:             }
21274:         }
21275:         my $newclone;
21276:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
21277:             $newclone = $env{'form.canclone'};
21278:         }
21279:         if ($newclone eq 'instcode') {
21280:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
21281:             my (%codedefaults,@code_order,@clonecode);
21282:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
21283:                                                     \@code_order);
21284:             foreach my $item (@code_order) {
21285:                 if (grep(/^\Q$item\E$/,@newcodes)) {
21286:                     push(@clonecode,$item);
21287:                 }
21288:             }
21289:             if (@clonecode) {
21290:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
21291:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
21292:                 if (@diffs) {
21293:                     $changes{'canclone'} = 1;
21294:                 }
21295:             } else {
21296:                 $newclone eq '';
21297:             }
21298:         } elsif ($newclone ne '') {
21299:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
21300:         }
21301:         if ($newclone ne $currclone) {
21302:             $changes{'canclone'} = 1;
21303:         }
21304:         my %credits;
21305:         foreach my $type (@types) {
21306:             unless ($type eq 'community') {
21307:                 $credits{$type} = $env{'form.'.$type.'_credits'};
21308:                 $credits{$type} =~ s/[^\d.]+//g;
21309:             }
21310:         }
21311:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
21312:             ($env{'form.coursecredits'} eq '1')) {
21313:             $changes{'coursecredits'} = 1;
21314:             foreach my $type (keys(%credits)) {
21315:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
21316:             }
21317:         } else {
21318:             if ($env{'form.coursecredits'} eq '1') {
21319:                 foreach my $type (@types) {
21320:                     unless ($type eq 'community') {
21321:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
21322:                             $changes{'coursecredits'} = 1;
21323:                         }
21324:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
21325:                     }
21326:                 }
21327:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
21328:                 foreach my $type (@types) {
21329:                     unless ($type eq 'community') {
21330:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
21331:                             $changes{'coursecredits'} = 1;
21332:                             last;
21333:                         }
21334:                     }
21335:                 }
21336:             }
21337:         }
21338:         if ($env{'form.postsubmit'} eq '1') {
21339:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
21340:             my %currtimeout;
21341:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21342:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
21343:                     $changes{'postsubmit'} = 1;
21344:                 }
21345:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
21346:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
21347:                 }
21348:             } else {
21349:                 $changes{'postsubmit'} = 1;
21350:             }
21351:             foreach my $type (@types) {
21352:                 my $timeout = $env{'form.'.$type.'_timeout'};
21353:                 $timeout =~ s/\D//g;
21354:                 if ($timeout == $staticdefaults{'postsubmit'}) {
21355:                     $timeout = '';
21356:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
21357:                     $timeout = '0';
21358:                 }
21359:                 unless ($timeout eq '') {
21360:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
21361:                 }
21362:                 if (exists($currtimeout{$type})) {
21363:                     if ($timeout ne $currtimeout{$type}) {
21364:                         $changes{'postsubmit'} = 1;
21365:                     }
21366:                 } elsif ($timeout ne '') {
21367:                     $changes{'postsubmit'} = 1;
21368:                 }
21369:             }
21370:         } else {
21371:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
21372:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21373:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
21374:                     $changes{'postsubmit'} = 1;
21375:                 }
21376:             } else {
21377:                 $changes{'postsubmit'} = 1;
21378:             }
21379:         }
21380:     }
21381:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
21382:                                              $dom);
21383:     if ($putresult eq 'ok') {
21384:         if (keys(%changes) > 0) {
21385:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21386:             if (($changes{'canuse_pdfforms'}) || ($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
21387:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
21388:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'}) ||
21389:                 ($changes{'inline_chem'}) || ($changes{'ltiauth'})) {
21390:                 foreach my $item ('canuse_pdfforms','uselcmath','usejsme','inline_chem','texengine','ltiauth') {
21391:                     if ($changes{$item}) {
21392:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
21393:                     }
21394:                 }
21395:                 if ($changes{'coursecredits'}) {
21396:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
21397:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
21398:                             $domdefaults{$type.'credits'} =
21399:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
21400:                         }
21401:                     }
21402:                 }
21403:                 if ($changes{'postsubmit'}) {
21404:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21405:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
21406:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
21407:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
21408:                                 $domdefaults{$type.'postsubtimeout'} =
21409:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
21410:                             }
21411:                         }
21412:                     }
21413:                 }
21414:                 if ($changes{'uploadquota'}) {
21415:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
21416:                         foreach my $type (@types) {
21417:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
21418:                         }
21419:                     }
21420:                 }
21421:                 if ($changes{'canclone'}) {
21422:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
21423:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
21424:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
21425:                             if (@clonecodes) {
21426:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
21427:                             }
21428:                         }
21429:                     } else {
21430:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
21431:                     }
21432:                 }
21433:                 my $cachetime = 24*60*60;
21434:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21435:                 if (ref($lastactref) eq 'HASH') {
21436:                     $lastactref->{'domdefaults'} = 1;
21437:                 }
21438:             }
21439:             $resulttext = &mt('Changes made:').'<ul>';
21440:             foreach my $item (sort(keys(%changes))) {
21441:                 if ($item eq 'canuse_pdfforms') {
21442:                     if ($env{'form.'.$item} eq '1') {
21443:                         $resulttext .= '<li>'.&mt("Course/Community users can create/upload PDF forms set to 'on'").'</li>';
21444:                     } else {
21445:                         $resulttext .= '<li>'.&mt('Course/Community users can create/upload PDF forms set to "off"').'</li>';
21446:                     }
21447:                 } elsif ($item eq 'uselcmath') {
21448:                     if ($env{'form.'.$item} eq '1') {
21449:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
21450:                     } else {
21451:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
21452:                     }
21453:                 } elsif ($item eq 'usejsme') {
21454:                     if ($env{'form.'.$item} eq '1') {
21455:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
21456:                     } else {
21457:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
21458:                     }
21459:                 } elsif ($item eq 'inline_chem') {
21460:                     if ($env{'form.'.$item} eq '1') {
21461:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses inline previewer').'</li>';
21462:                     } else {
21463:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses pop-up previewer').'</li>';
21464:                     }
21465:                 } elsif ($item eq 'texengine') {
21466:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
21467:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
21468:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
21469:                     }
21470:                 } elsif ($item eq 'anonsurvey_threshold') {
21471:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
21472:                 } elsif ($item eq 'uploadquota') {
21473:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
21474:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
21475:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
21476:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
21477:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
21478:                                        '<li>'.&mt('Placement tests: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'placement'}.'</b>').'</li>'. 
21479:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
21480:                                        '</ul>'.
21481:                                        '</li>';
21482:                     } else {
21483:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
21484:                     }
21485:                 } elsif ($item eq 'mysqltables') {
21486:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
21487:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
21488:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
21489:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
21490:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
21491:                                        '<li>'.&mt('Placement tests: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'placement'}.'</b>').'</li>'.
21492:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
21493:                                        '</ul>'.
21494:                                        '</li>';
21495:                     } else {
21496:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
21497:                     }
21498:                 } elsif ($item eq 'postsubmit') {
21499:                     if ($domdefaults{'postsubmit'} eq 'off') {
21500:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
21501:                     } else {
21502:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
21503:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21504:                             $resulttext .= &mt('durations:').'<ul>';
21505:                             foreach my $type (@types) {
21506:                                 $resulttext .= '<li>';
21507:                                 my $timeout;
21508:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
21509:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
21510:                                 }
21511:                                 my $display;
21512:                                 if ($timeout eq '0') {
21513:                                     $display = &mt('unlimited');
21514:                                 } elsif ($timeout eq '') {
21515:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
21516:                                 } else {
21517:                                     $display = &mt('[quant,_1,second]',$timeout);
21518:                                 }
21519:                                 if ($type eq 'community') {
21520:                                     $resulttext .= &mt('Communities');
21521:                                 } elsif ($type eq 'official') {
21522:                                     $resulttext .= &mt('Official courses');
21523:                                 } elsif ($type eq 'unofficial') {
21524:                                     $resulttext .= &mt('Unofficial courses');
21525:                                 } elsif ($type eq 'textbook') {
21526:                                     $resulttext .= &mt('Textbook courses');
21527:                                 } elsif ($type eq 'placement') {
21528:                                     $resulttext .= &mt('Placement tests');
21529:                                 }
21530:                                 $resulttext .= ' -- '.$display.'</li>';
21531:                             }
21532:                             $resulttext .= '</ul>';
21533:                         }
21534:                         $resulttext .= '</li>';
21535:                     }
21536:                 } elsif ($item eq 'coursecredits') {
21537:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
21538:                         if (($domdefaults{'officialcredits'} eq '') &&
21539:                             ($domdefaults{'unofficialcredits'} eq '') &&
21540:                             ($domdefaults{'textbookcredits'} eq '')) {
21541:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
21542:                         } else {
21543:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
21544:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
21545:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
21546:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
21547:                                            '</ul>'.
21548:                                            '</li>';
21549:                         }
21550:                     } else {
21551:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
21552:                     }
21553:                 } elsif ($item eq 'canclone') {
21554:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
21555:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
21556:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
21557:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
21558:                         }
21559:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
21560:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
21561:                     } else {
21562:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
21563:                     }
21564:                 } elsif ($item eq 'ltiauth') {
21565:                     if ($env{'form.'.$item} eq '1') {
21566:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL need not require re-authentication').'</li>';
21567:                     } else {
21568:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL will require re-authentication').'</li>';
21569:                     }
21570:                 }
21571:             }
21572:             $resulttext .= '</ul>';
21573:         } else {
21574:             $resulttext = &mt('No changes made to course defaults');
21575:         }
21576:     } else {
21577:         $resulttext = '<span class="LC_error">'.
21578:             &mt('An error occurred: [_1]',$putresult).'</span>';
21579:     }
21580:     return $resulttext;
21581: }
21582: 
21583: sub modify_selfenrollment {
21584:     my ($dom,$lastactref,%domconfig) = @_;
21585:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
21586:     my @types = ('official','unofficial','community','textbook','placement');
21587:     my %titles = &tool_titles();
21588:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
21589:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
21590:     $ordered{'default'} = ['types','registered','approval','limit'];
21591: 
21592:     my (%roles,%shown,%toplevel);
21593:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
21594: 
21595:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
21596:         if ($domconfig{'selfenrollment'} eq '') {
21597:             $domconfig{'selfenrollment'} = {};
21598:         }
21599:     }
21600:     %toplevel = (
21601:                   admin      => 'Configuration Rights',
21602:                   default    => 'Default settings',
21603:                   validation => 'Validation of self-enrollment requests',
21604:                 );
21605:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
21606: 
21607:     if (ref($ordered{'admin'}) eq 'ARRAY') {
21608:         foreach my $item (@{$ordered{'admin'}}) {
21609:             foreach my $type (@types) {
21610:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
21611:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
21612:                 } else {
21613:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
21614:                 }
21615:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
21616:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
21617:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
21618:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
21619:                             push(@{$changes{'admin'}{$type}},$item);
21620:                         }
21621:                     } else {
21622:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
21623:                             push(@{$changes{'admin'}{$type}},$item);
21624:                         }
21625:                     }
21626:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
21627:                     push(@{$changes{'admin'}{$type}},$item);
21628:                 }
21629:             }
21630:         }
21631:     }
21632: 
21633:     foreach my $item (@{$ordered{'default'}}) {
21634:         foreach my $type (@types) {
21635:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
21636:             if ($item eq 'types') {
21637:                 unless (($value eq 'all') || ($value eq 'dom')) {
21638:                     $value = '';
21639:                 }
21640:             } elsif ($item eq 'registered') {
21641:                 unless ($value eq '1') {
21642:                     $value = 0;
21643:                 }
21644:             } elsif ($item eq 'approval') {
21645:                 unless ($value =~ /^[012]$/) {
21646:                     $value = 0;
21647:                 }
21648:             } else {
21649:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
21650:                     $value = 'none';
21651:                 }
21652:             }
21653:             $selfenrollhash{'default'}{$type}{$item} = $value;
21654:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
21655:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
21656:                     if ($selfenrollhash{'default'}{$type}{$item} ne
21657:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
21658:                          push(@{$changes{'default'}{$type}},$item);
21659:                     }
21660:                 } else {
21661:                     push(@{$changes{'default'}{$type}},$item);
21662:                 }
21663:             } else {
21664:                 push(@{$changes{'default'}{$type}},$item);
21665:             }
21666:             if ($item eq 'limit') {
21667:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
21668:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
21669:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
21670:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
21671:                     }
21672:                 } else {
21673:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
21674:                 }
21675:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
21676:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
21677:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
21678:                          push(@{$changes{'default'}{$type}},'cap');
21679:                     }
21680:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
21681:                     push(@{$changes{'default'}{$type}},'cap');
21682:                 }
21683:             }
21684:         }
21685:     }
21686: 
21687:     foreach my $item (@{$itemsref}) {
21688:         if ($item eq 'fields') {
21689:             my @changed;
21690:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
21691:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
21692:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
21693:             }
21694:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
21695:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
21696:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
21697:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
21698:                 } else {
21699:                     @changed = @{$selfenrollhash{'validation'}{$item}};
21700:                 }
21701:             } else {
21702:                 @changed = @{$selfenrollhash{'validation'}{$item}};
21703:             }
21704:             if (@changed) {
21705:                 if ($selfenrollhash{'validation'}{$item}) { 
21706:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
21707:                 } else {
21708:                     $changes{'validation'}{$item} = &mt('None');
21709:                 }
21710:             }
21711:         } else {
21712:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
21713:             if ($item eq 'markup') {
21714:                if ($env{'form.selfenroll_validation_'.$item}) {
21715:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
21716:                }
21717:             }
21718:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
21719:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
21720:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
21721:                 }
21722:             }
21723:         }
21724:     }
21725: 
21726:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
21727:                                              $dom);
21728:     if ($putresult eq 'ok') {
21729:         if (keys(%changes) > 0) {
21730:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21731:             $resulttext = &mt('Changes made:').'<ul>';
21732:             foreach my $key ('admin','default','validation') {
21733:                 if (ref($changes{$key}) eq 'HASH') {
21734:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
21735:                     if ($key eq 'validation') {
21736:                         foreach my $item (@{$itemsref}) {
21737:                             if (exists($changes{$key}{$item})) {
21738:                                 if ($item eq 'markup') {
21739:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
21740:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
21741:                                 } else {  
21742:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
21743:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
21744:                                 }
21745:                             }
21746:                         }
21747:                     } else {
21748:                         foreach my $type (@types) {
21749:                             if ($type eq 'community') {
21750:                                 $roles{'1'} = &mt('Community personnel');
21751:                             } else {
21752:                                 $roles{'1'} = &mt('Course personnel');
21753:                             }
21754:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
21755:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
21756:                                     if ($key eq 'admin') {
21757:                                         my @mgrdc = ();
21758:                                         if (ref($ordered{$key}) eq 'ARRAY') {
21759:                                             foreach my $item (@{$ordered{'admin'}}) {
21760:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
21761:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
21762:                                                         push(@mgrdc,$item);
21763:                                                     }
21764:                                                 }
21765:                                             }
21766:                                             if (@mgrdc) {
21767:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
21768:                                             } else {
21769:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
21770:                                             }
21771:                                         }
21772:                                     } else {
21773:                                         if (ref($ordered{$key}) eq 'ARRAY') {
21774:                                             foreach my $item (@{$ordered{$key}}) {
21775:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
21776:                                                     $domdefaults{$type.'selfenroll'.$item} =
21777:                                                         $selfenrollhash{$key}{$type}{$item};
21778:                                                 }
21779:                                             }
21780:                                         }
21781:                                     }
21782:                                 }
21783:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
21784:                                 foreach my $item (@{$ordered{$key}}) {
21785:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
21786:                                         $resulttext .= '<li>';
21787:                                         if ($key eq 'admin') {
21788:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
21789:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
21790:                                         } else {
21791:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
21792:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
21793:                                         }
21794:                                         $resulttext .= '</li>';
21795:                                     }
21796:                                 }
21797:                                 $resulttext .= '</ul></li>';
21798:                             }
21799:                         }
21800:                         $resulttext .= '</ul></li>'; 
21801:                     }
21802:                 }
21803:             }
21804:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
21805:                 my $cachetime = 24*60*60;
21806:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21807:                 if (ref($lastactref) eq 'HASH') {
21808:                     $lastactref->{'domdefaults'} = 1;
21809:                 }
21810:             }
21811:             $resulttext .= '</ul>';
21812:         } else {
21813:             $resulttext = &mt('No changes made to self-enrollment settings');
21814:         }
21815:     } else {
21816:         $resulttext = '<span class="LC_error">'.
21817:             &mt('An error occurred: [_1]',$putresult).'</span>';
21818:     }
21819:     return $resulttext;
21820: }
21821: 
21822: sub modify_wafproxy {
21823:     my ($dom,$action,$lastactref,%domconfig) = @_;
21824:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
21825:     my (%othercontrol,%canset,%values,%curralias,%currsaml,%currvalue,@warnings,
21826:         %wafproxy,%changes,%expirecache,%expiresaml);
21827:     foreach my $server (sort(keys(%servers))) {
21828:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
21829:         if ($serverhome eq $server) {
21830:             my $serverdom = &Apache::lonnet::host_domain($server);
21831:             if ($serverdom eq $dom) {
21832:                 $canset{$server} = 1;
21833:             }
21834:         }
21835:     }
21836:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
21837:         %{$values{$dom}} = ();
21838:         if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
21839:             %curralias = %{$domconfig{'wafproxy'}{'alias'}};
21840:         }
21841:         if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
21842:             %currsaml = %{$domconfig{'wafproxy'}{'saml'}};
21843:         }
21844:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
21845:             $currvalue{$item} = $domconfig{'wafproxy'}{$item};
21846:         }
21847:     }
21848:     my $output;
21849:     if (keys(%canset)) {
21850:         %{$wafproxy{'alias'}} = ();
21851:         %{$wafproxy{'saml'}} = ();
21852:         foreach my $key (sort(keys(%canset))) {
21853:             if ($env{'form.wafproxy_'.$dom}) {
21854:                 $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
21855:                 $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
21856:                 if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
21857:                     $changes{'alias'} = 1;
21858:                 }
21859:                 if ($env{'form.wafproxy_alias_saml_'.$key}) {
21860:                     $wafproxy{'saml'}{$key} = 1;
21861:                 }
21862:                 if ($wafproxy{'saml'}{$key} ne $currsaml{$key}) {
21863:                     $changes{'saml'} = 1;
21864:                 }
21865:             } else {
21866:                 $wafproxy{'alias'}{$key} = '';
21867:                 $wafproxy{'saml'}{$key} = '';
21868:                 if ($curralias{$key}) {
21869:                     $changes{'alias'} = 1;
21870:                 }
21871:                 if ($currsaml{$key}) {
21872:                     $changes{'saml'} = 1;
21873:                 }
21874:             }
21875:             if ($wafproxy{'alias'}{$key} eq '') {
21876:                 if ($curralias{$key}) {
21877:                     $expirecache{$key} = 1;
21878:                 }
21879:                 delete($wafproxy{'alias'}{$key});
21880:             }
21881:             if ($wafproxy{'saml'}{$key} eq '') {
21882:                 if ($currsaml{$key}) {
21883:                     $expiresaml{$key} = 1;
21884:                 }
21885:                 delete($wafproxy{'saml'}{$key});
21886:             }
21887:         }
21888:         unless (keys(%{$wafproxy{'alias'}})) {
21889:             delete($wafproxy{'alias'});
21890:         }
21891:         unless (keys(%{$wafproxy{'saml'}})) {
21892:             delete($wafproxy{'saml'});
21893:         }
21894:         # Localization for values in %warn occurs in &mt() calls separately.
21895:         my %warn = (
21896:                      trusted => 'trusted IP range(s)',
21897:                      vpnint => 'internal IP range(s) for VPN sessions(s)',
21898:                      vpnext => 'IP range(s) for backend WAF connections',
21899:                    );
21900:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
21901:             my $possible = $env{'form.wafproxy_'.$item};
21902:             $possible =~ s/^\s+|\s+$//g;
21903:             if ($possible ne '') {
21904:                 if ($item eq 'remoteip') {
21905:                     if ($possible =~ /^[mhn]$/) {
21906:                         $wafproxy{$item} = $possible;
21907:                     }
21908:                 } elsif ($item eq 'ipheader') {
21909:                     if ($wafproxy{'remoteip'} eq 'h') {
21910:                         $wafproxy{$item} = $possible;
21911:                     }
21912:                 } elsif ($item eq 'sslopt') {
21913:                     if ($possible =~ /^0|1$/) {
21914:                         $wafproxy{$item} = $possible;
21915:                     }
21916:                 } else {
21917:                     my (@ok,$count);
21918:                     if (($item eq 'vpnint') || ($item eq 'vpnext')) {
21919:                         unless ($env{'form.wafproxy_vpnaccess'}) {
21920:                             $possible = '';
21921:                         }
21922:                     } elsif ($item eq 'trusted') {
21923:                         unless ($wafproxy{'remoteip'} eq 'h') {
21924:                             $possible = '';
21925:                         }
21926:                     }
21927:                     unless ($possible eq '') {
21928:                         $possible =~ s/[\r\n]+/\s/g;
21929:                         $possible =~ s/\s*-\s*/-/g;
21930:                         $possible =~ s/\s+/,/g;
21931:                         $possible =~ s/,+/,/g;
21932:                     }
21933:                     $count = 0;
21934:                     if ($possible ne '') {
21935:                         foreach my $poss (split(/\,/,$possible)) {
21936:                             $count ++;
21937:                             $poss = &validate_ip_pattern($poss);
21938:                             if ($poss ne '') {
21939:                                 push(@ok,$poss);
21940:                             }
21941:                         }
21942:                         my $diff = $count - scalar(@ok);
21943:                         if ($diff) {
21944:                             push(@warnings,'<li>'.
21945:                                  &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
21946:                                      $diff,$warn{$item}).
21947:                                  '</li>');
21948:                         }
21949:                         if (@ok) {
21950:                             my @cidr_list;
21951:                             foreach my $item (@ok) {
21952:                                 @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
21953:                             }
21954:                             $wafproxy{$item} = join(',',@cidr_list);
21955:                         }
21956:                     }
21957:                 }
21958:                 if ($wafproxy{$item} ne $currvalue{$item}) {
21959:                     $changes{$item} = 1;
21960:                 }
21961:             } elsif ($currvalue{$item}) {
21962:                 $changes{$item} = 1;
21963:             } 
21964:         }
21965:     } else {
21966:         if (keys(%curralias)) {
21967:             $changes{'alias'} = 1;
21968:         }
21969:         if (keys(%currsaml)) {
21970:             $changes{'saml'} = 1;
21971:         } 
21972:         if (keys(%currvalue)) {
21973:             foreach my $key (keys(%currvalue)) {
21974:                 $changes{$key} = 1;
21975:             }
21976:         }
21977:     }
21978:     if (keys(%changes)) {
21979:         my %defaultshash = (
21980:                               wafproxy => \%wafproxy,
21981:                            ); 
21982:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
21983:                                                  $dom);
21984:         if ($putresult eq 'ok') {
21985:             my $cachetime = 24*60*60;
21986:             my (%domdefaults,$updatedomdefs);
21987:             foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
21988:                 if ($changes{$item}) {
21989:                     unless ($updatedomdefs) {
21990:                         %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
21991:                         $updatedomdefs = 1;
21992:                     }
21993:                     if ($wafproxy{$item}) {
21994:                         $domdefaults{'waf_'.$item} = $wafproxy{$item};
21995:                     } elsif (exists($domdefaults{'waf_'.$item})) {
21996:                         delete($domdefaults{'waf_'.$item});
21997:                     } 
21998:                 }
21999:             }
22000:             if ($updatedomdefs) {
22001:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22002:                 if (ref($lastactref) eq 'HASH') {
22003:                     $lastactref->{'domdefaults'} = 1;
22004:                 }
22005:             }
22006:             if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
22007:                 my %updates = %expirecache;
22008:                 foreach my $key (keys(%expirecache)) {
22009:                     &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
22010:                 }
22011:                 if (ref($wafproxy{'alias'}) eq 'HASH') {
22012:                     my $cachetime = 24*60*60;
22013:                     foreach my $key (keys(%{$wafproxy{'alias'}})) {
22014:                         $updates{$key} = 1;
22015:                         &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
22016:                                                       $cachetime);
22017:                     }
22018:                 }
22019:                 if (ref($lastactref) eq 'HASH') {
22020:                     $lastactref->{'proxyalias'} = \%updates;
22021:                 }
22022:             }
22023:             if ((exists($wafproxy{'saml'})) || (keys(%expiresaml))) {
22024:                 my %samlupdates = %expiresaml;
22025:                 foreach my $key (keys(%expiresaml)) {
22026:                     &Apache::lonnet::devalidate_cache_new('proxysaml',$key);
22027:                 }
22028:                 if (ref($wafproxy{'saml'}) eq 'HASH') {
22029:                     my $cachetime = 24*60*60;
22030:                     foreach my $key (keys(%{$wafproxy{'saml'}})) {
22031:                         $samlupdates{$key} = 1;
22032:                         &Apache::lonnet::do_cache_new('proxysaml',$key,$wafproxy{'saml'}{$key},
22033:                                                       $cachetime);
22034:                     }
22035:                 }
22036:                 if (ref($lastactref) eq 'HASH') {
22037:                     $lastactref->{'proxysaml'} = \%samlupdates;
22038:                 }
22039:             }
22040:             $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
22041:             foreach my $item ('alias','saml','remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
22042:                 if ($changes{$item}) {
22043:                     if ($item eq 'alias') {
22044:                         my $numaliased = 0;
22045:                         if (ref($wafproxy{'alias'}) eq 'HASH') {
22046:                             my $shown;
22047:                             if (keys(%{$wafproxy{'alias'}})) {
22048:                                 foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
22049:                                     $shown .= '<li>'.&mt('[_1] aliased by [_2]',
22050:                                                          &Apache::lonnet::hostname($server),
22051:                                                          $wafproxy{'alias'}{$server}).'</li>';
22052:                                     $numaliased ++;
22053:                                 }
22054:                                 if ($numaliased) {
22055:                                     $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
22056:                                                           '<ul>'.$shown.'</ul>').'</li>';
22057:                                 }
22058:                             }
22059:                         }
22060:                         unless ($numaliased) {
22061:                             $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
22062:                         }
22063:                     } elsif ($item eq 'saml') {
22064:                         my $shown; 
22065:                         if (ref($wafproxy{'saml'}) eq 'HASH') {
22066:                             if (keys(%{$wafproxy{'saml'}})) {
22067:                                 $shown = join(', ',sort(keys(%{$wafproxy{'saml'}})));
22068:                             }
22069:                         }
22070:                         if ($shown) {
22071:                             $output .= '<li>'.&mt('Alias used by SSO Auth for: [_1]',
22072:                                                   $shown).'</li>';
22073:                         } else {
22074:                             $output .= '<li>'.&mt('No alias used for SSO Auth').'</li>';
22075:                         }
22076:                     } else {
22077:                         if ($item eq 'remoteip') {
22078:                             my %ip_methods = &remoteip_methods();
22079:                             if ($wafproxy{$item} =~ /^[mh]$/) {
22080:                                 $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
22081:                                                       $ip_methods{$wafproxy{$item}}).'</li>';
22082:                             } else {
22083:                                 if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
22084:                                     $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
22085:                                                '</li>';
22086:                                 } else {
22087:                                     $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
22088:                                 }
22089:                             }
22090:                         } elsif ($item eq 'ipheader') {
22091:                             if ($wafproxy{$item}) {
22092:                                 $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
22093:                                                       $wafproxy{$item}).'</li>';
22094:                             } else {
22095:                                 $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
22096:                             }
22097:                         } elsif ($item eq 'trusted') {
22098:                             if ($wafproxy{$item}) {
22099:                                 $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
22100:                                                       $wafproxy{$item}).'</li>';
22101:                             } else {
22102:                                 $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
22103:                             }
22104:                         } elsif ($item eq 'vpnint') {
22105:                             if ($wafproxy{$item}) {
22106:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
22107:                                                        $wafproxy{$item}).'</li>';
22108:                             } else {
22109:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
22110:                             }
22111:                         } elsif ($item eq 'vpnext') {
22112:                             if ($wafproxy{$item}) {
22113:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
22114:                                                        $wafproxy{$item}).'</li>';
22115:                             } else {
22116:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
22117:                             }
22118:                         } elsif ($item eq 'sslopt') {
22119:                             if ($wafproxy{$item}) {
22120:                                 $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>';
22121:                             } else {
22122:                                 $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>';
22123:                             }
22124:                         }
22125:                     }
22126:                 }
22127:             }
22128:         } else {
22129:             $output = '<span class="LC_error">'.
22130:                       &mt('An error occurred: [_1]',$putresult).'</span>';
22131:         }
22132:     } elsif (keys(%canset)) {
22133:         $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
22134:     }
22135:     if (@warnings) {
22136:         $output .= '<br />'.&mt('Warnings:').'<ul>'.
22137:                        join("\n",@warnings).'</ul>';
22138:     }
22139:     return $output;
22140: }
22141: 
22142: sub validate_ip_pattern {
22143:     my ($pattern) = @_;
22144:     if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
22145:         my ($start,$end) = ($1,$2);
22146:         if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
22147:             if (($start !~ m{/}) && ($end !~ m{/})) {
22148:                 return $start.'-'.$end;
22149:             }
22150:         }
22151:     } elsif ($pattern ne '') {
22152:         $pattern = &Net::CIDR::cidrvalidate($pattern);
22153:         if ($pattern ne '') {
22154:             return $pattern;
22155:         }
22156:     }
22157:     return;
22158: }
22159: 
22160: sub modify_usersessions {
22161:     my ($dom,$lastactref,%domconfig) = @_;
22162:     my @hostingtypes = ('version','excludedomain','includedomain');
22163:     my @offloadtypes = ('primary','default');
22164:     my %types = (
22165:                   remote => \@hostingtypes,
22166:                   hosted => \@hostingtypes,
22167:                   spares => \@offloadtypes,
22168:                 );
22169:     my @prefixes = ('remote','hosted','spares');
22170:     my @lcversions = &Apache::lonnet::all_loncaparevs();
22171:     my (%by_ip,%by_location,@intdoms,@instdoms);
22172:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
22173:     my @locations = sort(keys(%by_location));
22174:     my (%defaultshash,%changes);
22175:     foreach my $prefix (@prefixes) {
22176:         $defaultshash{'usersessions'}{$prefix} = {};
22177:     }
22178:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
22179:     my $resulttext;
22180:     my %iphost = &Apache::lonnet::get_iphost();
22181:     foreach my $prefix (@prefixes) {
22182:         next if ($prefix eq 'spares');
22183:         foreach my $type (@{$types{$prefix}}) {
22184:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22185:             if ($type eq 'version') {
22186:                 my $value = $env{'form.'.$prefix.'_'.$type};
22187:                 my $okvalue;
22188:                 if ($value ne '') {
22189:                     if (grep(/^\Q$value\E$/,@lcversions)) {
22190:                         $okvalue = $value;
22191:                     }
22192:                 }
22193:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
22194:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
22195:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
22196:                             if ($inuse == 0) {
22197:                                 $changes{$prefix}{$type} = 1;
22198:                             } else {
22199:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
22200:                                     $changes{$prefix}{$type} = 1;
22201:                                 }
22202:                                 if ($okvalue ne '') {
22203:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22204:                                 } 
22205:                             }
22206:                         } else {
22207:                             if (($inuse == 1) && ($okvalue ne '')) {
22208:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22209:                                 $changes{$prefix}{$type} = 1;
22210:                             }
22211:                         }
22212:                     } else {
22213:                         if (($inuse == 1) && ($okvalue ne '')) {
22214:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22215:                             $changes{$prefix}{$type} = 1;
22216:                         }
22217:                     }
22218:                 } else {
22219:                     if (($inuse == 1) && ($okvalue ne '')) {
22220:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22221:                         $changes{$prefix}{$type} = 1;
22222:                     }
22223:                 }
22224:             } else {
22225:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22226:                 my @okvals;
22227:                 foreach my $val (@vals) {
22228:                     if ($val =~ /:/) {
22229:                         my @items = split(/:/,$val);
22230:                         foreach my $item (@items) {
22231:                             if (ref($by_location{$item}) eq 'ARRAY') {
22232:                                 push(@okvals,$item);
22233:                             }
22234:                         }
22235:                     } else {
22236:                         if (ref($by_location{$val}) eq 'ARRAY') {
22237:                             push(@okvals,$val);
22238:                         }
22239:                     }
22240:                 }
22241:                 @okvals = sort(@okvals);
22242:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
22243:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
22244:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
22245:                             if ($inuse == 0) {
22246:                                 $changes{$prefix}{$type} = 1; 
22247:                             } else {
22248:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22249:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
22250:                                 if (@changed > 0) {
22251:                                     $changes{$prefix}{$type} = 1;
22252:                                 }
22253:                             }
22254:                         } else {
22255:                             if ($inuse == 1) {
22256:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22257:                                 $changes{$prefix}{$type} = 1;
22258:                             }
22259:                         } 
22260:                     } else {
22261:                         if ($inuse == 1) {
22262:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22263:                             $changes{$prefix}{$type} = 1;
22264:                         }
22265:                     }
22266:                 } else {
22267:                     if ($inuse == 1) {
22268:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22269:                         $changes{$prefix}{$type} = 1;
22270:                     }
22271:                 }
22272:             }
22273:         }
22274:     }
22275: 
22276:     my @alldoms = &Apache::lonnet::all_domains();
22277:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22278:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
22279:     my $savespares;
22280: 
22281:     foreach my $lonhost (sort(keys(%servers))) {
22282:         my $serverhomeID =
22283:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
22284:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
22285:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
22286:         my %spareschg;
22287:         foreach my $type (@{$types{'spares'}}) {
22288:             my @okspares;
22289:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
22290:             foreach my $server (@checked) {
22291:                 if (&Apache::lonnet::hostname($server) ne '') {
22292:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
22293:                         unless (grep(/^\Q$server\E$/,@okspares)) {
22294:                             push(@okspares,$server);
22295:                         }
22296:                     }
22297:                 }
22298:             }
22299:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
22300:             my $newspare;
22301:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
22302:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
22303:                     $newspare = $new;
22304:                 }
22305:             }
22306:             my @spares;
22307:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
22308:                 @spares = sort(@okspares,$newspare);
22309:             } else {
22310:                 @spares = sort(@okspares);
22311:             }
22312:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
22313:             if (ref($spareid{$lonhost}) eq 'HASH') {
22314:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
22315:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
22316:                     if (@diffs > 0) {
22317:                         $spareschg{$type} = 1;
22318:                     }
22319:                 }
22320:             }
22321:         }
22322:         if (keys(%spareschg) > 0) {
22323:             $changes{'spares'}{$lonhost} = \%spareschg;
22324:         }
22325:     }
22326:     $defaultshash{'usersessions'}{'offloadnow'} = {};
22327:     $defaultshash{'usersessions'}{'offloadoth'} = {};
22328:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
22329:     my @okoffload;
22330:     if (@offloadnow) {
22331:         foreach my $server (@offloadnow) {
22332:             if (&Apache::lonnet::hostname($server) ne '') {
22333:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
22334:                     push(@okoffload,$server);
22335:                 }
22336:             }
22337:         }
22338:         if (@okoffload) {
22339:             foreach my $lonhost (@okoffload) {
22340:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
22341:             }
22342:         }
22343:     }
22344:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
22345:     my @okoffloadoth;
22346:     if (@offloadoth) {
22347:         foreach my $server (@offloadoth) {
22348:             if (&Apache::lonnet::hostname($server) ne '') {
22349:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
22350:                     push(@okoffloadoth,$server);
22351:                 }
22352:             }
22353:         }
22354:         if (@okoffloadoth) {
22355:             foreach my $lonhost (@okoffloadoth) {
22356:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
22357:             }
22358:         }
22359:     }
22360:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
22361:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
22362:             if (ref($changes{'spares'}) eq 'HASH') {
22363:                 if (keys(%{$changes{'spares'}}) > 0) {
22364:                     $savespares = 1;
22365:                 }
22366:             }
22367:         } else {
22368:             $savespares = 1;
22369:         }
22370:         foreach my $offload ('offloadnow','offloadoth') {
22371:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
22372:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
22373:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
22374:                         $changes{$offload} = 1;
22375:                         last;
22376:                     }
22377:                 }
22378:                 unless ($changes{$offload}) {
22379:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
22380:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
22381:                             $changes{$offload} = 1;
22382:                             last;
22383:                         }
22384:                     }
22385:                 }
22386:             } else {
22387:                 if (($offload eq 'offloadnow') && (@okoffload)) {
22388:                      $changes{'offloadnow'} = 1;
22389:                 }
22390:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
22391:                     $changes{'offloadoth'} = 1;
22392:                 }
22393:             } 
22394:         }
22395:     } else {
22396:         if (@okoffload) {
22397:             $changes{'offloadnow'} = 1;
22398:         }
22399:         if (@okoffloadoth) {
22400:             $changes{'offloadoth'} = 1;
22401:         }
22402:     }
22403:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
22404:     if ((keys(%changes) > 0) || ($savespares)) {
22405:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22406:                                                  $dom);
22407:         if ($putresult eq 'ok') {
22408:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
22409:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
22410:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
22411:                 }
22412:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
22413:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
22414:                 }
22415:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
22416:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
22417:                 }
22418:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
22419:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
22420:                 }
22421:             }
22422:             my $cachetime = 24*60*60;
22423:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22424:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
22425:             if (ref($lastactref) eq 'HASH') {
22426:                 $lastactref->{'domdefaults'} = 1;
22427:                 $lastactref->{'usersessions'} = 1;
22428:             }
22429:             if (keys(%changes) > 0) {
22430:                 my %lt = &usersession_titles();
22431:                 $resulttext = &mt('Changes made:').'<ul>';
22432:                 foreach my $prefix (@prefixes) {
22433:                     if (ref($changes{$prefix}) eq 'HASH') {
22434:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
22435:                         if ($prefix eq 'spares') {
22436:                             if (ref($changes{$prefix}) eq 'HASH') {
22437:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
22438:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
22439:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
22440:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
22441:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
22442:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
22443:                                         foreach my $type (@{$types{$prefix}}) {
22444:                                             if ($changes{$prefix}{$lonhost}{$type}) {
22445:                                                 my $offloadto = &mt('None');
22446:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
22447:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
22448:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
22449:                                                     }
22450:                                                 }
22451:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
22452:                                             }
22453:                                         }
22454:                                     }
22455:                                     $resulttext .= '</li>';
22456:                                 }
22457:                             }
22458:                         } else {
22459:                             foreach my $type (@{$types{$prefix}}) {
22460:                                 if (defined($changes{$prefix}{$type})) {
22461:                                     my ($newvalue,$notinuse);
22462:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
22463:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
22464:                                             if ($type eq 'version') {
22465:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
22466:                                             } else {
22467:                                                 if (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
22468:                                                     if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
22469:                                                         $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
22470:                                                     }
22471:                                                 } else {
22472:                                                     $notinuse = 1;
22473:                                                 }
22474:                                             }
22475:                                         }
22476:                                     }
22477:                                     if ($newvalue eq '') {
22478:                                         if ($type eq 'version') {
22479:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
22480:                                         } elsif ($notinuse) {
22481:                                             $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
22482:                                         } else {
22483:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
22484:                                         }
22485:                                     } else {
22486:                                         if ($type eq 'version') {
22487:                                             $newvalue .= ' '.&mt('(or later)');
22488:                                         }
22489:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
22490:                                     }
22491:                                 }
22492:                             }
22493:                         }
22494:                         $resulttext .= '</ul>';
22495:                     }
22496:                 }
22497:                 if ($changes{'offloadnow'}) {
22498:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
22499:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
22500:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
22501:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
22502:                                 $resulttext .= '<li>'.$lonhost.'</li>';
22503:                             }
22504:                             $resulttext .= '</ul>';
22505:                         } else {
22506:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
22507:                         }
22508:                     } else {
22509:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
22510:                     }
22511:                 }
22512:                 if ($changes{'offloadoth'}) {
22513:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
22514:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
22515:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
22516:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
22517:                                 $resulttext .= '<li>'.$lonhost.'</li>';
22518:                             }
22519:                             $resulttext .= '</ul>';
22520:                         } else {
22521:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
22522:                         }
22523:                     } else {
22524:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
22525:                     }
22526:                 }
22527:                 $resulttext .= '</ul>';
22528:             } else {
22529:                 $resulttext = $nochgmsg;
22530:             }
22531:         } else {
22532:             $resulttext = '<span class="LC_error">'.
22533:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22534:         }
22535:     } else {
22536:         $resulttext = $nochgmsg;
22537:     }
22538:     return $resulttext;
22539: }
22540: 
22541: sub modify_ssl {
22542:     my ($dom,$lastactref,%domconfig) = @_;
22543:     my (%by_ip,%by_location,@intdoms,@instdoms);
22544:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
22545:     my @locations = sort(keys(%by_location));
22546:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22547:     my (%defaultshash,%changes);
22548:     my $action = 'ssl';
22549:     my @prefixes = ('connto','connfrom','replication');
22550:     foreach my $prefix (@prefixes) {
22551:         $defaultshash{$action}{$prefix} = {};
22552:     }
22553:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
22554:     my $resulttext;
22555:     my %iphost = &Apache::lonnet::get_iphost();
22556:     my @reptypes = ('certreq','nocertreq');
22557:     my @connecttypes = ('dom','intdom','other');
22558:     my %types = (
22559:                   connto      => \@connecttypes,
22560:                   connfrom    => \@connecttypes,
22561:                   replication => \@reptypes,
22562:                 );
22563:     foreach my $prefix (sort(keys(%types))) {
22564:         foreach my $type (@{$types{$prefix}}) {
22565:             if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
22566:                 my $value = 'yes';
22567:                 if ($env{'form.'.$prefix.'_'.$type} =~ /^(no|req)$/) {
22568:                     $value = $env{'form.'.$prefix.'_'.$type};
22569:                 }
22570:                 if (ref($domconfig{$action}) eq 'HASH') {
22571:                     if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
22572:                         if ($domconfig{$action}{$prefix}{$type} ne '') {
22573:                             if ($value ne $domconfig{$action}{$prefix}{$type}) {
22574:                                 $changes{$prefix}{$type} = 1;
22575:                             }
22576:                             $defaultshash{$action}{$prefix}{$type} = $value;
22577:                         } else {
22578:                             $defaultshash{$action}{$prefix}{$type} = $value;
22579:                             $changes{$prefix}{$type} = 1;
22580:                         }
22581:                     } else {
22582:                         $defaultshash{$action}{$prefix}{$type} = $value;
22583:                         $changes{$prefix}{$type} = 1;
22584:                     }
22585:                 } else {
22586:                     $defaultshash{$action}{$prefix}{$type} = $value;
22587:                     $changes{$prefix}{$type} = 1;
22588:                 }
22589:                 if (($type eq 'dom') && (keys(%servers) == 1)) {
22590:                     delete($changes{$prefix}{$type});
22591:                 } elsif (($type eq 'intdom') && (@instdoms == 1)) {
22592:                     delete($changes{$prefix}{$type});
22593:                 } elsif (($type eq 'other') && (keys(%by_location) == 0)) { 
22594:                     delete($changes{$prefix}{$type});
22595:                 }
22596:             } elsif ($prefix eq 'replication') {
22597:                 if (@locations > 0) {
22598:                     my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22599:                     my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22600:                     my @okvals;
22601:                     foreach my $val (@vals) {
22602:                         if ($val =~ /:/) {
22603:                             my @items = split(/:/,$val);
22604:                             foreach my $item (@items) {
22605:                                 if (ref($by_location{$item}) eq 'ARRAY') {
22606:                                     push(@okvals,$item);
22607:                                 }
22608:                             }
22609:                         } else {
22610:                             if (ref($by_location{$val}) eq 'ARRAY') {
22611:                                 push(@okvals,$val);
22612:                             }
22613:                         }
22614:                     }
22615:                     @okvals = sort(@okvals);
22616:                     if (ref($domconfig{$action}) eq 'HASH') {
22617:                         if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
22618:                             if (ref($domconfig{$action}{$prefix}{$type}) eq 'ARRAY') {
22619:                                 if ($inuse == 0) {
22620:                                     $changes{$prefix}{$type} = 1;
22621:                                 } else {
22622:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
22623:                                     my @changed = &Apache::loncommon::compare_arrays($domconfig{$action}{$prefix}{$type},$defaultshash{$action}{$prefix}{$type});
22624:                                     if (@changed > 0) {
22625:                                         $changes{$prefix}{$type} = 1;
22626:                                     }
22627:                                 }
22628:                             } else {
22629:                                 if ($inuse == 1) {
22630:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
22631:                                     $changes{$prefix}{$type} = 1;
22632:                                 }
22633:                             }
22634:                         } else {
22635:                             if ($inuse == 1) {
22636:                                 $defaultshash{$action}{$prefix}{$type} = \@okvals;
22637:                                 $changes{$prefix}{$type} = 1;
22638:                             }
22639:                         }
22640:                     } else {
22641:                         if ($inuse == 1) {
22642:                             $defaultshash{$action}{$prefix}{$type} = \@okvals;
22643:                             $changes{$prefix}{$type} = 1;
22644:                         }
22645:                     }
22646:                 }
22647:             }
22648:         }
22649:     }
22650:     if (keys(%changes)) {
22651:         foreach my $prefix (keys(%changes)) {
22652:             if (ref($changes{$prefix}) eq 'HASH') {
22653:                 if (scalar(keys(%{$changes{$prefix}})) == 0) {
22654:                     delete($changes{$prefix});
22655:                 }
22656:             } else {
22657:                 delete($changes{$prefix});
22658:             }
22659:         }
22660:     }
22661:     my $nochgmsg = &mt('No changes made to LON-CAPA SSL settings');
22662:     if (keys(%changes) > 0) {
22663:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22664:                                                  $dom);
22665:         if ($putresult eq 'ok') {
22666:             if (ref($defaultshash{$action}) eq 'HASH') {
22667:                 if (ref($defaultshash{$action}{'replication'}) eq 'HASH') {
22668:                     $domdefaults{'replication'} = $defaultshash{$action}{'replication'};
22669:                 }
22670:                 if (ref($defaultshash{$action}{'connto'}) eq 'HASH') {
22671:                     $domdefaults{'connto'} = $defaultshash{$action}{'connto'};
22672:                 }
22673:                 if (ref($defaultshash{$action}{'connfrom'}) eq 'HASH') {
22674:                     $domdefaults{'connfrom'} = $defaultshash{$action}{'connfrom'};
22675:                 }
22676:             }
22677:             my $cachetime = 24*60*60;
22678:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22679:             if (ref($lastactref) eq 'HASH') {
22680:                 $lastactref->{'domdefaults'} = 1;
22681:             }
22682:             if (keys(%changes) > 0) {
22683:                 my %titles = &ssl_titles();
22684:                 $resulttext = &mt('Changes made:').'<ul>';
22685:                 foreach my $prefix (@prefixes) {
22686:                     if (ref($changes{$prefix}) eq 'HASH') {
22687:                         $resulttext .= '<li>'.$titles{$prefix}.'<ul>';
22688:                         foreach my $type (@{$types{$prefix}}) {
22689:                             if (defined($changes{$prefix}{$type})) {
22690:                                 my ($newvalue,$notinuse);
22691:                                 if (ref($defaultshash{$action}) eq 'HASH') {
22692:                                     if (ref($defaultshash{$action}{$prefix})) {
22693:                                         if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
22694:                                             $newvalue = $titles{$defaultshash{$action}{$prefix}{$type}};
22695:                                         } else {
22696:                                             if (ref($defaultshash{$action}{$prefix}{$type}) eq 'ARRAY') {
22697:                                                 if (@{$defaultshash{$action}{$prefix}{$type}} > 0) {
22698:                                                     $newvalue = join(', ',@{$defaultshash{$action}{$prefix}{$type}});
22699:                                                 }
22700:                                             } else {
22701:                                                 $notinuse = 1;
22702:                                             }
22703:                                         }
22704:                                     }
22705:                                     if ($notinuse) {
22706:                                         $resulttext .= '<li>'.&mt('[_1] set to: not in use',$titles{$type}).'</li>';
22707:                                     } elsif ($newvalue eq '') {
22708:                                         $resulttext .= '<li>'.&mt('[_1] set to: none',$titles{$type}).'</li>';
22709:                                     } else {
22710:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$titles{$type},$newvalue).'</li>';
22711:                                     }
22712:                                 }
22713:                             }
22714:                         }
22715:                         $resulttext .= '</ul>';
22716:                     }
22717:                 }
22718:             } else {
22719:                 $resulttext = $nochgmsg;
22720:             }
22721:         } else {
22722:             $resulttext = '<span class="LC_error">'.
22723:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22724:         }
22725:     } else {
22726:         $resulttext = $nochgmsg;
22727:     }
22728:     return $resulttext;
22729: }
22730: 
22731: sub modify_trust {
22732:     my ($dom,$lastactref,%domconfig) = @_;
22733:     my (%by_ip,%by_location,@intdoms,@instdoms);
22734:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
22735:     my @locations = sort(keys(%by_location));
22736:     my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
22737:     my @types = ('exc','inc');
22738:     my (%defaultshash,%changes);
22739:     foreach my $prefix (@prefixes) {
22740:         $defaultshash{'trust'}{$prefix} = {};
22741:     }
22742:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
22743:     my $resulttext;
22744:     foreach my $prefix (@prefixes) {
22745:         foreach my $type (@types) {
22746:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22747:             my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22748:             my @okvals;
22749:             foreach my $val (@vals) {
22750:                 if ($val =~ /:/) {
22751:                     my @items = split(/:/,$val);
22752:                     foreach my $item (@items) {
22753:                         if (ref($by_location{$item}) eq 'ARRAY') {
22754:                             push(@okvals,$item);
22755:                         }
22756:                     }
22757:                 } else {
22758:                     if (ref($by_location{$val}) eq 'ARRAY') {
22759:                         push(@okvals,$val);
22760:                     }
22761:                 }
22762:             }
22763:             @okvals = sort(@okvals);
22764:             if (ref($domconfig{'trust'}) eq 'HASH') {
22765:                 if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
22766:                     if (ref($domconfig{'trust'}{$prefix}{$type}) eq 'ARRAY') {
22767:                         if ($inuse == 0) {
22768:                             $changes{$prefix}{$type} = 1;
22769:                         } else {
22770:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22771:                             my @changed = &Apache::loncommon::compare_arrays($domconfig{'trust'}{$prefix}{$type},$defaultshash{'trust'}{$prefix}{$type});
22772:                             if (@changed > 0) {
22773:                                 $changes{$prefix}{$type} = 1;
22774:                             }
22775:                         }
22776:                     } else {
22777:                         if ($inuse == 1) {
22778:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22779:                             $changes{$prefix}{$type} = 1;
22780:                         }
22781:                     }
22782:                 } else {
22783:                     if ($inuse == 1) {
22784:                         $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22785:                         $changes{$prefix}{$type} = 1;
22786:                     }
22787:                 }
22788:             } else {
22789:                 if ($inuse == 1) {
22790:                     $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22791:                     $changes{$prefix}{$type} = 1;
22792:                 }
22793:             }
22794:         }
22795:     }
22796:     my $nochgmsg = &mt('No changes made to trust settings.');
22797:     if (keys(%changes) > 0) {
22798:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22799:                                                  $dom);
22800:         if ($putresult eq 'ok') {
22801:             if (ref($defaultshash{'trust'}) eq 'HASH') {
22802:                 foreach my $prefix (@prefixes) {
22803:                     if (ref($defaultshash{'trust'}{$prefix}) eq 'HASH') {
22804:                         $domdefaults{'trust'.$prefix} = $defaultshash{'trust'}{$prefix};
22805:                     }
22806:                 }
22807:             }
22808:             my $cachetime = 24*60*60;
22809:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22810:             &Apache::lonnet::do_cache_new('trust',$dom,$defaultshash{'trust'},3600);
22811:             if (ref($lastactref) eq 'HASH') {
22812:                 $lastactref->{'domdefaults'} = 1;
22813:                 $lastactref->{'trust'} = 1;
22814:             }
22815:             if (keys(%changes) > 0) {
22816:                 my %lt = &trust_titles();
22817:                 $resulttext = &mt('Changes made:').'<ul>';
22818:                 foreach my $prefix (@prefixes) {
22819:                     if (ref($changes{$prefix}) eq 'HASH') {
22820:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
22821:                         foreach my $type (@types) {
22822:                             if (defined($changes{$prefix}{$type})) {
22823:                                 my ($newvalue,$notinuse);
22824:                                 if (ref($defaultshash{'trust'}) eq 'HASH') {
22825:                                     if (ref($defaultshash{'trust'}{$prefix})) {
22826:                                         if (ref($defaultshash{'trust'}{$prefix}{$type}) eq 'ARRAY') {
22827:                                             if (@{$defaultshash{'trust'}{$prefix}{$type}} > 0) {
22828:                                                 $newvalue = join(', ',@{$defaultshash{'trust'}{$prefix}{$type}});
22829:                                             }
22830:                                         } else {
22831:                                             $notinuse = 1;
22832:                                         }
22833:                                     }
22834:                                 }
22835:                                 if ($notinuse) {
22836:                                     $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
22837:                                 } elsif ($newvalue eq '') {
22838:                                     $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
22839:                                 } else {
22840:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
22841:                                 }
22842:                             }
22843:                         }
22844:                         $resulttext .= '</ul>';
22845:                     }
22846:                 }
22847:                 $resulttext .= '</ul>';
22848:             } else {
22849:                 $resulttext = $nochgmsg;
22850:             }
22851:         } else {
22852:             $resulttext = '<span class="LC_error">'.
22853:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22854:         }
22855:     } else {
22856:         $resulttext = $nochgmsg;
22857:     }
22858:     return $resulttext;
22859: }
22860: 
22861: sub modify_loadbalancing {
22862:     my ($dom,%domconfig) = @_;
22863:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
22864:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
22865:     my ($othertitle,$usertypes,$types) =
22866:         &Apache::loncommon::sorted_inst_types($dom);
22867:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22868:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
22869:     my @sparestypes = ('primary','default');
22870:     my %typetitles = &sparestype_titles();
22871:     my $resulttext;
22872:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
22873:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
22874:         %existing = %{$domconfig{'loadbalancing'}};
22875:     }
22876:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
22877:                               \%currtargets,\%currrules,\%currcookies);
22878:     my ($saveloadbalancing,%defaultshash,%changes);
22879:     my ($alltypes,$othertypes,$titles) =
22880:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
22881:     my %ruletitles = &offloadtype_text();
22882:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
22883:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
22884:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
22885:         if ($balancer eq '') {
22886:             next;
22887:         }
22888:         if (!exists($servers{$balancer})) {
22889:             if (exists($currbalancer{$balancer})) {
22890:                 push(@{$changes{'delete'}},$balancer);
22891:             }
22892:             next;
22893:         }
22894:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
22895:             push(@{$changes{'delete'}},$balancer);
22896:             next;
22897:         }
22898:         if (!exists($currbalancer{$balancer})) {
22899:             push(@{$changes{'add'}},$balancer);
22900:         }
22901:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
22902:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
22903:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
22904:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
22905:             $saveloadbalancing = 1;
22906:         }
22907:         foreach my $sparetype (@sparestypes) {
22908:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
22909:             my @offloadto;
22910:             foreach my $target (@targets) {
22911:                 if (($servers{$target}) && ($target ne $balancer)) {
22912:                     if ($sparetype eq 'default') {
22913:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
22914:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
22915:                         }
22916:                     }
22917:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
22918:                         push(@offloadto,$target);
22919:                     }
22920:                 }
22921:             }
22922:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
22923:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
22924:                     push(@offloadto,$balancer);
22925:                 }
22926:             }
22927:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
22928:         }
22929:         if ($env{'form.loadbalancing_cookie_'.$i}) {
22930:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
22931:             if (exists($currbalancer{$balancer})) { 
22932:                 unless ($currcookies{$balancer}) {
22933:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
22934:                 }
22935:             }
22936:         } elsif (exists($currbalancer{$balancer})) {
22937:             if ($currcookies{$balancer}) {
22938:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
22939:             }
22940:         }
22941:         if (ref($currtargets{$balancer}) eq 'HASH') {
22942:             foreach my $sparetype (@sparestypes) {
22943:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
22944:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
22945:                     if (@targetdiffs > 0) {
22946:                         $changes{'curr'}{$balancer}{'targets'} = 1;
22947:                     }
22948:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22949:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
22950:                         $changes{'curr'}{$balancer}{'targets'} = 1;
22951:                     }
22952:                 }
22953:             }
22954:         } else {
22955:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
22956:                 foreach my $sparetype (@sparestypes) {
22957:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22958:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
22959:                             $changes{'curr'}{$balancer}{'targets'} = 1;
22960:                         }
22961:                     }
22962:                 }
22963:             }
22964:         }
22965:         my $ishomedom;
22966:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
22967:             $ishomedom = 1;
22968:         }
22969:         if (ref($alltypes) eq 'ARRAY') {
22970:             foreach my $type (@{$alltypes}) {
22971:                 my $rule;
22972:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
22973:                          (!$ishomedom)) {
22974:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
22975:                 }
22976:                 if ($rule eq 'specific') {
22977:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
22978:                     if (exists($servers{$specifiedhost})) {
22979:                         $rule = $specifiedhost;
22980:                     }
22981:                 }
22982:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
22983:                 if (ref($currrules{$balancer}) eq 'HASH') {
22984:                     if ($rule ne $currrules{$balancer}{$type}) {
22985:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
22986:                     }
22987:                 } elsif ($rule ne '') {
22988:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
22989:                 }
22990:             }
22991:         }
22992:     }
22993:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
22994:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
22995:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
22996:             $defaultshash{'loadbalancing'} = {};
22997:         }
22998:         my $putresult = &Apache::lonnet::put_dom('configuration',
22999:                                                  \%defaultshash,$dom);
23000:         if ($putresult eq 'ok') {
23001:             if (keys(%changes) > 0) {
23002:                 my %toupdate;
23003:                 if (ref($changes{'delete'}) eq 'ARRAY') {
23004:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
23005:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
23006:                         $toupdate{$balancer} = 1;
23007:                     }
23008:                 }
23009:                 if (ref($changes{'add'}) eq 'ARRAY') {
23010:                     foreach my $balancer (sort(@{$changes{'add'}})) {
23011:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
23012:                         $toupdate{$balancer} = 1;
23013:                     }
23014:                 }
23015:                 if (ref($changes{'curr'}) eq 'HASH') {
23016:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
23017:                         $toupdate{$balancer} = 1;
23018:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
23019:                             if ($changes{'curr'}{$balancer}{'targets'}) {
23020:                                 my %offloadstr;
23021:                                 foreach my $sparetype (@sparestypes) {
23022:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
23023:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
23024:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
23025:                                         }
23026:                                     }
23027:                                 }
23028:                                 if (keys(%offloadstr) == 0) {
23029:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
23030:                                 } else {
23031:                                     my $showoffload;
23032:                                     foreach my $sparetype (@sparestypes) {
23033:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
23034:                                         if (defined($offloadstr{$sparetype})) {
23035:                                             $showoffload .= $offloadstr{$sparetype};
23036:                                         } else {
23037:                                             $showoffload .= &mt('None');
23038:                                         }
23039:                                         $showoffload .= ('&nbsp;'x3);
23040:                                     }
23041:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
23042:                                 }
23043:                             }
23044:                         }
23045:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
23046:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
23047:                                 foreach my $type (@{$alltypes}) {
23048:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
23049:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
23050:                                         my $balancetext;
23051:                                         if ($rule eq '') {
23052:                                             $balancetext =  $ruletitles{'default'};
23053:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
23054:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
23055:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
23056:                                                 foreach my $sparetype (@sparestypes) {
23057:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
23058:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
23059:                                                     }
23060:                                                 }
23061:                                                 foreach my $item (@{$alltypes}) {
23062:                                                     next if ($item =~  /^_LC_ipchange/);
23063:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
23064:                                                     if ($hasrule eq 'homeserver') {
23065:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
23066:                                                     } else {
23067:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
23068:                                                             if ($servers{$hasrule}) {
23069:                                                                 $toupdate{$hasrule} = 1;
23070:                                                             }
23071:                                                         }
23072:                                                     }
23073:                                                 }
23074:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
23075:                                                     $balancetext =  $ruletitles{$rule};
23076:                                                 } else {
23077:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
23078:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
23079:                                                     if ($receiver) {
23080:                                                         $toupdate{$receiver};
23081:                                                     }
23082:                                                 }
23083:                                             } else {
23084:                                                 $balancetext =  $ruletitles{$rule};
23085:                                             }
23086:                                         } else {
23087:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
23088:                                         }
23089:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
23090:                                     }
23091:                                 }
23092:                             }
23093:                         }
23094:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
23095:                             if ($currcookies{$balancer}) {
23096:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use disabled',
23097:                                                           $balancer).'</li>';
23098:                             } else {
23099:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
23100:                                                           $balancer).'</li>';
23101:                             }
23102:                         }
23103:                     }
23104:                 }
23105:                 if (keys(%toupdate)) {
23106:                     my %thismachine;
23107:                     my $updatedhere;
23108:                     my $cachetime = 60*60*24;
23109:                     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
23110:                     foreach my $lonhost (keys(%toupdate)) {
23111:                         if ($thismachine{$lonhost}) {
23112:                             unless ($updatedhere) {
23113:                                 &Apache::lonnet::do_cache_new('loadbalancing',$dom,
23114:                                                               $defaultshash{'loadbalancing'},
23115:                                                               $cachetime);
23116:                                 $updatedhere = 1;
23117:                             }
23118:                         } else {
23119:                             my $cachekey = &escape('loadbalancing').':'.&escape($dom);
23120:                             &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
23121:                         }
23122:                     }
23123:                 }
23124:                 if ($resulttext ne '') {
23125:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
23126:                 } else {
23127:                     $resulttext = $nochgmsg;
23128:                 }
23129:             } else {
23130:                 $resulttext = $nochgmsg;
23131:             }
23132:         } else {
23133:             $resulttext = '<span class="LC_error">'.
23134:                           &mt('An error occurred: [_1]',$putresult).'</span>';
23135:         }
23136:     } else {
23137:         $resulttext = $nochgmsg;
23138:     }
23139:     return $resulttext;
23140: }
23141: 
23142: sub recurse_check {
23143:     my ($chkcats,$categories,$depth,$name) = @_;
23144:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
23145:         my $chg = 0;
23146:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
23147:             my $category = $chkcats->[$depth]{$name}[$j];
23148:             my $item;
23149:             if ($category eq '') {
23150:                 $chg ++;
23151:             } else {
23152:                 my $deeper = $depth + 1;
23153:                 $item = &escape($category).':'.&escape($name).':'.$depth;
23154:                 if ($chg) {
23155:                     $categories->{$item} -= $chg;
23156:                 }
23157:                 &recurse_check($chkcats,$categories,$deeper,$category);
23158:                 $deeper --;
23159:             }
23160:         }
23161:     }
23162:     return;
23163: }
23164: 
23165: sub recurse_cat_deletes {
23166:     my ($item,$coursecategories,$deletions) = @_;
23167:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
23168:     my $subdepth = $depth + 1;
23169:     if (ref($coursecategories) eq 'HASH') {
23170:         foreach my $subitem (keys(%{$coursecategories})) {
23171:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
23172:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
23173:                 delete($coursecategories->{$subitem});
23174:                 $deletions->{$subitem} = 1;
23175:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
23176:             }
23177:         }
23178:     }
23179:     return;
23180: }
23181: 
23182: sub active_dc_picker {
23183:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
23184:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
23185:     my @domcoord = keys(%domcoords);
23186:     if (keys(%currhash)) {
23187:         foreach my $dc (keys(%currhash)) {
23188:             unless (exists($domcoords{$dc})) {
23189:                 push(@domcoord,$dc);
23190:             }
23191:         }
23192:     }
23193:     @domcoord = sort(@domcoord);
23194:     my $numdcs = scalar(@domcoord);
23195:     my $rows = 0;
23196:     my $table;
23197:     if ($numdcs > 1) {
23198:         $table = '<table>';
23199:         for (my $i=0; $i<@domcoord; $i++) {
23200:             my $rem = $i%($numinrow);
23201:             if ($rem == 0) {
23202:                 if ($i > 0) {
23203:                     $table .= '</tr>';
23204:                 }
23205:                 $table .= '<tr>';
23206:                 $rows ++;
23207:             }
23208:             my $check = '';
23209:             if ($inputtype eq 'radio') {
23210:                 if (keys(%currhash) == 0) {
23211:                     if (!$i) {
23212:                         $check = ' checked="checked"';
23213:                     }
23214:                 } elsif (exists($currhash{$domcoord[$i]})) {
23215:                     $check = ' checked="checked"';
23216:                 }
23217:             } else {
23218:                 if (exists($currhash{$domcoord[$i]})) {
23219:                     $check = ' checked="checked"';
23220:                 }
23221:             }
23222:             if ($i == @domcoord - 1) {
23223:                 my $colsleft = $numinrow - $rem;
23224:                 if ($colsleft > 1) {
23225:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
23226:                 } else {
23227:                     $table .= '<td class="LC_left_item">';
23228:                 }
23229:             } else {
23230:                 $table .= '<td class="LC_left_item">';
23231:             }
23232:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
23233:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
23234:             $table .= '<span class="LC_nobreak"><label>'.
23235:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
23236:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
23237:             if ($user ne $dcname.':'.$dcdom) {
23238:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
23239:             }
23240:             $table .= '</label></span></td>';
23241:         }
23242:         $table .= '</tr></table>';
23243:     } elsif ($numdcs == 1) {
23244:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
23245:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
23246:         if ($inputtype eq 'radio') {
23247:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
23248:             if ($user ne $dcname.':'.$dcdom) {
23249:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
23250:             }
23251:         } else {
23252:             my $check;
23253:             if (exists($currhash{$domcoord[0]})) {
23254:                 $check = ' checked="checked"';
23255:             }
23256:             $table = '<span class="LC_nobreak"><label>'.
23257:                      '<input type="checkbox" name="'.$name.'" '.
23258:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
23259:             if ($user ne $dcname.':'.$dcdom) {
23260:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
23261:             }
23262:             $table .= '</label></span>';
23263:             $rows ++;
23264:         }
23265:     }
23266:     return ($numdcs,$table,$rows);
23267: }
23268: 
23269: sub usersession_titles {
23270:     return &Apache::lonlocal::texthash(
23271:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
23272:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
23273:                spares => 'Servers offloaded to, when busy',
23274:                version => 'LON-CAPA version requirement',
23275:                excludedomain => 'Allow all, but exclude specific domains',
23276:                includedomain => 'Deny all, but include specific domains',
23277:                primary => 'Primary (checked first)',
23278:                default => 'Default',
23279:            );
23280: }
23281: 
23282: sub id_for_thisdom {
23283:     my (%servers) = @_;
23284:     my %altids;
23285:     foreach my $server (keys(%servers)) {
23286:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
23287:         if ($serverhome ne $server) {
23288:             $altids{$serverhome} = $server;
23289:         }
23290:     }
23291:     return %altids;
23292: }
23293: 
23294: sub count_servers {
23295:     my ($currbalancer,%servers) = @_;
23296:     my (@spares,$numspares);
23297:     foreach my $lonhost (sort(keys(%servers))) {
23298:         next if ($currbalancer eq $lonhost);
23299:         push(@spares,$lonhost);
23300:     }
23301:     if ($currbalancer) {
23302:         $numspares = scalar(@spares);
23303:     } else {
23304:         $numspares = scalar(@spares) - 1;
23305:     }
23306:     return ($numspares,@spares);
23307: }
23308: 
23309: sub lonbalance_targets_js {
23310:     my ($dom,$types,$servers,$settings) = @_;
23311:     my $select = &mt('Select');
23312:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
23313:     if (ref($servers) eq 'HASH') {
23314:         $alltargets = join("','",sort(keys(%{$servers})));
23315:         my @homedoms;
23316:         foreach my $server (sort(keys(%{$servers}))) {
23317:             if (&Apache::lonnet::host_domain($server) eq $dom) {
23318:                 push(@homedoms,'1');
23319:             } else {
23320:                 push(@homedoms,'0');
23321:             }
23322:         }
23323:         $allishome = join("','",@homedoms);
23324:     }
23325:     if (ref($types) eq 'ARRAY') {
23326:         if (@{$types} > 0) {
23327:             @alltypes = @{$types};
23328:         }
23329:     }
23330:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
23331:     $allinsttypes = join("','",@alltypes);
23332:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
23333:     if (ref($settings) eq 'HASH') {
23334:         %existing = %{$settings};
23335:     }
23336:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
23337:                               \%currtargets,\%currrules,\%currcookies);
23338:     my $balancers = join("','",sort(keys(%currbalancer)));
23339:     return <<"END";
23340: 
23341: <script type="text/javascript">
23342: // <![CDATA[
23343: 
23344: currBalancers = new Array('$balancers');
23345: 
23346: function toggleTargets(balnum) {
23347:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
23348:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
23349:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
23350:     var prevbalancer = prevhostitem.value;
23351:     var baltotal = document.getElementById('loadbalancing_total').value;
23352:     prevhostitem.value = balancer;
23353:     if (prevbalancer != '') {
23354:         var prevIdx = currBalancers.indexOf(prevbalancer);
23355:         if (prevIdx != -1) {
23356:             currBalancers.splice(prevIdx,1);
23357:         }
23358:     }
23359:     if (balancer == '') {
23360:         hideSpares(balnum);
23361:     } else {
23362:         var currIdx = currBalancers.indexOf(balancer);
23363:         if (currIdx == -1) {
23364:             currBalancers.push(balancer);
23365:         }
23366:         var homedoms = new Array('$allishome');
23367:         var ishomedom = homedoms[lonhostitem.selectedIndex];
23368:         showSpares(balancer,ishomedom,balnum);
23369:     }
23370:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
23371:     return;
23372: }
23373: 
23374: function showSpares(balancer,ishomedom,balnum) {
23375:     var alltargets = new Array('$alltargets');
23376:     var insttypes = new Array('$allinsttypes');
23377:     var offloadtypes = new Array('primary','default');
23378: 
23379:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
23380:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
23381:  
23382:     for (var i=0; i<offloadtypes.length; i++) {
23383:         var count = 0;
23384:         for (var j=0; j<alltargets.length; j++) {
23385:             if (alltargets[j] != balancer) {
23386:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
23387:                 item.value = alltargets[j];
23388:                 item.style.textAlign='left';
23389:                 item.style.textFace='normal';
23390:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
23391:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
23392:                     item.disabled = '';
23393:                 } else {
23394:                     item.disabled = 'disabled';
23395:                     item.checked = false;
23396:                 }
23397:                 count ++;
23398:             }
23399:         }
23400:     }
23401:     for (var k=0; k<insttypes.length; k++) {
23402:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
23403:             if (ishomedom == 1) {
23404:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
23405:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
23406:             } else {
23407:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
23408:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
23409:             }
23410:         } else {
23411:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
23412:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
23413:         }
23414:         if ((insttypes[k] != '_LC_external') && 
23415:             ((insttypes[k] != '_LC_internetdom') ||
23416:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
23417:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
23418:             item.options.length = 0;
23419:             item.options[0] = new Option("","",true,true);
23420:             var idx = 0;
23421:             for (var m=0; m<alltargets.length; m++) {
23422:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
23423:                     idx ++;
23424:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
23425:                 }
23426:             }
23427:         }
23428:     }
23429:     return;
23430: }
23431: 
23432: function hideSpares(balnum) {
23433:     var alltargets = new Array('$alltargets');
23434:     var insttypes = new Array('$allinsttypes');
23435:     var offloadtypes = new Array('primary','default');
23436: 
23437:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
23438:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
23439: 
23440:     var total = alltargets.length - 1;
23441:     for (var i=0; i<offloadtypes; i++) {
23442:         for (var j=0; j<total; j++) {
23443:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
23444:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
23445:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
23446:         }
23447:     }
23448:     for (var k=0; k<insttypes.length; k++) {
23449:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
23450:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
23451:         if (insttypes[k] != '_LC_external') {
23452:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
23453:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
23454:         }
23455:     }
23456:     return;
23457: }
23458: 
23459: function checkOffloads(item,balnum,type) {
23460:     var alltargets = new Array('$alltargets');
23461:     var offloadtypes = new Array('primary','default');
23462:     if (item.checked) {
23463:         var total = alltargets.length - 1;
23464:         var other;
23465:         if (type == offloadtypes[0]) {
23466:             other = offloadtypes[1];
23467:         } else {
23468:             other = offloadtypes[0];
23469:         }
23470:         for (var i=0; i<total; i++) {
23471:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
23472:             if (server == item.value) {
23473:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
23474:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
23475:                 }
23476:             }
23477:         }
23478:     }
23479:     return;
23480: }
23481: 
23482: function singleServerToggle(balnum,type) {
23483:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
23484:     if (offloadtoSelIdx == 0) {
23485:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
23486:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
23487: 
23488:     } else {
23489:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
23490:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
23491:     }
23492:     return;
23493: }
23494: 
23495: function balanceruleChange(formname,balnum,type) {
23496:     if (type == '_LC_external') {
23497:         return;
23498:     }
23499:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
23500:     for (var i=0; i<typesRules.length; i++) {
23501:         if (formname.elements[typesRules[i]].checked) {
23502:             if (formname.elements[typesRules[i]].value != 'specific') {
23503:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
23504:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
23505:             } else {
23506:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
23507:             }
23508:         }
23509:     }
23510:     return;
23511: }
23512: 
23513: function balancerDeleteChange(balnum) {
23514:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
23515:     var baltotal = document.getElementById('loadbalancing_total').value;
23516:     var addtarget;
23517:     var removetarget;
23518:     var action = 'delete';
23519:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
23520:         var lonhost = hostitem.value;
23521:         var currIdx = currBalancers.indexOf(lonhost);
23522:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
23523:             if (currIdx != -1) {
23524:                 currBalancers.splice(currIdx,1);
23525:             }
23526:             addtarget = lonhost;
23527:         } else {
23528:             if (currIdx == -1) {
23529:                 currBalancers.push(lonhost);
23530:             }
23531:             removetarget = lonhost;
23532:             action = 'undelete';
23533:         }
23534:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
23535:     }
23536:     return;
23537: }
23538: 
23539: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
23540:     if (baltotal > 1) {
23541:         var offloadtypes = new Array('primary','default');
23542:         var alltargets = new Array('$alltargets');
23543:         var insttypes = new Array('$allinsttypes');
23544:         for (var i=0; i<baltotal; i++) {
23545:             if (i != balnum) {
23546:                 for (var j=0; j<offloadtypes.length; j++) {
23547:                     var total = alltargets.length - 1;
23548:                     for (var k=0; k<total; k++) {
23549:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
23550:                         var server = serveritem.value;
23551:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
23552:                             if (server == addtarget) {
23553:                                 serveritem.disabled = '';
23554:                             }
23555:                         }
23556:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
23557:                             if (server == removetarget) {
23558:                                 serveritem.disabled = 'disabled';
23559:                                 serveritem.checked = false;
23560:                             }
23561:                         }
23562:                     }
23563:                 }
23564:                 for (var j=0; j<insttypes.length; j++) {
23565:                     if (insttypes[j] != '_LC_external') {
23566:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
23567:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
23568:                             var currSel = singleserver.selectedIndex;
23569:                             var currVal = singleserver.options[currSel].value;
23570:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
23571:                                 var numoptions = singleserver.options.length;
23572:                                 var needsnew = 1;
23573:                                 for (var k=0; k<numoptions; k++) {
23574:                                     if (singleserver.options[k] == addtarget) {
23575:                                         needsnew = 0;
23576:                                         break;
23577:                                     }
23578:                                 }
23579:                                 if (needsnew == 1) {
23580:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
23581:                                 }
23582:                             }
23583:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
23584:                                 singleserver.options.length = 0;
23585:                                 if ((currVal) && (currVal != removetarget)) {
23586:                                     singleserver.options[0] = new Option("","",false,false);
23587:                                 } else {
23588:                                     singleserver.options[0] = new Option("","",true,true);
23589:                                 }
23590:                                 var idx = 0;
23591:                                 for (var m=0; m<alltargets.length; m++) {
23592:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
23593:                                         idx ++;
23594:                                         if (currVal == alltargets[m]) {
23595:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
23596:                                         } else {
23597:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
23598:                                         }
23599:                                     }
23600:                                 }
23601:                             }
23602:                         }
23603:                     }
23604:                 }
23605:             }
23606:         }
23607:     }
23608:     return;
23609: }
23610: 
23611: // ]]>
23612: </script>
23613: 
23614: END
23615: }
23616: 
23617: 
23618: sub new_spares_js {
23619:     my @sparestypes = ('primary','default');
23620:     my $types = join("','",@sparestypes);
23621:     my $select = &mt('Select');
23622:     return <<"END";
23623: 
23624: <script type="text/javascript">
23625: // <![CDATA[
23626: 
23627: function updateNewSpares(formname,lonhost) {
23628:     var types = new Array('$types');
23629:     var include = new Array();
23630:     var exclude = new Array();
23631:     for (var i=0; i<types.length; i++) {
23632:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
23633:         for (var j=0; j<spareboxes.length; j++) {
23634:             if (formname.elements[spareboxes[j]].checked) {
23635:                 exclude.push(formname.elements[spareboxes[j]].value);
23636:             } else {
23637:                 include.push(formname.elements[spareboxes[j]].value);
23638:             }
23639:         }
23640:     }
23641:     for (var i=0; i<types.length; i++) {
23642:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
23643:         var selIdx = newSpare.selectedIndex;
23644:         var currnew = newSpare.options[selIdx].value;
23645:         var okSpares = new Array();
23646:         for (var j=0; j<newSpare.options.length; j++) {
23647:             var possible = newSpare.options[j].value;
23648:             if (possible != '') {
23649:                 if (exclude.indexOf(possible) == -1) {
23650:                     okSpares.push(possible);
23651:                 } else {
23652:                     if (currnew == possible) {
23653:                         selIdx = 0;
23654:                     }
23655:                 }
23656:             }
23657:         }
23658:         for (var k=0; k<include.length; k++) {
23659:             if (okSpares.indexOf(include[k]) == -1) {
23660:                 okSpares.push(include[k]);
23661:             }
23662:         }
23663:         okSpares.sort();
23664:         newSpare.options.length = 0;
23665:         if (selIdx == 0) {
23666:             newSpare.options[0] = new Option("$select","",true,true);
23667:         } else {
23668:             newSpare.options[0] = new Option("$select","",false,false);
23669:         }
23670:         for (var m=0; m<okSpares.length; m++) {
23671:             var idx = m+1;
23672:             var selThis = 0;
23673:             if (selIdx != 0) {
23674:                 if (okSpares[m] == currnew) {
23675:                     selThis = 1;
23676:                 }
23677:             }
23678:             if (selThis == 1) {
23679:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
23680:             } else {
23681:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
23682:             }
23683:         }
23684:     }
23685:     return;
23686: }
23687: 
23688: function checkNewSpares(lonhost,type) {
23689:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
23690:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
23691:     if (chosen != '') {
23692:         var othertype;
23693:         var othernewSpare;
23694:         if (type == 'primary') {
23695:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
23696:         }
23697:         if (type == 'default') {
23698:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
23699:         }
23700:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
23701:             othernewSpare.selectedIndex = 0;
23702:         }
23703:     }
23704:     return;
23705: }
23706: 
23707: // ]]>
23708: </script>
23709: 
23710: END
23711: 
23712: }
23713: 
23714: sub common_domprefs_js {
23715:     return <<"END";
23716: 
23717: <script type="text/javascript">
23718: // <![CDATA[
23719: 
23720: function getIndicesByName(formname,item) {
23721:     var group = new Array();
23722:     for (var i=0;i<formname.elements.length;i++) {
23723:         if (formname.elements[i].name == item) {
23724:             group.push(formname.elements[i].id);
23725:         }
23726:     }
23727:     return group;
23728: }
23729: 
23730: // ]]>
23731: </script>
23732: 
23733: END
23734: 
23735: }
23736: 
23737: sub recaptcha_js {
23738:     my %lt = &captcha_phrases();
23739:     return <<"END";
23740: 
23741: <script type="text/javascript">
23742: // <![CDATA[
23743: 
23744: function updateCaptcha(caller,context) {
23745:     var privitem;
23746:     var pubitem;
23747:     var privtext;
23748:     var pubtext;
23749:     var versionitem;
23750:     var versiontext;
23751:     if (document.getElementById(context+'_recaptchapub')) {
23752:         pubitem = document.getElementById(context+'_recaptchapub');
23753:     } else {
23754:         return;
23755:     }
23756:     if (document.getElementById(context+'_recaptchapriv')) {
23757:         privitem = document.getElementById(context+'_recaptchapriv');
23758:     } else {
23759:         return;
23760:     }
23761:     if (document.getElementById(context+'_recaptchapubtxt')) {
23762:         pubtext = document.getElementById(context+'_recaptchapubtxt');
23763:     } else {
23764:         return;
23765:     }
23766:     if (document.getElementById(context+'_recaptchaprivtxt')) {
23767:         privtext = document.getElementById(context+'_recaptchaprivtxt');
23768:     } else {
23769:         return;
23770:     }
23771:     if (document.getElementById(context+'_recaptchaversion')) {
23772:         versionitem = document.getElementById(context+'_recaptchaversion');
23773:     } else {
23774:         return;
23775:     }
23776:     if (document.getElementById(context+'_recaptchavertxt')) {
23777:         versiontext = document.getElementById(context+'_recaptchavertxt');
23778:     } else {
23779:         return;
23780:     }
23781:     if (caller.checked) {
23782:         if (caller.value == 'recaptcha') {
23783:             pubitem.type = 'text';
23784:             privitem.type = 'text';
23785:             pubitem.size = '40';
23786:             privitem.size = '40';
23787:             pubtext.innerHTML = "$lt{'pub'}";
23788:             privtext.innerHTML = "$lt{'priv'}";
23789:             versionitem.type = 'text';
23790:             versionitem.size = '3';
23791:             versiontext.innerHTML = "$lt{'ver'}";
23792:         } else {
23793:             pubitem.type = 'hidden';
23794:             privitem.type = 'hidden';
23795:             versionitem.type = 'hidden';
23796:             pubtext.innerHTML = '';
23797:             privtext.innerHTML = '';
23798:             versiontext.innerHTML = '';
23799:         }
23800:     }
23801:     return;
23802: }
23803: 
23804: // ]]>
23805: </script>
23806: 
23807: END
23808: 
23809: }
23810: 
23811: sub toggle_display_js {
23812:     return <<"END";
23813: 
23814: <script type="text/javascript">
23815: // <![CDATA[
23816: 
23817: function toggleDisplay(domForm,caller) {
23818:     if (document.getElementById(caller)) {
23819:         var divitem = document.getElementById(caller);
23820:         var optionsElement = domForm.coursecredits;
23821:         var checkval = 1;
23822:         var dispval = 'block';
23823:         var selfcreateRegExp = /^cancreate_emailverified/;
23824:         if (caller == 'emailoptions') {
23825:             optionsElement = domForm.cancreate_email;
23826:         }
23827:         if (caller == 'studentsubmission') {
23828:             optionsElement = domForm.postsubmit;
23829:         }
23830:         if (caller == 'cloneinstcode') {
23831:             optionsElement = domForm.canclone;
23832:             checkval = 'instcode';
23833:         }
23834:         if (selfcreateRegExp.test(caller)) {
23835:             optionsElement = domForm.elements[caller];
23836:             checkval = 'other';
23837:             dispval = 'inline'
23838:         }
23839:         if (optionsElement.length) {
23840:             var currval;
23841:             for (var i=0; i<optionsElement.length; i++) {
23842:                 if (optionsElement[i].checked) {
23843:                    currval = optionsElement[i].value;
23844:                 }
23845:             }
23846:             if (currval == checkval) {
23847:                 divitem.style.display = dispval;
23848:             } else {
23849:                 divitem.style.display = 'none';
23850:             }
23851:         }
23852:     }
23853:     return;
23854: }
23855: 
23856: // ]]>
23857: </script>
23858: 
23859: END
23860: 
23861: }
23862: 
23863: sub captcha_phrases {
23864:     return &Apache::lonlocal::texthash (
23865:                  priv => 'Private key',
23866:                  pub  => 'Public key',
23867:                  original  => 'original (CAPTCHA)',
23868:                  recaptcha => 'successor (ReCAPTCHA)',
23869:                  notused   => 'unused',
23870:                  ver => 'ReCAPTCHA version (1 or 2)',
23871:     );
23872: }
23873: 
23874: sub devalidate_remote_domconfs {
23875:     my ($dom,$cachekeys) = @_;
23876:     return unless (ref($cachekeys) eq 'HASH');
23877:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
23878:     my %thismachine;
23879:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
23880:     my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
23881:                       'directorysrch','passwdconf','cats','proxyalias','proxysaml',
23882:                       'ipaccess','trust');
23883:     my %cache_by_lonhost;
23884:     if (exists($cachekeys->{'samllanding'})) {
23885:         if (ref($cachekeys->{'samllanding'}) eq 'HASH') {
23886:             my %landing = %{$cachekeys->{'samllanding'}};
23887:             my %domservers = &Apache::lonnet::get_servers($dom);
23888:             if (keys(%domservers)) {
23889:                 foreach my $server (keys(%domservers)) {
23890:                     my @cached;
23891:                     next if ($thismachine{$server});
23892:                     if ($landing{$server}) {
23893:                         push(@cached,&escape('samllanding').':'.&escape($server));
23894:                     }
23895:                     if (@cached) {
23896:                         $cache_by_lonhost{$server} = \@cached;
23897:                     }
23898:                 }
23899:             }
23900:         }
23901:     }
23902:     if (keys(%servers)) {
23903:         foreach my $server (keys(%servers)) {
23904:             next if ($thismachine{$server});
23905:             my @cached;
23906:             foreach my $name (@posscached) {
23907:                 if ($cachekeys->{$name}) {
23908:                     if (($name eq 'proxyalias') || ($name eq 'proxysaml')) {
23909:                         if (ref($cachekeys->{$name}) eq 'HASH') {
23910:                             foreach my $key (keys(%{$cachekeys->{$name}})) {
23911:                                 push(@cached,&escape($name).':'.&escape($key));
23912:                             }
23913:                         }
23914:                     } else {
23915:                         push(@cached,&escape($name).':'.&escape($dom));
23916:                     }
23917:                 }
23918:             }
23919:             if ((exists($cache_by_lonhost{$server})) &&
23920:                 (ref($cache_by_lonhost{$server}) eq 'ARRAY')) {
23921:                 push(@cached,@{$cache_by_lonhost{$server}});
23922:             }
23923:             if (@cached) {
23924:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
23925:             }
23926:         }
23927:     }
23928:     return;
23929: }
23930: 
23931: 1;

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