File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.363: download - view: text, annotated - select for diffs
Thu Jul 18 18:28:52 2019 UTC (4 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754. LON-CAPA as LTI Provider.
  Domain configuration to support session expiration in LON-CAPA,
  after user logs out of LTI Consumer which originally launched session,
  (if Consumer supports logoutServiceUrl; e.g. custom_logout_url in Canvas).

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.363 2019/07/18 18:28:52 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: 
  180: my $registered_cleanup;
  181: my $modified_urls;
  182: 
  183: sub handler {
  184:     my $r=shift;
  185:     if ($r->header_only) {
  186:         &Apache::loncommon::content_type($r,'text/html');
  187:         $r->send_http_header;
  188:         return OK;
  189:     }
  190: 
  191:     my $context = 'domain';
  192:     my $dom = $env{'request.role.domain'};
  193:     my $domdesc = &Apache::lonnet::domain($dom,'description');
  194:     if (&Apache::lonnet::allowed('mau',$dom)) {
  195:         &Apache::loncommon::content_type($r,'text/html');
  196:         $r->send_http_header;
  197:     } else {
  198:         $env{'user.error.msg'}=
  199:         "/adm/domainprefs:mau:0:0:Cannot modify domain settings";
  200:         return HTTP_NOT_ACCEPTABLE;
  201:     }
  202: 
  203:     $registered_cleanup=0;
  204:     @{$modified_urls}=();
  205: 
  206:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  207:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  208:                                             ['phase','actions']);
  209:     my $phase = 'pickactions';
  210:     if ( exists($env{'form.phase'}) ) {
  211:         $phase = $env{'form.phase'};
  212:     }
  213:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
  214:     my %domconfig =
  215:       &Apache::lonnet::get_dom('configuration',['login','rolecolors',
  216:                 'quotas','autoenroll','autoupdate','autocreate',
  217:                 'directorysrch','usercreation','usermodification',
  218:                 'contacts','defaults','scantron','coursecategories',
  219:                 'serverstatuses','requestcourses','helpsettings',
  220:                 'coursedefaults','usersessions','loadbalancing',
  221:                 'requestauthor','selfenrollment','inststatus',
  222:                 'ltitools','ssl','trust','lti','privacy','passwords'],$dom);
  223:     my %encconfig =
  224:         &Apache::lonnet::get_dom('encconfig',['ltitools','lti'],$dom);
  225:     if (ref($domconfig{'ltitools'}) eq 'HASH') {
  226:         if (ref($encconfig{'ltitools'}) eq 'HASH') {
  227:             foreach my $id (keys(%{$domconfig{'ltitools'}})) {
  228:                 if ((ref($domconfig{'ltitools'}{$id}) eq 'HASH') &&
  229:                     (ref($encconfig{'ltitools'}{$id}) eq 'HASH')) {
  230:                     foreach my $item ('key','secret') {
  231:                         $domconfig{'ltitools'}{$id}{$item} = $encconfig{'ltitools'}{$id}{$item};
  232:                     }
  233:                 }
  234:             }
  235:         }
  236:     }
  237:     if (ref($domconfig{'lti'}) eq 'HASH') {
  238:         if (ref($encconfig{'lti'}) eq 'HASH') {
  239:             foreach my $id (keys(%{$domconfig{'lti'}})) {
  240:                 if ((ref($domconfig{'lti'}{$id}) eq 'HASH') &&
  241:                     (ref($encconfig{'lti'}{$id}) eq 'HASH')) {
  242:                     foreach my $item ('key','secret') {
  243:                         $domconfig{'lti'}{$id}{$item} = $encconfig{'lti'}{$id}{$item};
  244:                     }
  245:                 }
  246:             }
  247:         }
  248:     }
  249:     my @prefs_order = ('rolecolors','login','defaults','passwords','quotas','autoenroll',
  250:                        'autoupdate','autocreate','directorysrch','contacts','privacy',
  251:                        'usercreation','selfcreation','usermodification','scantron',
  252:                        'requestcourses','requestauthor','coursecategories',
  253:                        'serverstatuses','helpsettings','coursedefaults',
  254:                        'ltitools','selfenrollment','usersessions','ssl','trust','lti');
  255:     my %existing;
  256:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  257:         %existing = %{$domconfig{'loadbalancing'}};
  258:     }
  259:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  260:         push(@prefs_order,'loadbalancing');
  261:     }
  262:     my %prefs = (
  263:         'rolecolors' =>
  264:                    { text => 'Default color schemes',
  265:                      help => 'Domain_Configuration_Color_Schemes',
  266:                      header => [{col1 => 'Student Settings',
  267:                                  col2 => '',},
  268:                                 {col1 => 'Coordinator Settings',
  269:                                  col2 => '',},
  270:                                 {col1 => 'Author Settings',
  271:                                  col2 => '',},
  272:                                 {col1 => 'Administrator Settings',
  273:                                  col2 => '',}],
  274:                       print => \&print_rolecolors,
  275:                       modify => \&modify_rolecolors,
  276:                     },
  277:         'login' =>
  278:                     { text => 'Log-in page options',
  279:                       help => 'Domain_Configuration_Login_Page',
  280:                       header => [{col1 => 'Log-in Page Items',
  281:                                   col2 => '',},
  282:                                  {col1 => 'Log-in Help',
  283:                                   col2 => 'Value'},
  284:                                  {col1 => 'Custom HTML in document head',
  285:                                   col2 => 'Value'}],
  286:                       print => \&print_login,
  287:                       modify => \&modify_login,
  288:                     },
  289:         'defaults' => 
  290:                     { text => 'Default authentication/language/timezone/portal/types',
  291:                       help => 'Domain_Configuration_LangTZAuth',
  292:                       header => [{col1 => 'Setting',
  293:                                   col2 => 'Value'},
  294:                                  {col1 => 'Institutional user types',
  295:                                   col2 => 'Name displayed'}],
  296:                       print => \&print_defaults,
  297:                       modify => \&modify_defaults,
  298:                     },
  299:         'passwords' =>
  300:                     { text => 'Passwords (Internal authentication)',
  301:                       help => 'Domain_Configuration_Passwords',
  302:                       header => [{col1 => 'Resetting Forgotten Password',
  303:                                   col2 => 'Settings'},
  304:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  305:                                   col2 => 'Settings'},
  306:                                  {col1 => 'Rules for LON-CAPA Passwords',
  307:                                   col2 => 'Settings'},
  308:                                  {col1 => 'Course Owner Changing Student Passwords',
  309:                                   col2 => 'Settings'}],
  310:                       print => \&print_passwords,
  311:                       modify => \&modify_passwords,
  312:                     },
  313:         'quotas' => 
  314:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  315:                       help => 'Domain_Configuration_Quotas',
  316:                       header => [{col1 => 'User affiliation',
  317:                                   col2 => 'Available tools',
  318:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  319:                       print => \&print_quotas,
  320:                       modify => \&modify_quotas,
  321:                     },
  322:         'autoenroll' =>
  323:                    { text => 'Auto-enrollment settings',
  324:                      help => 'Domain_Configuration_Auto_Enrollment',
  325:                      header => [{col1 => 'Configuration setting',
  326:                                  col2 => 'Value(s)'}],
  327:                      print => \&print_autoenroll,
  328:                      modify => \&modify_autoenroll,
  329:                    },
  330:         'autoupdate' => 
  331:                    { text => 'Auto-update settings',
  332:                      help => 'Domain_Configuration_Auto_Updates',
  333:                      header => [{col1 => 'Setting',
  334:                                  col2 => 'Value',},
  335:                                 {col1 => 'Setting',
  336:                                  col2 => 'Affiliation'},
  337:                                 {col1 => 'User population',
  338:                                  col2 => 'Updatable user data'}],
  339:                      print => \&print_autoupdate,
  340:                      modify => \&modify_autoupdate,
  341:                   },
  342:         'autocreate' => 
  343:                   { text => 'Auto-course creation settings',
  344:                      help => 'Domain_Configuration_Auto_Creation',
  345:                      header => [{col1 => 'Configuration Setting',
  346:                                  col2 => 'Value',}],
  347:                      print => \&print_autocreate,
  348:                      modify => \&modify_autocreate,
  349:                   },
  350:         'directorysrch' => 
  351:                   { text => 'Directory searches',
  352:                     help => 'Domain_Configuration_InstDirectory_Search',
  353:                     header => [{col1 => 'Institutional Directory Setting',
  354:                                 col2 => 'Value',},
  355:                                {col1 => 'LON-CAPA Directory Setting',
  356:                                 col2 => 'Value',}],
  357:                     print => \&print_directorysrch,
  358:                     modify => \&modify_directorysrch,
  359:                   },
  360:         'contacts' =>
  361:                   { text => 'E-mail addresses and helpform',
  362:                     help => 'Domain_Configuration_Contact_Info',
  363:                     header => [{col1 => 'Default e-mail addresses',
  364:                                 col2 => 'Value',},
  365:                                {col1 => 'Recipient(s) for notifications',
  366:                                 col2 => 'Value',},
  367:                                {col1 => 'Nightly status check e-mail',
  368:                                 col2 => 'Settings',},
  369:                                {col1 => 'Ask helpdesk form settings',
  370:                                 col2 => 'Value',},],
  371:                     print => \&print_contacts,
  372:                     modify => \&modify_contacts,
  373:                   },
  374:         'usercreation' => 
  375:                   { text => 'User creation',
  376:                     help => 'Domain_Configuration_User_Creation',
  377:                     header => [{col1 => 'Format rule type',
  378:                                 col2 => 'Format rules in force'},
  379:                                {col1 => 'User account creation',
  380:                                 col2 => 'Usernames which may be created',},
  381:                                {col1 => 'Context',
  382:                                 col2 => 'Assignable authentication types'}],
  383:                     print => \&print_usercreation,
  384:                     modify => \&modify_usercreation,
  385:                   },
  386:         'selfcreation' => 
  387:                   { text => 'Users self-creating accounts',
  388:                     help => 'Domain_Configuration_Self_Creation', 
  389:                     header => [{col1 => 'Self-creation with institutional username',
  390:                                 col2 => 'Enabled?'},
  391:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  392:                                 col2 => 'Information user can enter'},
  393:                                {col1 => 'Self-creation with e-mail verification',
  394:                                 col2 => 'Settings'}],
  395:                     print => \&print_selfcreation,
  396:                     modify => \&modify_selfcreation,
  397:                   },
  398:         'usermodification' =>
  399:                   { text => 'User modification',
  400:                     help => 'Domain_Configuration_User_Modification',
  401:                     header => [{col1 => 'Target user has role',
  402:                                 col2 => 'User information updatable in author context'},
  403:                                {col1 => 'Target user has role',
  404:                                 col2 => 'User information updatable in course context'}],
  405:                     print => \&print_usermodification,
  406:                     modify => \&modify_usermodification,
  407:                   },
  408:         'scantron' =>
  409:                   { text => 'Bubblesheet format',
  410:                     help => 'Domain_Configuration_Scantron_Format',
  411:                     header => [ {col1 => 'Bubblesheet format file',
  412:                                  col2 => ''},
  413:                                 {col1 => 'Bubblesheet data upload formats',
  414:                                  col2 => 'Settings'}],
  415:                     print => \&print_scantron,
  416:                     modify => \&modify_scantron,
  417:                   },
  418:         'requestcourses' => 
  419:                  {text => 'Request creation of courses',
  420:                   help => 'Domain_Configuration_Request_Courses',
  421:                   header => [{col1 => 'User affiliation',
  422:                               col2 => 'Availability/Processing of requests',},
  423:                              {col1 => 'Setting',
  424:                               col2 => 'Value'},
  425:                              {col1 => 'Available textbooks',
  426:                               col2 => ''},
  427:                              {col1 => 'Available templates',
  428:                               col2 => ''},
  429:                              {col1 => 'Validation (not official courses)',
  430:                               col2 => 'Value'},],
  431:                   print => \&print_quotas,
  432:                   modify => \&modify_quotas,
  433:                  },
  434:         'requestauthor' =>
  435:                  {text => 'Request Authoring Space',
  436:                   help => 'Domain_Configuration_Request_Author',
  437:                   header => [{col1 => 'User affiliation',
  438:                               col2 => 'Availability/Processing of requests',},
  439:                              {col1 => 'Setting',
  440:                               col2 => 'Value'}],
  441:                   print => \&print_quotas,
  442:                   modify => \&modify_quotas,
  443:                  },
  444:         'coursecategories' =>
  445:                   { text => 'Cataloging of courses/communities',
  446:                     help => 'Domain_Configuration_Cataloging_Courses',
  447:                     header => [{col1 => 'Catalog type/availability',
  448:                                 col2 => '',},
  449:                                {col1 => 'Category settings for standard catalog',
  450:                                 col2 => '',},
  451:                                {col1 => 'Categories',
  452:                                 col2 => '',
  453:                                }],
  454:                     print => \&print_coursecategories,
  455:                     modify => \&modify_coursecategories,
  456:                   },
  457:         'serverstatuses' =>
  458:                  {text   => 'Access to server status pages',
  459:                   help   => 'Domain_Configuration_Server_Status',
  460:                   header => [{col1 => 'Status Page',
  461:                               col2 => 'Other named users',
  462:                               col3 => 'Specific IPs',
  463:                             }],
  464:                   print => \&print_serverstatuses,
  465:                   modify => \&modify_serverstatuses,
  466:                  },
  467:         'helpsettings' =>
  468:                  {text   => 'Support settings',
  469:                   help   => 'Domain_Configuration_Help_Settings',
  470:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  471:                               col2 => 'Value'},
  472:                              {col1 => 'Helpdesk Roles',
  473:                               col2 => 'Settings'},],
  474:                   print  => \&print_helpsettings,
  475:                   modify => \&modify_helpsettings,
  476:                  },
  477:         'coursedefaults' => 
  478:                  {text => 'Course/Community defaults',
  479:                   help => 'Domain_Configuration_Course_Defaults',
  480:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  481:                               col2 => 'Value',},
  482:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  483:                               col2 => 'Value',},],
  484:                   print => \&print_coursedefaults,
  485:                   modify => \&modify_coursedefaults,
  486:                  },
  487:         'selfenrollment' => 
  488:                  {text   => 'Self-enrollment in Course/Community',
  489:                   help   => 'Domain_Configuration_Selfenrollment',
  490:                   header => [{col1 => 'Configuration Rights',
  491:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  492:                              {col1 => 'Defaults',
  493:                               col2 => 'Value'},
  494:                              {col1 => 'Self-enrollment validation (optional)',
  495:                               col2 => 'Value'},],
  496:                   print => \&print_selfenrollment,
  497:                   modify => \&modify_selfenrollment,
  498:                  },
  499:         'privacy' => 
  500:                  {text   => 'Availability of User Information',
  501:                   help   => 'Domain_Configuration_User_Privacy',
  502:                   header => [{col1 => 'Role assigned in different domain',
  503:                               col2 => 'Approval options'},
  504:                              {col1 => 'Role assigned in different domain to user of type',
  505:                               col2 => 'User information available in that domain'},
  506:                              {col1 => "Role assigned in user's domain",
  507:                               col2 => 'Information viewable by privileged user'},
  508:                              {col1 => "Role assigned in user's domain",
  509:                               col2 => 'Information viewable by unprivileged user'}],
  510:                   print => \&print_privacy,
  511:                   modify => \&modify_privacy,
  512:                  },
  513:         'usersessions' =>
  514:                  {text  => 'User session hosting/offloading',
  515:                   help  => 'Domain_Configuration_User_Sessions',
  516:                   header => [{col1 => 'Domain server',
  517:                               col2 => 'Servers to offload sessions to when busy'},
  518:                              {col1 => 'Hosting of users from other domains',
  519:                               col2 => 'Rules'},
  520:                              {col1 => "Hosting domain's own users elsewhere",
  521:                               col2 => 'Rules'}],
  522:                   print => \&print_usersessions,
  523:                   modify => \&modify_usersessions,
  524:                  },
  525:         'loadbalancing' =>
  526:                  {text  => 'Dedicated Load Balancer(s)',
  527:                   help  => 'Domain_Configuration_Load_Balancing',
  528:                   header => [{col1 => 'Balancers',
  529:                               col2 => 'Default destinations',
  530:                               col3 => 'User affiliation',
  531:                               col4 => 'Overrides'},
  532:                             ],
  533:                   print => \&print_loadbalancing,
  534:                   modify => \&modify_loadbalancing,
  535:                  },
  536:         'ltitools' => 
  537:                  {text => 'External Tools (LTI)',
  538:                   help => 'Domain_Configuration_LTI_Tools',
  539:                   header => [{col1 => 'Setting',
  540:                               col2 => 'Value',}],
  541:                   print => \&print_ltitools,
  542:                   modify => \&modify_ltitools,
  543:                  },
  544:         'ssl' =>
  545:                  {text  => 'LON-CAPA Network (SSL)',
  546:                   help  => 'Domain_Configuration_Network_SSL',
  547:                   header => [{col1 => 'Server',
  548:                               col2 => 'Certificate Status'},
  549:                              {col1 => 'Connections to other servers',
  550:                               col2 => 'Rules'},
  551:                              {col1 => 'Connections from other servers',
  552:                               col2 => 'Rules'},
  553:                              {col1 => "Replicating domain's published content",
  554:                               col2 => 'Rules'}],
  555:                   print => \&print_ssl,
  556:                   modify => \&modify_ssl,
  557:                  },
  558:         'trust' =>
  559:                  {text   => 'Trust Settings',
  560:                   help   => 'Domain_Configuration_Trust',
  561:                   header => [{col1 => "Access to this domain's content by others",
  562:                               col2 => 'Rules'},
  563:                              {col1 => "Access to other domain's content by this domain",
  564:                               col2 => 'Rules'},
  565:                              {col1 => "Enrollment in this domain's courses by others",
  566:                               col2 => 'Rules',},
  567:                              {col1 => "Co-author roles in this domain for others",
  568:                               col2 => 'Rules',},
  569:                              {col1 => "Co-author roles for this domain's users elsewhere",
  570:                               col2 => 'Rules',},
  571:                              {col1 => "Domain roles in this domain assignable to others",
  572:                               col2 => 'Rules'},
  573:                              {col1 => "Course catalog for this domain displayed elsewhere",
  574:                               col2 => 'Rules'},
  575:                              {col1 => "Requests for creation of courses in this domain by others",
  576:                               col2 => 'Rules'},
  577:                              {col1 => "Users in other domains can send messages to this domain",
  578:                               col2 => 'Rules'},],
  579:                   print => \&print_trust,
  580:                   modify => \&modify_trust,
  581:                  },
  582:           'lti' =>
  583:                  {text => 'LTI Provider',
  584:                   help => 'Domain_Configuration_LTI_Provider',
  585:                   header => [{col1 => 'Setting',
  586:                               col2 => 'Value',}],
  587:                   print => \&print_lti,
  588:                   modify => \&modify_lti,
  589:                  },
  590:     );
  591:     if (keys(%servers) > 1) {
  592:         $prefs{'login'}  = { text   => 'Log-in page options',
  593:                              help   => 'Domain_Configuration_Login_Page',
  594:                             header => [{col1 => 'Log-in Service',
  595:                                         col2 => 'Server Setting',},
  596:                                        {col1 => 'Log-in Page Items',
  597:                                         col2 => ''},
  598:                                        {col1 => 'Log-in Help',
  599:                                         col2 => 'Value'},
  600:                                        {col1 => 'Custom HTML in document head',
  601:                                         col2 => 'Value'}],
  602:                             print => \&print_login,
  603:                             modify => \&modify_login,
  604:                            };
  605:     }
  606: 
  607:     my @roles = ('student','coordinator','author','admin');
  608:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  609:     &Apache::lonhtmlcommon::add_breadcrumb
  610:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  611:       text=>"Settings to display/modify"});
  612:     my $confname = $dom.'-domainconfig';
  613: 
  614:     if ($phase eq 'process') {
  615:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  616:                                                               \%prefs,\%domconfig,$confname,\@roles);
  617:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  618:             $r->rflush();
  619:             &devalidate_remote_domconfs($dom,$result);
  620:         }
  621:     } elsif ($phase eq 'display') {
  622:         my $js = &recaptcha_js().
  623:                  &toggle_display_js();
  624:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  625:             my ($othertitle,$usertypes,$types) =
  626:                 &Apache::loncommon::sorted_inst_types($dom);
  627:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  628:                                           $domconfig{'loadbalancing'}).
  629:                    &new_spares_js().
  630:                    &common_domprefs_js().
  631:                    &Apache::loncommon::javascript_array_indexof();
  632:         }
  633:         if (grep(/^requestcourses$/,@actions)) {
  634:             my $javascript_validations;
  635:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  636:             $js .= <<END;
  637: <script type="text/javascript">
  638: $javascript_validations
  639: </script>
  640: $coursebrowserjs
  641: END
  642:         }
  643:         if (grep(/^selfcreation$/,@actions)) {
  644:             $js .= &selfcreate_javascript();
  645:         }
  646:         if (grep(/^contacts$/,@actions)) {
  647:             $js .= &contacts_javascript();
  648:         }
  649:         if (grep(/^scantron$/,@actions)) {
  650:             $js .= &scantron_javascript();
  651:         }
  652:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  653:     } else {
  654: # check if domconfig user exists for the domain.
  655:         my $servadm = $r->dir_config('lonAdmEMail');
  656:         my ($configuserok,$author_ok,$switchserver) =
  657:             &config_check($dom,$confname,$servadm);
  658:         unless ($configuserok eq 'ok') {
  659:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  660:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  661:                           $confname).
  662:                       '<br />'
  663:             );
  664:             if ($switchserver) {
  665:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  666:                           '<br />'.
  667:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  668:                           '<br />'.
  669:                           &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).
  670:                           '<br />'.
  671:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  672:                 );
  673:             } else {
  674:                 $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.').
  675:                           '<br />'.
  676:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  677:                 );
  678:             }
  679:             $r->print(&Apache::loncommon::end_page());
  680:             return OK;
  681:         }
  682:         if (keys(%domconfig) == 0) {
  683:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  684:             my @ids=&Apache::lonnet::current_machine_ids();
  685:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  686:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  687:                 my @loginimages = ('img','logo','domlogo','login');
  688:                 my $custom_img_count = 0;
  689:                 foreach my $img (@loginimages) {
  690:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  691:                         $custom_img_count ++;
  692:                     }
  693:                 }
  694:                 foreach my $role (@roles) {
  695:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  696:                         $custom_img_count ++;
  697:                     }
  698:                 }
  699:                 if ($custom_img_count > 0) {
  700:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  701:                     my $switch_server = &check_switchserver($dom,$confname);
  702:                     $r->print(
  703:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  704:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  705:     &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 />'.
  706:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  707:                     if ($switch_server) {
  708:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  709:                     }
  710:                     $r->print(&Apache::loncommon::end_page());
  711:                     return OK;
  712:                 }
  713:             }
  714:         }
  715:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  716:     }
  717:     return OK;
  718: }
  719: 
  720: sub process_changes {
  721:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  722:     my %domconfig;
  723:     if (ref($values) eq 'HASH') {
  724:         %domconfig = %{$values};
  725:     }
  726:     my $output;
  727:     if ($action eq 'login') {
  728:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  729:     } elsif ($action eq 'rolecolors') {
  730:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  731:                                      $lastactref,%domconfig);
  732:     } elsif ($action eq 'quotas') {
  733:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  734:     } elsif ($action eq 'autoenroll') {
  735:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  736:     } elsif ($action eq 'autoupdate') {
  737:         $output = &modify_autoupdate($dom,%domconfig);
  738:     } elsif ($action eq 'autocreate') {
  739:         $output = &modify_autocreate($dom,%domconfig);
  740:     } elsif ($action eq 'directorysrch') {
  741:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  742:     } elsif ($action eq 'usercreation') {
  743:         $output = &modify_usercreation($dom,%domconfig);
  744:     } elsif ($action eq 'selfcreation') {
  745:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  746:     } elsif ($action eq 'usermodification') {
  747:         $output = &modify_usermodification($dom,%domconfig);
  748:     } elsif ($action eq 'contacts') {
  749:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  750:     } elsif ($action eq 'defaults') {
  751:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  752:     } elsif ($action eq 'scantron') {
  753:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  754:     } elsif ($action eq 'coursecategories') {
  755:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  756:     } elsif ($action eq 'serverstatuses') {
  757:         $output = &modify_serverstatuses($dom,%domconfig);
  758:     } elsif ($action eq 'requestcourses') {
  759:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  760:     } elsif ($action eq 'requestauthor') {
  761:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  762:     } elsif ($action eq 'helpsettings') {
  763:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  764:     } elsif ($action eq 'coursedefaults') {
  765:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  766:     } elsif ($action eq 'selfenrollment') {
  767:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  768:     } elsif ($action eq 'usersessions') {
  769:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  770:     } elsif ($action eq 'loadbalancing') {
  771:         $output = &modify_loadbalancing($dom,%domconfig);
  772:     } elsif ($action eq 'ltitools') {
  773:         $output = &modify_ltitools($r,$dom,$action,$lastactref,%domconfig);
  774:     } elsif ($action eq 'ssl') {
  775:         $output = &modify_ssl($dom,$lastactref,%domconfig);
  776:     } elsif ($action eq 'trust') {
  777:         $output = &modify_trust($dom,$lastactref,%domconfig);
  778:     } elsif ($action eq 'lti') {
  779:         $output = &modify_lti($r,$dom,$action,$lastactref,%domconfig);
  780:     } elsif ($action eq 'privacy') {
  781:         $output = &modify_privacy($dom,%domconfig);
  782:     } elsif ($action eq 'passwords') {
  783:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  784:     }
  785:     return $output;
  786: }
  787: 
  788: sub print_config_box {
  789:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  790:     my $rowtotal = 0;
  791:     my $output;
  792:     if ($action eq 'coursecategories') {
  793:         $output = &coursecategories_javascript($settings);
  794:     } elsif ($action eq 'defaults') {
  795:         $output = &defaults_javascript($settings); 
  796:     } elsif ($action eq 'passwords') {
  797:         $output = &passwords_javascript();
  798:     } elsif ($action eq 'helpsettings') {
  799:         my (%privs,%levelscurrent);
  800:         my %full=();
  801:         my %levels=(
  802:                      course => {},
  803:                      domain => {},
  804:                      system => {},
  805:                    );
  806:         my $context = 'domain';
  807:         my $crstype = 'Course';
  808:         my $formname = 'display';
  809:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  810:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  811:         $output =
  812:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full, 
  813:                                                       \@templateroles);
  814:     } elsif ($action eq 'ltitools') {
  815:         $output .= &ltitools_javascript($settings);
  816:     } elsif ($action eq 'lti') {
  817:         $output .= &lti_javascript($settings);
  818:     }
  819:     $output .=
  820:          '<table class="LC_nested_outer">
  821:           <tr>
  822:            <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
  823:            &mt($item->{text}).'&nbsp;'.
  824:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  825:           '</tr>';
  826:     $rowtotal ++;
  827:     my $numheaders = 1;
  828:     if (ref($item->{'header'}) eq 'ARRAY') {
  829:         $numheaders = scalar(@{$item->{'header'}});
  830:     }
  831:     if ($numheaders > 1) {
  832:         my $colspan = '';
  833:         my $rightcolspan = '';
  834:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  835:             ($action eq 'directorysrch') ||
  836:             (($action eq 'login') && ($numheaders < 4))) {
  837:             $colspan = ' colspan="2"';
  838:         }
  839:         if ($action eq 'usersessions') {
  840:             $rightcolspan = ' colspan="3"'; 
  841:         }
  842:         $output .= '
  843:           <tr>
  844:            <td>
  845:             <table class="LC_nested">
  846:              <tr class="LC_info_row">
  847:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  848:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  849:              </tr>';
  850:         $rowtotal ++;
  851:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  852:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  853:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'ssl') ||
  854:             ($action eq 'directorysrch') || ($action eq 'trust') || ($action eq 'helpsettings') ||
  855:             ($action eq 'contacts') || ($action eq 'privacy')) {
  856:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  857:         } elsif ($action eq 'passwords') {
  858:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  859:         } elsif ($action eq 'coursecategories') {
  860:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  861:         } elsif ($action eq 'scantron') {
  862:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  863:         } elsif ($action eq 'login') {
  864:             if ($numheaders == 4) {
  865:                 $colspan = ' colspan="2"';
  866:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  867:             } else {
  868:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  869:             }
  870:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  871:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  872:         } elsif ($action eq 'rolecolors') {
  873:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  874:         }
  875:         $output .= '
  876:            </table>
  877:           </td>
  878:          </tr>
  879:          <tr>
  880:            <td>
  881:             <table class="LC_nested">
  882:              <tr class="LC_info_row">
  883:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  884:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  885:              </tr>';
  886:             $rowtotal ++;
  887:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  888:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  889:             ($action eq 'usersessions') || ($action eq 'coursecategories') || 
  890:             ($action eq 'trust') || ($action eq 'contacts') ||
  891:             ($action eq 'privacy') || ($action eq 'passwords')) {
  892:             if ($action eq 'coursecategories') {
  893:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  894:                 $colspan = ' colspan="2"';
  895:             } elsif ($action eq 'trust') {
  896:                 $output .= $item->{'print'}->('shared',$dom,$settings,\$rowtotal);
  897:             } elsif ($action eq 'passwords') {
  898:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
  899:             } else {
  900:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  901:             }
  902:             if ($action eq 'trust') {
  903:                 $output .= '
  904:             </table>
  905:           </td>
  906:          </tr>';
  907:                 my @trusthdrs = qw(2 3 4 5 6 7);
  908:                 my @prefixes = qw(enroll othcoau coaurem domroles catalog reqcrs);
  909:                 for (my $i=0; $i<@trusthdrs; $i++) {
  910:                     $output .= '
  911:          <tr>
  912:            <td>
  913:             <table class="LC_nested">
  914:              <tr class="LC_info_row">
  915:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col1'}).'</td>
  916:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col2'}).'</td></tr>'.
  917:                            $item->{'print'}->($prefixes[$i],$dom,$settings,\$rowtotal).'
  918:             </table>
  919:           </td>
  920:          </tr>';
  921:                 }
  922:                 $output .= '
  923:          <tr>
  924:            <td>
  925:             <table class="LC_nested">
  926:              <tr class="LC_info_row">
  927:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col1'}).'</td>
  928:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col2'}).'</td></tr>'.
  929:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  930:             } else {
  931:                 $output .= '
  932:            </table>
  933:           </td>
  934:          </tr>
  935:          <tr>
  936:            <td>
  937:             <table class="LC_nested">
  938:              <tr class="LC_info_row">
  939:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  940:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  941:              </tr>'."\n";
  942:                 if ($action eq 'coursecategories') {
  943:                     $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
  944:                 } elsif (($action eq 'contacts') || ($action eq 'privacy') || ($action eq 'passwords')) {
  945:                     if ($action eq 'passwords') {
  946:                         $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal);
  947:                     } else {
  948:                         $output .= $item->{'print'}->('lower',$dom,$settings,\$rowtotal);
  949:                     }
  950:                     $output .= '
  951:              </tr>
  952:             </table>
  953:            </td>
  954:           </tr>
  955:           <tr>
  956:            <td>
  957:             <table class="LC_nested">
  958:              <tr class="LC_info_row">
  959:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  960:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
  961:                     if ($action eq 'passwords') {
  962:                         $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
  963:                     } else {
  964:                         $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  965:                     }
  966:                     $output .= '
  967:             </table>
  968:           </td>
  969:          </tr>
  970:          <tr>';
  971:                 } else {
  972:                     $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  973:                 }
  974:             }
  975:             $rowtotal ++;
  976:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
  977:                  ($action eq 'defaults') || ($action eq 'directorysrch') ||
  978:                  ($action eq 'helpsettings')) {
  979:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  980:         } elsif ($action eq 'scantron') {
  981:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
  982:         } elsif ($action eq 'ssl') {
  983:             $output .= $item->{'print'}->('connto',$dom,$settings,\$rowtotal).'
  984:             </table>
  985:           </td>
  986:          </tr>
  987:          <tr>
  988:            <td>
  989:             <table class="LC_nested">
  990:              <tr class="LC_info_row">
  991:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  992:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
  993:                            $item->{'print'}->('connfrom',$dom,$settings,\$rowtotal).'
  994:             </table>
  995:           </td>
  996:          </tr>
  997:          <tr>
  998:            <td>
  999:             <table class="LC_nested">
 1000:              <tr class="LC_info_row">
 1001:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1002:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'.
 1003:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1004:         } elsif ($action eq 'login') {
 1005:             if ($numheaders == 4) {
 1006:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
 1007:            </table>
 1008:           </td>
 1009:          </tr>
 1010:          <tr>
 1011:            <td>
 1012:             <table class="LC_nested">
 1013:              <tr class="LC_info_row">
 1014:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1015:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1016:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1017:                 $rowtotal ++;
 1018:             } else {
 1019:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1020:             }
 1021:             $output .= '
 1022:            </table>
 1023:           </td>
 1024:          </tr>
 1025:          <tr>
 1026:            <td>
 1027:             <table class="LC_nested">
 1028:              <tr class="LC_info_row">';
 1029:             if ($numheaders == 4) {
 1030:                 $output .= '
 1031:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1032:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1033:              </tr>';
 1034:             } else {
 1035:                 $output .= '
 1036:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1037:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1038:              </tr>';
 1039:             }
 1040:             $rowtotal ++;
 1041:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal);
 1042:         } elsif ($action eq 'requestcourses') {
 1043:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1044:             $rowtotal ++;
 1045:             $output .= &print_studentcode($settings,\$rowtotal).'
 1046:            </table>
 1047:           </td>
 1048:          </tr>
 1049:          <tr>
 1050:            <td>
 1051:             <table class="LC_nested">
 1052:              <tr class="LC_info_row">
 1053:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1054:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
 1055:                        &textbookcourses_javascript($settings).
 1056:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
 1057:             </table>
 1058:            </td>
 1059:           </tr>
 1060:          <tr>
 1061:            <td>
 1062:             <table class="LC_nested">
 1063:              <tr class="LC_info_row">
 1064:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1065:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
 1066:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
 1067:             </table>
 1068:            </td>
 1069:           </tr>
 1070:           <tr>
 1071:            <td>
 1072:             <table class="LC_nested">
 1073:              <tr class="LC_info_row">
 1074:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1075:               <td class="LC_right_item" style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1076:              </tr>'.
 1077:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
 1078:         } elsif ($action eq 'requestauthor') {
 1079:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1080:             $rowtotal ++;
 1081:         } elsif ($action eq 'rolecolors') {
 1082:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$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.' style="vertical-align: top">'.
 1091:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
 1092:               <td class="LC_right_item" style="vertical-align: top">'.
 1093:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
 1094:              </tr>'.
 1095:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
 1096:            </table>
 1097:           </td>
 1098:          </tr>
 1099:          <tr>
 1100:            <td>
 1101:             <table class="LC_nested">
 1102:              <tr class="LC_info_row">
 1103:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1104:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1105:              </tr>'.
 1106:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
 1107:             $rowtotal += 2;
 1108:         }
 1109:     } else {
 1110:         $output .= '
 1111:           <tr>
 1112:            <td>
 1113:             <table class="LC_nested">
 1114:              <tr class="LC_info_row">';
 1115:         if ($action eq 'login') {
 1116:             $output .= '  
 1117:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1118:         } elsif ($action eq 'serverstatuses') {
 1119:             $output .= '
 1120:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).
 1121:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
 1122: 
 1123:         } else {
 1124:             $output .= '
 1125:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1126:         }
 1127:         if (defined($item->{'header'}->[0]->{'col3'})) {
 1128:             $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1129:                        &mt($item->{'header'}->[0]->{'col2'});
 1130:             if ($action eq 'serverstatuses') {
 1131:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
 1132:             } 
 1133:         } else {
 1134:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1135:                        &mt($item->{'header'}->[0]->{'col2'});
 1136:         }
 1137:         $output .= '</td>';
 1138:         if ($item->{'header'}->[0]->{'col3'}) {
 1139:             if (defined($item->{'header'}->[0]->{'col4'})) {
 1140:                 $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1141:                             &mt($item->{'header'}->[0]->{'col3'});
 1142:             } else {
 1143:                 $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1144:                            &mt($item->{'header'}->[0]->{'col3'});
 1145:             }
 1146:             if ($action eq 'serverstatuses') {
 1147:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
 1148:             }
 1149:             $output .= '</td>';
 1150:         }
 1151:         if ($item->{'header'}->[0]->{'col4'}) {
 1152:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1153:                        &mt($item->{'header'}->[0]->{'col4'});
 1154:         }
 1155:         $output .= '</tr>';
 1156:         $rowtotal ++;
 1157:         if ($action eq 'quotas') {
 1158:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
 1159:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
 1160:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') || 
 1161:                  ($action eq 'ltitools') || ($action eq 'lti')) {
 1162:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
 1163:         }
 1164:     }
 1165:     $output .= '
 1166:    </table>
 1167:   </td>
 1168:  </tr>
 1169: </table><br />';
 1170:     return ($output,$rowtotal);
 1171: }
 1172: 
 1173: sub print_login {
 1174:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
 1175:     my ($css_class,$datatable);
 1176:     my %choices = &login_choices();
 1177: 
 1178:     if ($caller eq 'service') {
 1179:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1180:         my $choice = $choices{'disallowlogin'};
 1181:         $css_class = ' class="LC_odd_row"';
 1182:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1183:                       '<td style="text-align: right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1184:                       '<th>'.$choices{'server'}.'</th>'.
 1185:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1186:                       '<th>'.$choices{'custompath'}.'</th>'.
 1187:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1188:         my %disallowed;
 1189:         if (ref($settings) eq 'HASH') {
 1190:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1191:                %disallowed = %{$settings->{'loginvia'}};
 1192:             }
 1193:         }
 1194:         foreach my $lonhost (sort(keys(%servers))) {
 1195:             my $direct = 'selected="selected"';
 1196:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1197:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1198:                     $direct = '';
 1199:                 }
 1200:             }
 1201:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1202:                           '<td><select name="'.$lonhost.'_server">'.
 1203:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1204:                           '</option>';
 1205:             foreach my $hostid (sort(keys(%servers))) {
 1206:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1207:                 my $selected = '';
 1208:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1209:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1210:                         $selected = 'selected="selected"';
 1211:                     }
 1212:                 }
 1213:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1214:                               $servers{$hostid}.'</option>';
 1215:             }
 1216:             $datatable .= '</select></td>'.
 1217:                           '<td><select name="'.$lonhost.'_serverpath">';
 1218:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1219:                 my $pathname = $path;
 1220:                 if ($path eq 'custom') {
 1221:                     $pathname = &mt('Custom Path').' ->';
 1222:                 }
 1223:                 my $selected = '';
 1224:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1225:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1226:                         $selected = 'selected="selected"';
 1227:                     }
 1228:                 } elsif ($path eq '') {
 1229:                     $selected = 'selected="selected"';
 1230:                 }
 1231:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1232:             }
 1233:             $datatable .= '</select></td>';
 1234:             my ($custom,$exempt);
 1235:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1236:                 $custom = $disallowed{$lonhost}{'custompath'};
 1237:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1238:             }
 1239:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1240:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1241:                           '</tr>';
 1242:         }
 1243:         $datatable .= '</table></td></tr>';
 1244:         return $datatable;
 1245:     } elsif ($caller eq 'page') {
 1246:         my %defaultchecked = ( 
 1247:                                'coursecatalog' => 'on',
 1248:                                'helpdesk'      => 'on',
 1249:                                'adminmail'     => 'off',
 1250:                                'newuser'       => 'off',
 1251:                              );
 1252:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1253:         my (%checkedon,%checkedoff);
 1254:         foreach my $item (@toggles) {
 1255:             if ($defaultchecked{$item} eq 'on') { 
 1256:                 $checkedon{$item} = ' checked="checked" ';
 1257:                 $checkedoff{$item} = ' ';
 1258:             } elsif ($defaultchecked{$item} eq 'off') {
 1259:                 $checkedoff{$item} = ' checked="checked" ';
 1260:                 $checkedon{$item} = ' ';
 1261:             }
 1262:         }
 1263:         my @images = ('img','logo','domlogo','login');
 1264:         my @logintext = ('textcol','bgcol');
 1265:         my @bgs = ('pgbg','mainbg','sidebg');
 1266:         my @links = ('link','alink','vlink');
 1267:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1268:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1269:         my (%is_custom,%designs);
 1270:         my %defaults = (
 1271:                        font => $defaultdesign{'login.font'},
 1272:                        );
 1273:         foreach my $item (@images) {
 1274:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1275:             $defaults{'showlogo'}{$item} = 1;
 1276:         }
 1277:         foreach my $item (@bgs) {
 1278:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1279:         }
 1280:         foreach my $item (@logintext) {
 1281:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1282:         }
 1283:         foreach my $item (@links) {
 1284:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1285:         }
 1286:         if (ref($settings) eq 'HASH') {
 1287:             foreach my $item (@toggles) {
 1288:                 if ($settings->{$item} eq '1') {
 1289:                     $checkedon{$item} =  ' checked="checked" ';
 1290:                     $checkedoff{$item} = ' ';
 1291:                 } elsif ($settings->{$item} eq '0') {
 1292:                     $checkedoff{$item} =  ' checked="checked" ';
 1293:                     $checkedon{$item} = ' ';
 1294:                 }
 1295:             }
 1296:             foreach my $item (@images) {
 1297:                 if (defined($settings->{$item})) {
 1298:                     $designs{$item} = $settings->{$item};
 1299:                     $is_custom{$item} = 1;
 1300:                 }
 1301:                 if (defined($settings->{'showlogo'}{$item})) {
 1302:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1303:                 }
 1304:             }
 1305:             foreach my $item (@logintext) {
 1306:                 if ($settings->{$item} ne '') {
 1307:                     $designs{'logintext'}{$item} = $settings->{$item};
 1308:                     $is_custom{$item} = 1;
 1309:                 }
 1310:             }
 1311:             if ($settings->{'font'} ne '') {
 1312:                 $designs{'font'} = $settings->{'font'};
 1313:                 $is_custom{'font'} = 1;
 1314:             }
 1315:             foreach my $item (@bgs) {
 1316:                 if ($settings->{$item} ne '') {
 1317:                     $designs{'bgs'}{$item} = $settings->{$item};
 1318:                     $is_custom{$item} = 1;
 1319:                 }
 1320:             }
 1321:             foreach my $item (@links) {
 1322:                 if ($settings->{$item} ne '') {
 1323:                     $designs{'links'}{$item} = $settings->{$item};
 1324:                     $is_custom{$item} = 1;
 1325:                 }
 1326:             }
 1327:         } else {
 1328:             if ($designhash{$dom.'.login.font'} ne '') {
 1329:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1330:                 $is_custom{'font'} = 1;
 1331:             }
 1332:             foreach my $item (@images) {
 1333:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1334:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1335:                     $is_custom{$item} = 1;
 1336:                 }
 1337:             }
 1338:             foreach my $item (@bgs) {
 1339:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1340:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1341:                     $is_custom{$item} = 1;
 1342:                 }
 1343:             }
 1344:             foreach my $item (@links) {
 1345:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1346:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1347:                     $is_custom{$item} = 1;
 1348:                 }
 1349:             }
 1350:         }
 1351:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1352:                                                       logo => 'Institution Logo',
 1353:                                                       domlogo => 'Domain Logo',
 1354:                                                       login => 'Login box');
 1355:         my $itemcount = 1;
 1356:         foreach my $item (@toggles) {
 1357:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1358:             $datatable .=  
 1359:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1360:                 '</td><td>'.
 1361:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1362:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1363:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1364:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1365:                 '</tr>';
 1366:             $itemcount ++;
 1367:         }
 1368:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1369:         $datatable .= '</tr></table></td></tr>';
 1370:     } elsif ($caller eq 'help') {
 1371:         my ($defaulturl,$defaulttype,%url,%type,%lt,%langchoices);
 1372:         my $switchserver = &check_switchserver($dom,$confname);
 1373:         my $itemcount = 1;
 1374:         $defaulturl = '/adm/loginproblems.html';
 1375:         $defaulttype = 'default';
 1376:         %lt = &Apache::lonlocal::texthash (
 1377:                      del     => 'Delete?',
 1378:                      rep     => 'Replace:',
 1379:                      upl     => 'Upload:',
 1380:                      default => 'Default',
 1381:                      custom  => 'Custom',
 1382:                                              );
 1383:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1384:         my @currlangs;
 1385:         if (ref($settings) eq 'HASH') {
 1386:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1387:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1388:                     next if ($settings->{'helpurl'}{$key} eq '');
 1389:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1390:                     $type{$key} = 'custom';
 1391:                     unless ($key eq 'nolang') {
 1392:                         push(@currlangs,$key);
 1393:                     }
 1394:                 }
 1395:             } elsif ($settings->{'helpurl'} ne '') {
 1396:                 $type{'nolang'} = 'custom';
 1397:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1398:             }
 1399:         }
 1400:         foreach my $lang ('nolang',sort(@currlangs)) {
 1401:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1402:             $datatable .= '<tr'.$css_class.'>';
 1403:             if ($url{$lang} eq '') {
 1404:                 $url{$lang} = $defaulturl;
 1405:             }
 1406:             if ($type{$lang} eq '') {
 1407:                 $type{$lang} = $defaulttype;
 1408:             }
 1409:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1410:             if ($lang eq 'nolang') {
 1411:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1412:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1413:             } else {
 1414:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1415:                                   $langchoices{$lang},
 1416:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1417:             }
 1418:             $datatable .= '</span></td>'."\n".
 1419:                           '<td class="LC_left_item">';
 1420:             if ($type{$lang} eq 'custom') {
 1421:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1422:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1423:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1424:             } else {
 1425:                 $datatable .= $lt{'upl'};
 1426:             }
 1427:             $datatable .='<br />';
 1428:             if ($switchserver) {
 1429:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1430:             } else {
 1431:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1432:             }
 1433:             $datatable .= '</td></tr>';
 1434:             $itemcount ++;
 1435:         }
 1436:         my @addlangs;
 1437:         foreach my $lang (sort(keys(%langchoices))) {
 1438:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1439:             push(@addlangs,$lang);
 1440:         }
 1441:         if (@addlangs > 0) {
 1442:             my %toadd;
 1443:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1444:             $toadd{''} = &mt('Select');
 1445:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1446:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1447:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1448:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1449:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1450:             if ($switchserver) {
 1451:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1452:             } else {
 1453:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1454:             }
 1455:             $datatable .= '</td></tr>';
 1456:             $itemcount ++;
 1457:         }
 1458:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1459:     } elsif ($caller eq 'headtag') {
 1460:         my %domservers = &Apache::lonnet::get_servers($dom);
 1461:         my $choice = $choices{'headtag'};
 1462:         $css_class = ' class="LC_odd_row"';
 1463:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1464:                       '<td style="text-align: left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1465:                       '<th>'.$choices{'current'}.'</th>'.
 1466:                       '<th>'.$choices{'action'}.'</th>'.
 1467:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1468:         my (%currurls,%currexempt);
 1469:         if (ref($settings) eq 'HASH') {
 1470:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1471:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1472:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1473:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1474:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1475:                     }
 1476:                 }
 1477:             }
 1478:         }
 1479:         my %lt = &Apache::lonlocal::texthash(
 1480:                                                del  => 'Delete?',
 1481:                                                rep  => 'Replace:',
 1482:                                                upl  => 'Upload:',
 1483:                                                curr => 'View contents',
 1484:                                                none => 'None',
 1485:         );
 1486:         my $switchserver = &check_switchserver($dom,$confname);
 1487:         foreach my $lonhost (sort(keys(%domservers))) {
 1488:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1489:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1490:             if ($currurls{$lonhost}) {
 1491:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1492:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1493:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1494:                               '">'.$lt{'curr'}.'</a></td>'.
 1495:                               '<td><span class="LC_nobreak"><label>'.
 1496:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1497:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1498:             } else {
 1499:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1500:             }
 1501:             $datatable .='<br />';
 1502:             if ($switchserver) {
 1503:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1504:             } else {
 1505:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1506:             }
 1507:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1508:         }
 1509:         $datatable .= '</table></td></tr>';
 1510:     }
 1511:     return $datatable;
 1512: }
 1513: 
 1514: sub login_choices {
 1515:     my %choices =
 1516:         &Apache::lonlocal::texthash (
 1517:             coursecatalog => 'Display Course/Community Catalog link?',
 1518:             adminmail     => "Display Administrator's E-mail Address?",
 1519:             helpdesk      => 'Display "Contact Helpdesk" link',
 1520:             disallowlogin => "Login page requests redirected",
 1521:             hostid        => "Server",
 1522:             server        => "Redirect to:",
 1523:             serverpath    => "Path",
 1524:             custompath    => "Custom", 
 1525:             exempt        => "Exempt IP(s)",
 1526:             directlogin   => "No redirect",
 1527:             newuser       => "Link to create a user account",
 1528:             img           => "Header",
 1529:             logo          => "Main Logo",
 1530:             domlogo       => "Domain Logo",
 1531:             login         => "Log-in Header", 
 1532:             textcol       => "Text color",
 1533:             bgcol         => "Box color",
 1534:             bgs           => "Background colors",
 1535:             links         => "Link colors",
 1536:             font          => "Font color",
 1537:             pgbg          => "Header",
 1538:             mainbg        => "Page",
 1539:             sidebg        => "Login box",
 1540:             link          => "Link",
 1541:             alink         => "Active link",
 1542:             vlink         => "Visited link",
 1543:             headtag       => "Custom markup",
 1544:             action        => "Action",
 1545:             current       => "Current",
 1546:         );
 1547:     return %choices;
 1548: }
 1549: 
 1550: sub print_rolecolors {
 1551:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1552:     my %choices = &color_font_choices();
 1553:     my @bgs = ('pgbg','tabbg','sidebg');
 1554:     my @links = ('link','alink','vlink');
 1555:     my @images = ('img');
 1556:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1557:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1558:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1559:     my (%is_custom,%designs);
 1560:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1561:     if (ref($settings) eq 'HASH') {
 1562:         if (ref($settings->{$role}) eq 'HASH') {
 1563:             if ($settings->{$role}->{'img'} ne '') {
 1564:                 $designs{'img'} = $settings->{$role}->{'img'};
 1565:                 $is_custom{'img'} = 1;
 1566:             }
 1567:             if ($settings->{$role}->{'font'} ne '') {
 1568:                 $designs{'font'} = $settings->{$role}->{'font'};
 1569:                 $is_custom{'font'} = 1;
 1570:             }
 1571:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1572:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1573:                 $is_custom{'fontmenu'} = 1;
 1574:             }
 1575:             foreach my $item (@bgs) {
 1576:                 if ($settings->{$role}->{$item} ne '') {
 1577:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1578:                     $is_custom{$item} = 1;
 1579:                 }
 1580:             }
 1581:             foreach my $item (@links) {
 1582:                 if ($settings->{$role}->{$item} ne '') {
 1583:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1584:                     $is_custom{$item} = 1;
 1585:                 }
 1586:             }
 1587:         }
 1588:     } else {
 1589:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1590:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1591:             $is_custom{'img'} = 1;
 1592:         }
 1593:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1594:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1595:             $is_custom{'fontmenu'} = 1; 
 1596:         }
 1597:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1598:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1599:             $is_custom{'font'} = 1;
 1600:         }
 1601:         foreach my $item (@bgs) {
 1602:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1603:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1604:                 $is_custom{$item} = 1;
 1605:             
 1606:             }
 1607:         }
 1608:         foreach my $item (@links) {
 1609:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1610:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1611:                 $is_custom{$item} = 1;
 1612:             }
 1613:         }
 1614:     }
 1615:     my $itemcount = 1;
 1616:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 1617:     $datatable .= '</tr></table></td></tr>';
 1618:     return $datatable;
 1619: }
 1620: 
 1621: sub role_defaults {
 1622:     my ($role,$bgs,$links,$images,$logintext) = @_;
 1623:     my %defaults;
 1624:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 1625:         return %defaults;
 1626:     }
 1627:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1628:     if ($role eq 'login') {
 1629:         %defaults = (
 1630:                        font => $defaultdesign{$role.'.font'},
 1631:                     );
 1632:         if (ref($logintext) eq 'ARRAY') {
 1633:             foreach my $item (@{$logintext}) {
 1634:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 1635:             }
 1636:         }
 1637:         foreach my $item (@{$images}) {
 1638:             $defaults{'showlogo'}{$item} = 1;
 1639:         }
 1640:     } else {
 1641:         %defaults = (
 1642:                        img => $defaultdesign{$role.'.img'},
 1643:                        font => $defaultdesign{$role.'.font'},
 1644:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 1645:                     );
 1646:     }
 1647:     foreach my $item (@{$bgs}) {
 1648:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 1649:     }
 1650:     foreach my $item (@{$links}) {
 1651:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 1652:     }
 1653:     foreach my $item (@{$images}) {
 1654:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 1655:     }
 1656:     return %defaults;
 1657: }
 1658: 
 1659: sub display_color_options {
 1660:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 1661:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 1662:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1663:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1664:     my $datatable = '<tr'.$css_class.'>'.
 1665:         '<td>'.$choices->{'font'}.'</td>';
 1666:     if (!$is_custom->{'font'}) {
 1667:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 1668:     } else {
 1669:         $datatable .= '<td>&nbsp;</td>';
 1670:     }
 1671:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 1672: 
 1673:     $datatable .= '<td><span class="LC_nobreak">'.
 1674:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 1675:                   ' value="'.$current_color.'" />&nbsp;'.
 1676:                   '&nbsp;</span></td></tr>';
 1677:     unless ($role eq 'login') { 
 1678:         $datatable .= '<tr'.$css_class.'>'.
 1679:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 1680:         if (!$is_custom->{'fontmenu'}) {
 1681:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 1682:         } else {
 1683:             $datatable .= '<td>&nbsp;</td>';
 1684:         }
 1685: 	$current_color = $designs->{'fontmenu'} ?
 1686: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 1687:         $datatable .= '<td><span class="LC_nobreak">'.
 1688:                       '<input class="colorchooser" type="text" size="10" name="'
 1689: 		      .$role.'_fontmenu"'.
 1690:                       ' value="'.$current_color.'" />&nbsp;'.
 1691:                       '&nbsp;</span></td></tr>';
 1692:     }
 1693:     my $switchserver = &check_switchserver($dom,$confname);
 1694:     foreach my $img (@{$images}) {
 1695: 	$itemcount ++;
 1696:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1697:         $datatable .= '<tr'.$css_class.'>'.
 1698:                       '<td>'.$choices->{$img};
 1699:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors);
 1700:         if ($role eq 'login') {
 1701:             if ($img eq 'login') {
 1702:                 $login_hdr_pick =
 1703:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 1704:                 $logincolors =
 1705:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 1706:                                        $designs,$defaults);
 1707:             } elsif ($img ne 'domlogo') {
 1708:                 $datatable.= &logo_display_options($img,$defaults,$designs);
 1709:             }
 1710:         }
 1711:         $datatable .= '</td>';
 1712:         if ($designs->{$img} ne '') {
 1713:             $imgfile = $designs->{$img};
 1714: 	    $img_import = ($imgfile =~ m{^/adm/});
 1715:         } else {
 1716:             $imgfile = $defaults->{$img};
 1717:         }
 1718:         if ($imgfile) {
 1719:             my ($showfile,$fullsize);
 1720:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 1721:                 my $urldir = $1;
 1722:                 my $filename = $2;
 1723:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 1724:                 if (@info) {
 1725:                     my $thumbfile = 'tn-'.$filename;
 1726:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 1727:                     if (@thumb) {
 1728:                         $showfile = $urldir.'/'.$thumbfile;
 1729:                     } else {
 1730:                         $showfile = $imgfile;
 1731:                     }
 1732:                 } else {
 1733:                     $showfile = '';
 1734:                 }
 1735:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 1736:                 $showfile = $imgfile;
 1737:                 my $imgdir = $1;
 1738:                 my $filename = $2;
 1739:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 1740:                     $showfile = "/$imgdir/tn-".$filename;
 1741:                 } else {
 1742:                     my $input = $londocroot.$imgfile;
 1743:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 1744:                     if (!-e $output) {
 1745:                         my ($width,$height) = &thumb_dimensions();
 1746:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 1747:                         if ($fullwidth ne '' && $fullheight ne '') {
 1748:                             if ($fullwidth > $width && $fullheight > $height) { 
 1749:                                 my $size = $width.'x'.$height;
 1750:                                 my @args = ('convert','-sample',$size,$input,$output);
 1751:                                 system({$args[0]} @args);
 1752:                                 $showfile = "/$imgdir/tn-".$filename;
 1753:                             }
 1754:                         }
 1755:                     }
 1756:                 }
 1757:             }
 1758:             if ($showfile) {
 1759:                 if ($showfile =~ m{^/(adm|res)/}) {
 1760:                     if ($showfile =~ m{^/res/}) {
 1761:                         my $local_showfile =
 1762:                             &Apache::lonnet::filelocation('',$showfile);
 1763:                         &Apache::lonnet::repcopy($local_showfile);
 1764:                     }
 1765:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 1766:                 }
 1767:                 if ($imgfile) {
 1768:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 1769:                         if ($imgfile =~ m{^/res/}) {
 1770:                             my $local_imgfile =
 1771:                                 &Apache::lonnet::filelocation('',$imgfile);
 1772:                             &Apache::lonnet::repcopy($local_imgfile);
 1773:                         }
 1774:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 1775:                     } else {
 1776:                         $fullsize = $imgfile;
 1777:                     }
 1778:                 }
 1779:                 $datatable .= '<td>';
 1780:                 if ($img eq 'login') {
 1781:                     $datatable .= $login_hdr_pick;
 1782:                 } 
 1783:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 1784:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 1785:             } else {
 1786:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1787:                               &mt('Upload:').'<br />';
 1788:             }
 1789:         } else {
 1790:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1791:                           &mt('Upload:').'<br />';
 1792:         }
 1793:         if ($switchserver) {
 1794:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1795:         } else {
 1796:             if ($img ne 'login') { # suppress file selection for Log-in header
 1797:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 1798:             }
 1799:         }
 1800:         $datatable .= '</td></tr>';
 1801:     }
 1802:     $itemcount ++;
 1803:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1804:     $datatable .= '<tr'.$css_class.'>'.
 1805:                   '<td>'.$choices->{'bgs'}.'</td>';
 1806:     my $bgs_def;
 1807:     foreach my $item (@{$bgs}) {
 1808:         if (!$is_custom->{$item}) {
 1809:             $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>';
 1810:         }
 1811:     }
 1812:     if ($bgs_def) {
 1813:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 1814:     } else {
 1815:         $datatable .= '<td>&nbsp;</td>';
 1816:     }
 1817:     $datatable .= '<td class="LC_right_item">'.
 1818:                   '<table border="0"><tr>';
 1819: 
 1820:     foreach my $item (@{$bgs}) {
 1821:         $datatable .= '<td style="text-align: center">'.$choices->{$item};
 1822: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 1823:         if ($designs->{'bgs'}{$item}) {
 1824:             $datatable .= '&nbsp;';
 1825:         }
 1826:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 1827:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 1828:     }
 1829:     $datatable .= '</tr></table></td></tr>';
 1830:     $itemcount ++;
 1831:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1832:     $datatable .= '<tr'.$css_class.'>'.
 1833:                   '<td>'.$choices->{'links'}.'</td>';
 1834:     my $links_def;
 1835:     foreach my $item (@{$links}) {
 1836:         if (!$is_custom->{$item}) {
 1837:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 1838:         }
 1839:     }
 1840:     if ($links_def) {
 1841:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 1842:     } else {
 1843:         $datatable .= '<td>&nbsp;</td>';
 1844:     }
 1845:     $datatable .= '<td class="LC_right_item">'.
 1846:                   '<table border="0"><tr>';
 1847:     foreach my $item (@{$links}) {
 1848: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 1849:         $datatable .= '<td style="text-align: center">'.$choices->{$item}."\n";
 1850:         if ($designs->{'links'}{$item}) {
 1851:             $datatable.='&nbsp;';
 1852:         }
 1853:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 1854:                       '" /></td>';
 1855:     }
 1856:     $$rowtotal += $itemcount;
 1857:     return $datatable;
 1858: }
 1859: 
 1860: sub logo_display_options {
 1861:     my ($img,$defaults,$designs) = @_;
 1862:     my $checkedon;
 1863:     if (ref($defaults) eq 'HASH') {
 1864:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 1865:             if ($defaults->{'showlogo'}{$img}) {
 1866:                 $checkedon = 'checked="checked" ';     
 1867:             }
 1868:         } 
 1869:     }
 1870:     if (ref($designs) eq 'HASH') {
 1871:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 1872:             if (defined($designs->{'showlogo'}{$img})) {
 1873:                 if ($designs->{'showlogo'}{$img} == 0) {
 1874:                     $checkedon = '';
 1875:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 1876:                     $checkedon = 'checked="checked" ';
 1877:                 }
 1878:             }
 1879:         }
 1880:     }
 1881:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 1882:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 1883:            &mt('show').'</label>'."\n";
 1884: }
 1885: 
 1886: sub login_header_options  {
 1887:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 1888:     my $output = '';
 1889:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 1890:         $output .= &mt('Text default(s):').'<br />';
 1891:         if (!$is_custom->{'textcol'}) {
 1892:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 1893:                        '&nbsp;&nbsp;&nbsp;';
 1894:         }
 1895:         if (!$is_custom->{'bgcol'}) {
 1896:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 1897:                        '<span id="css_'.$role.'_font" style="background-color: '.
 1898:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 1899:         }
 1900:         $output .= '<br />';
 1901:     }
 1902:     $output .='<br />';
 1903:     return $output;
 1904: }
 1905: 
 1906: sub login_text_colors {
 1907:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 1908:     my $color_menu = '<table border="0"><tr>';
 1909:     foreach my $item (@{$logintext}) {
 1910:         $color_menu .= '<td style="text-align: center">'.$choices->{$item};
 1911:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 1912:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 1913:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 1914:     }
 1915:     $color_menu .= '</tr></table><br />';
 1916:     return $color_menu;
 1917: }
 1918: 
 1919: sub image_changes {
 1920:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 1921:     my $output;
 1922:     if ($img eq 'login') {
 1923:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 1924:     } elsif (!$is_custom) {
 1925:         if ($img ne 'domlogo') {
 1926:             $output = &mt('Default image:').'<br />';
 1927:         } else {
 1928:             $output = &mt('Default in use:').'<br />';
 1929:         }
 1930:     }
 1931:     if ($img ne 'login') {
 1932:         if ($img_import) {
 1933:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 1934:         }
 1935:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 1936:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 1937:         if ($is_custom) {
 1938:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 1939:                        '<input type="checkbox" name="'.
 1940:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 1941:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 1942:         } else {
 1943:             $output .= '<td class="LC_middle">'.$logincolors.&mt('Upload:').'<br />';
 1944:         }
 1945:     }
 1946:     return $output;
 1947: }
 1948: 
 1949: sub print_quotas {
 1950:     my ($dom,$settings,$rowtotal,$action) = @_;
 1951:     my $context;
 1952:     if ($action eq 'quotas') {
 1953:         $context = 'tools';
 1954:     } else {
 1955:         $context = $action;
 1956:     }
 1957:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 1958:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 1959:     my $typecount = 0;
 1960:     my ($css_class,%titles);
 1961:     if ($context eq 'requestcourses') {
 1962:         @usertools = ('official','unofficial','community','textbook','placement','lti');
 1963:         @options =('norequest','approval','validate','autolimit');
 1964:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 1965:         %titles = &courserequest_titles();
 1966:     } elsif ($context eq 'requestauthor') {
 1967:         @usertools = ('author');
 1968:         @options = ('norequest','approval','automatic');
 1969:         %titles = &authorrequest_titles();
 1970:     } else {
 1971:         @usertools = ('aboutme','blog','webdav','portfolio');
 1972:         %titles = &tool_titles();
 1973:     }
 1974:     if (ref($types) eq 'ARRAY') {
 1975:         foreach my $type (@{$types}) {
 1976:             my ($currdefquota,$currauthorquota);
 1977:             unless (($context eq 'requestcourses') ||
 1978:                     ($context eq 'requestauthor')) {
 1979:                 if (ref($settings) eq 'HASH') {
 1980:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 1981:                         $currdefquota = $settings->{defaultquota}->{$type};
 1982:                     } else {
 1983:                         $currdefquota = $settings->{$type};
 1984:                     }
 1985:                     if (ref($settings->{authorquota}) eq 'HASH') {
 1986:                         $currauthorquota = $settings->{authorquota}->{$type};
 1987:                     }
 1988:                 }
 1989:             }
 1990:             if (defined($usertypes->{$type})) {
 1991:                 $typecount ++;
 1992:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 1993:                 $datatable .= '<tr'.$css_class.'>'.
 1994:                               '<td>'.$usertypes->{$type}.'</td>'.
 1995:                               '<td class="LC_left_item">';
 1996:                 if ($context eq 'requestcourses') {
 1997:                     $datatable .= '<table><tr>';
 1998:                 }
 1999:                 my %cell;  
 2000:                 foreach my $item (@usertools) {
 2001:                     if ($context eq 'requestcourses') {
 2002:                         my ($curroption,$currlimit);
 2003:                         if (ref($settings) eq 'HASH') {
 2004:                             if (ref($settings->{$item}) eq 'HASH') {
 2005:                                 $curroption = $settings->{$item}->{$type};
 2006:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 2007:                                     $currlimit = $1; 
 2008:                                 }
 2009:                             }
 2010:                         }
 2011:                         if (!$curroption) {
 2012:                             $curroption = 'norequest';
 2013:                         }
 2014:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 2015:                         foreach my $option (@options) {
 2016:                             my $val = $option;
 2017:                             if ($option eq 'norequest') {
 2018:                                 $val = 0;  
 2019:                             }
 2020:                             if ($option eq 'validate') {
 2021:                                 my $canvalidate = 0;
 2022:                                 if (ref($validations{$item}) eq 'HASH') { 
 2023:                                     if ($validations{$item}{$type}) {
 2024:                                         $canvalidate = 1;
 2025:                                     }
 2026:                                 }
 2027:                                 next if (!$canvalidate);
 2028:                             }
 2029:                             my $checked = '';
 2030:                             if ($option eq $curroption) {
 2031:                                 $checked = ' checked="checked"';
 2032:                             } elsif ($option eq 'autolimit') {
 2033:                                 if ($curroption =~ /^autolimit/) {
 2034:                                     $checked = ' checked="checked"';
 2035:                                 }                       
 2036:                             } 
 2037:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 2038:                                   '<input type="radio" name="crsreq_'.$item.
 2039:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 2040:                                   $titles{$option}.'</label>';
 2041:                             if ($option eq 'autolimit') {
 2042:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2043:                                                 $item.'_limit_'.$type.'" size="1" '.
 2044:                                                 'value="'.$currlimit.'" />';
 2045:                             }
 2046:                             $cell{$item} .= '</span> ';
 2047:                             if ($option eq 'autolimit') {
 2048:                                 $cell{$item} .= $titles{'unlimited'};
 2049:                             }
 2050:                         }
 2051:                     } elsif ($context eq 'requestauthor') {
 2052:                         my $curroption;
 2053:                         if (ref($settings) eq 'HASH') {
 2054:                             $curroption = $settings->{$type};
 2055:                         }
 2056:                         if (!$curroption) {
 2057:                             $curroption = 'norequest';
 2058:                         }
 2059:                         foreach my $option (@options) {
 2060:                             my $val = $option;
 2061:                             if ($option eq 'norequest') {
 2062:                                 $val = 0;
 2063:                             }
 2064:                             my $checked = '';
 2065:                             if ($option eq $curroption) {
 2066:                                 $checked = ' checked="checked"';
 2067:                             }
 2068:                             $datatable .= '<span class="LC_nobreak"><label>'.
 2069:                                   '<input type="radio" name="authorreq_'.$type.
 2070:                                   '" value="'.$val.'"'.$checked.' />'.
 2071:                                   $titles{$option}.'</label></span>&nbsp; ';
 2072:                         }
 2073:                     } else {
 2074:                         my $checked = 'checked="checked" ';
 2075:                         if (ref($settings) eq 'HASH') {
 2076:                             if (ref($settings->{$item}) eq 'HASH') {
 2077:                                 if ($settings->{$item}->{$type} == 0) {
 2078:                                     $checked = '';
 2079:                                 } elsif ($settings->{$item}->{$type} == 1) {
 2080:                                     $checked =  'checked="checked" ';
 2081:                                 }
 2082:                             }
 2083:                         }
 2084:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2085:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 2086:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 2087:                                       '</label></span>&nbsp; ';
 2088:                     }
 2089:                 }
 2090:                 if ($context eq 'requestcourses') {
 2091:                     $datatable .= '</tr><tr>';
 2092:                     foreach my $item (@usertools) {
 2093:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 2094:                     }
 2095:                     $datatable .= '</tr></table>';
 2096:                 }
 2097:                 $datatable .= '</td>';
 2098:                 unless (($context eq 'requestcourses') ||
 2099:                         ($context eq 'requestauthor')) {
 2100:                     $datatable .= 
 2101:                               '<td class="LC_right_item">'.
 2102:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2103:                               '<input type="text" name="quota_'.$type.
 2104:                               '" value="'.$currdefquota.
 2105:                               '" size="5" /></span>'.('&nbsp;' x 2).
 2106:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2107:                               '<input type="text" name="authorquota_'.$type.
 2108:                               '" value="'.$currauthorquota.
 2109:                               '" size="5" /></span></td>';
 2110:                 }
 2111:                 $datatable .= '</tr>';
 2112:             }
 2113:         }
 2114:     }
 2115:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2116:         $defaultquota = '20';
 2117:         $authorquota = '500';
 2118:         if (ref($settings) eq 'HASH') {
 2119:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 2120:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 2121:             } elsif (defined($settings->{'default'})) {
 2122:                 $defaultquota = $settings->{'default'};
 2123:             }
 2124:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 2125:                 $authorquota = $settings->{'authorquota'}->{'default'};
 2126:             }
 2127:         }
 2128:     }
 2129:     $typecount ++;
 2130:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2131:     $datatable .= '<tr'.$css_class.'>'.
 2132:                   '<td>'.$othertitle.'</td>'.
 2133:                   '<td class="LC_left_item">';
 2134:     if ($context eq 'requestcourses') {
 2135:         $datatable .= '<table><tr>';
 2136:     }
 2137:     my %defcell;
 2138:     foreach my $item (@usertools) {
 2139:         if ($context eq 'requestcourses') {
 2140:             my ($curroption,$currlimit);
 2141:             if (ref($settings) eq 'HASH') {
 2142:                 if (ref($settings->{$item}) eq 'HASH') {
 2143:                     $curroption = $settings->{$item}->{'default'};
 2144:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2145:                         $currlimit = $1;
 2146:                     }
 2147:                 }
 2148:             }
 2149:             if (!$curroption) {
 2150:                 $curroption = 'norequest';
 2151:             }
 2152:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2153:             foreach my $option (@options) {
 2154:                 my $val = $option;
 2155:                 if ($option eq 'norequest') {
 2156:                     $val = 0;
 2157:                 }
 2158:                 if ($option eq 'validate') {
 2159:                     my $canvalidate = 0;
 2160:                     if (ref($validations{$item}) eq 'HASH') {
 2161:                         if ($validations{$item}{'default'}) {
 2162:                             $canvalidate = 1;
 2163:                         }
 2164:                     }
 2165:                     next if (!$canvalidate);
 2166:                 }
 2167:                 my $checked = '';
 2168:                 if ($option eq $curroption) {
 2169:                     $checked = ' checked="checked"';
 2170:                 } elsif ($option eq 'autolimit') {
 2171:                     if ($curroption =~ /^autolimit/) {
 2172:                         $checked = ' checked="checked"';
 2173:                     }
 2174:                 }
 2175:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2176:                                   '<input type="radio" name="crsreq_'.$item.
 2177:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2178:                                   $titles{$option}.'</label>';
 2179:                 if ($option eq 'autolimit') {
 2180:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2181:                                        $item.'_limit_default" size="1" '.
 2182:                                        'value="'.$currlimit.'" />';
 2183:                 }
 2184:                 $defcell{$item} .= '</span> ';
 2185:                 if ($option eq 'autolimit') {
 2186:                     $defcell{$item} .= $titles{'unlimited'};
 2187:                 }
 2188:             }
 2189:         } elsif ($context eq 'requestauthor') {
 2190:             my $curroption;
 2191:             if (ref($settings) eq 'HASH') {
 2192:                 $curroption = $settings->{'default'};
 2193:             }
 2194:             if (!$curroption) {
 2195:                 $curroption = 'norequest';
 2196:             }
 2197:             foreach my $option (@options) {
 2198:                 my $val = $option;
 2199:                 if ($option eq 'norequest') {
 2200:                     $val = 0;
 2201:                 }
 2202:                 my $checked = '';
 2203:                 if ($option eq $curroption) {
 2204:                     $checked = ' checked="checked"';
 2205:                 }
 2206:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2207:                               '<input type="radio" name="authorreq_default"'.
 2208:                               ' value="'.$val.'"'.$checked.' />'.
 2209:                               $titles{$option}.'</label></span>&nbsp; ';
 2210:             }
 2211:         } else {
 2212:             my $checked = 'checked="checked" ';
 2213:             if (ref($settings) eq 'HASH') {
 2214:                 if (ref($settings->{$item}) eq 'HASH') {
 2215:                     if ($settings->{$item}->{'default'} == 0) {
 2216:                         $checked = '';
 2217:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2218:                         $checked = 'checked="checked" ';
 2219:                     }
 2220:                 }
 2221:             }
 2222:             $datatable .= '<span class="LC_nobreak"><label>'.
 2223:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2224:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2225:                           '</label></span>&nbsp; ';
 2226:         }
 2227:     }
 2228:     if ($context eq 'requestcourses') {
 2229:         $datatable .= '</tr><tr>';
 2230:         foreach my $item (@usertools) {
 2231:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2232:         }
 2233:         $datatable .= '</tr></table>';
 2234:     }
 2235:     $datatable .= '</td>';
 2236:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2237:         $datatable .= '<td class="LC_right_item">'.
 2238:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2239:                       '<input type="text" name="defaultquota" value="'.
 2240:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2241:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2242:                       '<input type="text" name="authorquota" value="'.
 2243:                       $authorquota.'" size="5" /></span></td>';
 2244:     }
 2245:     $datatable .= '</tr>';
 2246:     $typecount ++;
 2247:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2248:     $datatable .= '<tr'.$css_class.'>'.
 2249:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2250:     if ($context eq 'requestcourses') {
 2251:         $datatable .= &mt('(overrides affiliation, if set)').
 2252:                       '</td>'.
 2253:                       '<td class="LC_left_item">'.
 2254:                       '<table><tr>';
 2255:     } else {
 2256:         $datatable .= &mt('(overrides affiliation, if checked)').
 2257:                       '</td>'.
 2258:                       '<td class="LC_left_item" colspan="2">'.
 2259:                       '<br />';
 2260:     }
 2261:     my %advcell;
 2262:     foreach my $item (@usertools) {
 2263:         if ($context eq 'requestcourses') {
 2264:             my ($curroption,$currlimit);
 2265:             if (ref($settings) eq 'HASH') {
 2266:                 if (ref($settings->{$item}) eq 'HASH') {
 2267:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2268:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2269:                         $currlimit = $1;
 2270:                     }
 2271:                 }
 2272:             }
 2273:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2274:             my $checked = '';
 2275:             if ($curroption eq '') {
 2276:                 $checked = ' checked="checked"';
 2277:             }
 2278:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2279:                                '<input type="radio" name="crsreq_'.$item.
 2280:                                '__LC_adv" value=""'.$checked.' />'.
 2281:                                &mt('No override set').'</label></span>&nbsp; ';
 2282:             foreach my $option (@options) {
 2283:                 my $val = $option;
 2284:                 if ($option eq 'norequest') {
 2285:                     $val = 0;
 2286:                 }
 2287:                 if ($option eq 'validate') {
 2288:                     my $canvalidate = 0;
 2289:                     if (ref($validations{$item}) eq 'HASH') {
 2290:                         if ($validations{$item}{'_LC_adv'}) {
 2291:                             $canvalidate = 1;
 2292:                         }
 2293:                     }
 2294:                     next if (!$canvalidate);
 2295:                 }
 2296:                 my $checked = '';
 2297:                 if ($val eq $curroption) {
 2298:                     $checked = ' checked="checked"';
 2299:                 } elsif ($option eq 'autolimit') {
 2300:                     if ($curroption =~ /^autolimit/) {
 2301:                         $checked = ' checked="checked"';
 2302:                     }
 2303:                 }
 2304:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2305:                                   '<input type="radio" name="crsreq_'.$item.
 2306:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2307:                                   $titles{$option}.'</label>';
 2308:                 if ($option eq 'autolimit') {
 2309:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2310:                                        $item.'_limit__LC_adv" size="1" '.
 2311:                                        'value="'.$currlimit.'" />';
 2312:                 }
 2313:                 $advcell{$item} .= '</span> ';
 2314:                 if ($option eq 'autolimit') {
 2315:                     $advcell{$item} .= $titles{'unlimited'};
 2316:                 }
 2317:             }
 2318:         } elsif ($context eq 'requestauthor') {
 2319:             my $curroption;
 2320:             if (ref($settings) eq 'HASH') {
 2321:                 $curroption = $settings->{'_LC_adv'};
 2322:             }
 2323:             my $checked = '';
 2324:             if ($curroption eq '') {
 2325:                 $checked = ' checked="checked"';
 2326:             }
 2327:             $datatable .= '<span class="LC_nobreak"><label>'.
 2328:                           '<input type="radio" name="authorreq__LC_adv"'.
 2329:                           ' value=""'.$checked.' />'.
 2330:                           &mt('No override set').'</label></span>&nbsp; ';
 2331:             foreach my $option (@options) {
 2332:                 my $val = $option;
 2333:                 if ($option eq 'norequest') {
 2334:                     $val = 0;
 2335:                 }
 2336:                 my $checked = '';
 2337:                 if ($val eq $curroption) {
 2338:                     $checked = ' checked="checked"';
 2339:                 }
 2340:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2341:                               '<input type="radio" name="authorreq__LC_adv"'.
 2342:                               ' value="'.$val.'"'.$checked.' />'.
 2343:                               $titles{$option}.'</label></span>&nbsp; ';
 2344:             }
 2345:         } else {
 2346:             my $checked = 'checked="checked" ';
 2347:             if (ref($settings) eq 'HASH') {
 2348:                 if (ref($settings->{$item}) eq 'HASH') {
 2349:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2350:                         $checked = '';
 2351:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2352:                         $checked = 'checked="checked" ';
 2353:                     }
 2354:                 }
 2355:             }
 2356:             $datatable .= '<span class="LC_nobreak"><label>'.
 2357:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2358:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2359:                           '</label></span>&nbsp; ';
 2360:         }
 2361:     }
 2362:     if ($context eq 'requestcourses') {
 2363:         $datatable .= '</tr><tr>';
 2364:         foreach my $item (@usertools) {
 2365:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2366:         }
 2367:         $datatable .= '</tr></table>';
 2368:     }
 2369:     $datatable .= '</td></tr>';
 2370:     $$rowtotal += $typecount;
 2371:     return $datatable;
 2372: }
 2373: 
 2374: sub print_requestmail {
 2375:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2376:     my ($now,$datatable,%currapp);
 2377:     $now = time;
 2378:     if (ref($settings) eq 'HASH') {
 2379:         if (ref($settings->{'notify'}) eq 'HASH') {
 2380:             if ($settings->{'notify'}{'approval'} ne '') {
 2381:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2382:             }
 2383:         }
 2384:     }
 2385:     my $numinrow = 2;
 2386:     my $css_class;
 2387:     if ($$rowtotal%2) {
 2388:         $css_class = 'LC_odd_row';
 2389:     }
 2390:     if ($customcss) {
 2391:         $css_class .= " $customcss";
 2392:     }
 2393:     $css_class =~ s/^\s+//;
 2394:     if ($css_class) {
 2395:         $css_class = ' class="'.$css_class.'"';
 2396:     }
 2397:     if ($rowstyle) {
 2398:         $css_class .= ' style="'.$rowstyle.'"';
 2399:     }
 2400:     my $text;
 2401:     if ($action eq 'requestcourses') {
 2402:         $text = &mt('Receive notification of course requests requiring approval');
 2403:     } elsif ($action eq 'requestauthor') {
 2404:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2405:     } else {
 2406:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2407:     }
 2408:     $datatable = '<tr'.$css_class.'>'.
 2409:                  ' <td>'.$text.'</td>'.
 2410:                  ' <td class="LC_left_item">';
 2411:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2412:                                                  $action.'notifyapproval',%currapp);
 2413:     if ($numdc > 0) {
 2414:         $datatable .= $table;
 2415:     } else {
 2416:         $datatable .= &mt('There are no active Domain Coordinators');
 2417:     }
 2418:     $datatable .='</td></tr>';
 2419:     return $datatable;
 2420: }
 2421: 
 2422: sub print_studentcode {
 2423:     my ($settings,$rowtotal) = @_;
 2424:     my $rownum = 0; 
 2425:     my ($output,%current);
 2426:     my @crstypes = ('official','unofficial','community','textbook','placement','lti');
 2427:     if (ref($settings) eq 'HASH') {
 2428:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2429:             foreach my $type (@crstypes) {
 2430:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2431:             }
 2432:         }
 2433:     }
 2434:     $output .= '<tr>'.
 2435:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2436:                '<td class="LC_left_item">';
 2437:     foreach my $type (@crstypes) {
 2438:         my $check = ' ';
 2439:         if ($current{$type}) {
 2440:             $check = ' checked="checked" ';
 2441:         }
 2442:         $output .= '<span class="LC_nobreak"><label>'.
 2443:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2444:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2445:     }
 2446:     $output .= '</td></tr>';
 2447:     $$rowtotal ++;
 2448:     return $output;
 2449: }
 2450: 
 2451: sub print_textbookcourses {
 2452:     my ($dom,$type,$settings,$rowtotal) = @_;
 2453:     my $rownum = 0;
 2454:     my $css_class;
 2455:     my $itemcount = 1;
 2456:     my $maxnum = 0;
 2457:     my $bookshash;
 2458:     if (ref($settings) eq 'HASH') {
 2459:         $bookshash = $settings->{$type};
 2460:     }
 2461:     my %ordered;
 2462:     if (ref($bookshash) eq 'HASH') {
 2463:         foreach my $item (keys(%{$bookshash})) {
 2464:             if (ref($bookshash->{$item}) eq 'HASH') {
 2465:                 my $num = $bookshash->{$item}{'order'};
 2466:                 $ordered{$num} = $item;
 2467:             }
 2468:         }
 2469:     }
 2470:     my $confname = $dom.'-domainconfig';
 2471:     my $switchserver = &check_switchserver($dom,$confname);
 2472:     my $maxnum = scalar(keys(%ordered));
 2473:     my $datatable;
 2474:     if (keys(%ordered)) {
 2475:         my @items = sort { $a <=> $b } keys(%ordered);
 2476:         for (my $i=0; $i<@items; $i++) {
 2477:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2478:             my $key = $ordered{$items[$i]};
 2479:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2480:             my $coursetitle = $coursehash{'description'};
 2481:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2482:             if (ref($bookshash->{$key}) eq 'HASH') {
 2483:                 $subject = $bookshash->{$key}->{'subject'};
 2484:                 $title = $bookshash->{$key}->{'title'};
 2485:                 if ($type eq 'textbooks') {
 2486:                     $publisher = $bookshash->{$key}->{'publisher'};
 2487:                     $author = $bookshash->{$key}->{'author'};
 2488:                     $image = $bookshash->{$key}->{'image'};
 2489:                     if ($image ne '') {
 2490:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2491:                         my $imagethumb = "$path/tn-".$imagefile;
 2492:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2493:                     }
 2494:                 }
 2495:             }
 2496:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2497:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2498:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2499:             for (my $k=0; $k<=$maxnum; $k++) {
 2500:                 my $vpos = $k+1;
 2501:                 my $selstr;
 2502:                 if ($k == $i) {
 2503:                     $selstr = ' selected="selected" ';
 2504:                 }
 2505:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2506:             }
 2507:             $datatable .= '</select>'.('&nbsp;'x2).
 2508:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2509:                 &mt('Delete?').'</label></span></td>'.
 2510:                 '<td colspan="2">'.
 2511:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2512:                 ('&nbsp;'x2).
 2513:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2514:             if ($type eq 'textbooks') {
 2515:                 $datatable .= ('&nbsp;'x2).
 2516:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2517:                               ('&nbsp;'x2).
 2518:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2519:                               ('&nbsp;'x2).
 2520:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2521:                 if ($image) {
 2522:                     $datatable .= $imgsrc.
 2523:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2524:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2525:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2526:                 }
 2527:                 if ($switchserver) {
 2528:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2529:                 } else {
 2530:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2531:                 }
 2532:             }
 2533:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2534:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2535:                           $coursetitle.'</span></td></tr>'."\n";
 2536:             $itemcount ++;
 2537:         }
 2538:     }
 2539:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2540:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2541:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2542:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2543:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2544:     for (my $k=0; $k<$maxnum+1; $k++) {
 2545:         my $vpos = $k+1;
 2546:         my $selstr;
 2547:         if ($k == $maxnum) {
 2548:             $selstr = ' selected="selected" ';
 2549:         }
 2550:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2551:     }
 2552:     $datatable .= '</select>&nbsp;'."\n".
 2553:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2554:                   '<td colspan="2">'.
 2555:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2556:                   ('&nbsp;'x2).
 2557:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2558:                   ('&nbsp;'x2);
 2559:     if ($type eq 'textbooks') {
 2560:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2561:                       ('&nbsp;'x2).
 2562:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2563:                       ('&nbsp;'x2).
 2564:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2565:         if ($switchserver) {
 2566:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2567:         } else {
 2568:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2569:         }
 2570:         $datatable .= '</span>'."\n";
 2571:     }
 2572:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2573:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2574:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2575:                   &Apache::loncommon::selectcourse_link
 2576:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2577:                   '</span></td>'."\n".
 2578:                   '</tr>'."\n";
 2579:     $itemcount ++;
 2580:     return $datatable;
 2581: }
 2582: 
 2583: sub textbookcourses_javascript {
 2584:     my ($settings) = @_;
 2585:     return unless(ref($settings) eq 'HASH');
 2586:     my (%ordered,%total,%jstext);
 2587:     foreach my $type ('textbooks','templates') {
 2588:         $total{$type} = 0;
 2589:         if (ref($settings->{$type}) eq 'HASH') {
 2590:             foreach my $item (keys(%{$settings->{$type}})) {
 2591:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2592:                     my $num = $settings->{$type}->{$item}{'order'};
 2593:                     $ordered{$type}{$num} = $item;
 2594:                 }
 2595:             }
 2596:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2597:         }
 2598:         my @jsarray = ();
 2599:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 2600:             push(@jsarray,$ordered{$type}{$item});
 2601:         }
 2602:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 2603:     }
 2604:     return <<"ENDSCRIPT";
 2605: <script type="text/javascript">
 2606: // <![CDATA[
 2607: function reorderBooks(form,item,caller) {
 2608:     var changedVal;
 2609: $jstext{'textbooks'};
 2610: $jstext{'templates'};
 2611:     var newpos;
 2612:     var maxh;
 2613:     if (caller == 'textbooks') {  
 2614:         newpos = 'textbooks_addbook_pos';
 2615:         maxh = 1 + $total{'textbooks'};
 2616:     } else {
 2617:         newpos = 'templates_addbook_pos';
 2618:         maxh = 1 + $total{'templates'};
 2619:     }
 2620:     var current = new Array;
 2621:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2622:     if (item == newpos) {
 2623:         changedVal = newitemVal;
 2624:     } else {
 2625:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2626:         current[newitemVal] = newpos;
 2627:     }
 2628:     if (caller == 'textbooks') {
 2629:         for (var i=0; i<textbooks.length; i++) {
 2630:             var elementName = 'textbooks_'+textbooks[i];
 2631:             if (elementName != item) {
 2632:                 if (form.elements[elementName]) {
 2633:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2634:                     current[currVal] = elementName;
 2635:                 }
 2636:             }
 2637:         }
 2638:     }
 2639:     if (caller == 'templates') {
 2640:         for (var i=0; i<templates.length; i++) {
 2641:             var elementName = 'templates_'+templates[i];
 2642:             if (elementName != item) {
 2643:                 if (form.elements[elementName]) {
 2644:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2645:                     current[currVal] = elementName;
 2646:                 }
 2647:             }
 2648:         }
 2649:     }
 2650:     var oldVal;
 2651:     for (var j=0; j<maxh; j++) {
 2652:         if (current[j] == undefined) {
 2653:             oldVal = j;
 2654:         }
 2655:     }
 2656:     if (oldVal < changedVal) {
 2657:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2658:            var elementName = current[k];
 2659:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2660:         }
 2661:     } else {
 2662:         for (var k=changedVal; k<oldVal; k++) {
 2663:             var elementName = current[k];
 2664:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2665:         }
 2666:     }
 2667:     return;
 2668: }
 2669: 
 2670: // ]]>
 2671: </script>
 2672: 
 2673: ENDSCRIPT
 2674: }
 2675: 
 2676: sub ltitools_javascript {
 2677:     my ($settings) = @_;
 2678:     my $togglejs = &ltitools_toggle_js();
 2679:     unless (ref($settings) eq 'HASH') {
 2680:         return $togglejs;
 2681:     }
 2682:     my (%ordered,$total,%jstext);
 2683:     $total = 0;
 2684:     foreach my $item (keys(%{$settings})) {
 2685:         if (ref($settings->{$item}) eq 'HASH') {
 2686:             my $num = $settings->{$item}{'order'};
 2687:             $ordered{$num} = $item;
 2688:         }
 2689:     }
 2690:     $total = scalar(keys(%{$settings}));
 2691:     my @jsarray = ();
 2692:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 2693:         push(@jsarray,$ordered{$item});
 2694:     }
 2695:     my $jstext = '    var ltitools = Array('."'".join("','",@jsarray)."'".');'."\n";
 2696:     return <<"ENDSCRIPT";
 2697: <script type="text/javascript">
 2698: // <![CDATA[
 2699: function reorderLTITools(form,item) {
 2700:     var changedVal;
 2701: $jstext
 2702:     var newpos = 'ltitools_add_pos';
 2703:     var maxh = 1 + $total;
 2704:     var current = new Array;
 2705:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2706:     if (item == newpos) {
 2707:         changedVal = newitemVal;
 2708:     } else {
 2709:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2710:         current[newitemVal] = newpos;
 2711:     }
 2712:     for (var i=0; i<ltitools.length; i++) {
 2713:         var elementName = 'ltitools_'+ltitools[i];
 2714:         if (elementName != item) {
 2715:             if (form.elements[elementName]) {
 2716:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2717:                 current[currVal] = elementName;
 2718:             }
 2719:         }
 2720:     }
 2721:     var oldVal;
 2722:     for (var j=0; j<maxh; j++) {
 2723:         if (current[j] == undefined) {
 2724:             oldVal = j;
 2725:         }
 2726:     }
 2727:     if (oldVal < changedVal) {
 2728:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2729:            var elementName = current[k];
 2730:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2731:         }
 2732:     } else {
 2733:         for (var k=changedVal; k<oldVal; k++) {
 2734:             var elementName = current[k];
 2735:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2736:         }
 2737:     }
 2738:     return;
 2739: }
 2740: 
 2741: // ]]>
 2742: </script>
 2743: 
 2744: $togglejs
 2745: 
 2746: ENDSCRIPT
 2747: }
 2748: 
 2749: sub ltitools_toggle_js {
 2750:     return <<"ENDSCRIPT";
 2751: <script type="text/javascript">
 2752: // <![CDATA[
 2753: 
 2754: function toggleLTITools(form,setting,item) {
 2755:     var radioname = '';
 2756:     var divid = '';
 2757:     if ((setting == 'passback') || (setting == 'roster')) {
 2758:         radioname = 'ltitools_'+setting+'_'+item;
 2759:         divid = 'ltitools_'+setting+'time_'+item;
 2760:         var num = form.elements[radioname].length;
 2761:         if (num) {
 2762:             var setvis = '';
 2763:             for (var i=0; i<num; i++) {
 2764:                 if (form.elements[radioname][i].checked) {
 2765:                     if (form.elements[radioname][i].value == '1') {
 2766:                         if (document.getElementById(divid)) {
 2767:                             document.getElementById(divid).style.display = 'inline-block';
 2768:                         }
 2769:                         setvis = 1;
 2770:                     }
 2771:                     break;
 2772:                 }
 2773:             }
 2774:         }
 2775:         if (!setvis) {
 2776:             if (document.getElementById(divid)) {
 2777:                 document.getElementById(divid).style.display = 'none';
 2778:             }
 2779:         }
 2780:     }
 2781:     if (setting == 'user') {
 2782:         divid = 'ltitools_'+setting+'_div_'+item;
 2783:         var checkid = 'ltitools_'+setting+'_field_'+item;
 2784:         if (document.getElementById(divid)) {
 2785:             if (document.getElementById(checkid)) {
 2786:                 if (document.getElementById(checkid).checked) {
 2787:                     document.getElementById(divid).style.display = 'inline-block';
 2788:                 } else {
 2789:                     document.getElementById(divid).style.display = 'none';
 2790:                 }
 2791:             }
 2792:         }
 2793:     }
 2794:     return;
 2795: }
 2796: // ]]>
 2797: </script>
 2798: 
 2799: ENDSCRIPT
 2800: }
 2801: 
 2802: sub lti_javascript {
 2803:     my ($settings) = @_;
 2804:     my $togglejs = &lti_toggle_js();
 2805:     unless (ref($settings) eq 'HASH') {
 2806:         return $togglejs;
 2807:     }
 2808:     my (%ordered,$total,%jstext);
 2809:     $total = 0;
 2810:     foreach my $item (keys(%{$settings})) {
 2811:         if (ref($settings->{$item}) eq 'HASH') {
 2812:             my $num = $settings->{$item}{'order'};
 2813:             $ordered{$num} = $item;
 2814:         }
 2815:     }
 2816:     $total = scalar(keys(%{$settings}));
 2817:     my @jsarray = ();
 2818:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 2819:         push(@jsarray,$ordered{$item});
 2820:     }
 2821:     my $jstext = '    var lti = Array('."'".join("','",@jsarray)."'".');'."\n";
 2822:     return <<"ENDSCRIPT";
 2823: <script type="text/javascript">
 2824: // <![CDATA[
 2825: function reorderLTI(form,item) {
 2826:     var changedVal;
 2827: $jstext
 2828:     var newpos = 'lti_pos_add';
 2829:     var maxh = 1 + $total;
 2830:     var current = new Array;
 2831:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2832:     if (item == newpos) {
 2833:         changedVal = newitemVal;
 2834:     } else {
 2835:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2836:         current[newitemVal] = newpos;
 2837:     }
 2838:     for (var i=0; i<lti.length; i++) {
 2839:         var elementName = 'lti_pos_'+lti[i];
 2840:         if (elementName != item) {
 2841:             if (form.elements[elementName]) {
 2842:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2843:                 current[currVal] = elementName;
 2844:             }
 2845:         }
 2846:     }
 2847:     var oldVal;
 2848:     for (var j=0; j<maxh; j++) {
 2849:         if (current[j] == undefined) {
 2850:             oldVal = j;
 2851:         }
 2852:     }
 2853:     if (oldVal < changedVal) {
 2854:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2855:            var elementName = current[k];
 2856:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2857:         }
 2858:     } else {
 2859:         for (var k=changedVal; k<oldVal; k++) {
 2860:             var elementName = current[k];
 2861:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2862:         }
 2863:     }
 2864:     return;
 2865: }
 2866: // ]]>
 2867: </script>
 2868: 
 2869: $togglejs
 2870: 
 2871: ENDSCRIPT
 2872: }
 2873: 
 2874: sub lti_toggle_js {
 2875:     my %lcauthparmtext = &Apache::lonlocal::texthash (
 2876:                             localauth => 'Local auth argument',
 2877:                             krb       => 'Kerberos domain',
 2878:                          );
 2879:     return <<"ENDSCRIPT";
 2880: <script type="text/javascript">
 2881: // <![CDATA[
 2882: 
 2883: function toggleLTI(form,setting,item) {
 2884:     if (setting == 'requser') {
 2885:         var fieldsets = document.getElementsByClassName('ltioption_'+item);
 2886:         if (fieldsets.length) {
 2887:             var radioname = 'lti_'+setting+'_'+item;
 2888:             var num = form.elements[radioname].length;
 2889:             if (num) {
 2890:                 var setvis = '';
 2891:                 for (var i=0; i<num; i++) {
 2892:                     if (form.elements[radioname][i].checked) {
 2893:                         if (form.elements[radioname][i].value == '1') {
 2894:                            setvis = 1;
 2895:                            break;
 2896:                         }
 2897:                     }
 2898:                 }
 2899:                 for (var j=0; j<fieldsets.length; j++) {
 2900:                     if (setvis) {
 2901:                         fieldsets[j].style.display = 'block';
 2902:                     } else {
 2903:                         fieldsets[j].style.display = 'none';
 2904:                     }
 2905:                 }
 2906:             }
 2907:         }
 2908:     } else if ((setting == 'user') || (setting == 'crs') || (setting == 'passback') || (setting == 'callback')) {
 2909:         var radioname = '';
 2910:         var divid = '';
 2911:         if (setting == 'user') {
 2912:             radioname = 'lti_mapuser_'+item;
 2913:             divid = 'lti_userfield_'+item;
 2914:         } else if (setting == 'crs') {
 2915:             radioname = 'lti_mapcrs_'+item;
 2916:             divid = 'lti_crsfield_'+item;
 2917:         } else if (setting == 'callback') {
 2918:             radioname = 'lti_callback_'+item;
 2919:             divid = 'lti_callbackfield_'+item;
 2920:         } else {
 2921:             radioname = 'lti_passback_'+item;
 2922:             divid =  'lti_passback_'+item;
 2923:         }
 2924:         var num = form.elements[radioname].length;
 2925:         if (num) {
 2926:             var setvis = '';
 2927:             for (var i=0; i<num; i++) {
 2928:                if (form.elements[radioname][i].checked) {
 2929:                    if ((setting == 'passback') || (setting == 'callback')) {
 2930:                        if (form.elements[radioname][i].value == '1') {
 2931:                            if (document.getElementById(divid)) {
 2932:                                document.getElementById(divid).style.display = 'inline-block';
 2933:                            }
 2934:                            setvis = 1;
 2935:                            break;
 2936:                        }
 2937:                    } else {
 2938:                        if (form.elements[radioname][i].value == 'other') {
 2939:                            if (document.getElementById(divid)) {
 2940:                                document.getElementById(divid).style.display = 'inline-block';
 2941:                            }
 2942:                            setvis = 1;
 2943:                            break;
 2944:                        }
 2945:                    }
 2946:                } 
 2947:             }
 2948:             if (!setvis) {
 2949:                 if (document.getElementById(divid)) {
 2950:                     document.getElementById(divid).style.display = 'none';
 2951:                 }
 2952:             }
 2953:         }
 2954:     } else if ((setting == 'sec') || (setting == 'secsrc')) {
 2955:         var numsec = form.elements['lti_crssec_'+item].length;
 2956:         if (numsec) {
 2957:             var setvis = '';
 2958:             for (var i=0; i<numsec; i++) {
 2959:                 if (form.elements['lti_crssec_'+item][i].checked) {
 2960:                     if (form.elements['lti_crssec_'+item][i].value == '1') {
 2961:                         if (document.getElementById('lti_crssecfield_'+item)) {
 2962:                             document.getElementById('lti_crssecfield_'+item).style.display = 'inline-block';
 2963:                             setvis = 1;
 2964:                             var numsrcsec = form.elements['lti_crssecsrc_'+item].length;
 2965:                             if (numsrcsec) {
 2966:                                 var setsrcvis = '';
 2967:                                 for (var j=0; j<numsrcsec; j++) {
 2968:                                     if (form.elements['lti_crssecsrc_'+item][j].checked) {
 2969:                                         if (form.elements['lti_crssecsrc_'+item][j].value == 'other') {
 2970:                                             if (document.getElementById('lti_secsrcfield_'+item)) {
 2971:                                                 document.getElementById('lti_secsrcfield_'+item).style.display = 'inline-block';
 2972:                                                 setsrcvis = 1;
 2973:                                             }
 2974:                                         }
 2975:                                     }
 2976:                                 }
 2977:                                 if (!setsrcvis) {
 2978:                                     if (document.getElementById('lti_secsrcfield_'+item)) {
 2979:                                         document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 2980:                                     }
 2981:                                 }
 2982:                             }
 2983:                         }
 2984:                     }
 2985:                 }
 2986:             }
 2987:             if (!setvis) {
 2988:                 if (document.getElementById('lti_crssecfield_'+item)) {
 2989:                     document.getElementById('lti_crssecfield_'+item).style.display = 'none';
 2990:                 }
 2991:                 if (document.getElementById('lti_secsrcfield_'+item)) {
 2992:                     document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 2993:                 }
 2994:             }
 2995:         }
 2996:     } else if (setting == 'lcauth') {
 2997:         var numauth = form.elements['lti_lcauth_'+item].length;
 2998:         if (numauth) {
 2999:             for (var i=0; i<numauth; i++) {
 3000:                 if (form.elements['lti_lcauth_'+item][i].checked) {
 3001:                     if (document.getElementById('lti_'+setting+'_parmrow_'+item)) {
 3002:                         if ((form.elements['lti_'+setting+'_'+item][i].value == 'internal') || (form.elements['lti_'+setting+'_'+item][i].value == 'lti')) {
 3003:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'none';
 3004:                         } else {
 3005:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'table-row';
 3006:                             if (document.getElementById('lti_'+setting+'_parmtext_'+item)) {
 3007:                                 if (form.elements['lti_'+setting+'_'+item][i].value == 'localauth') {
 3008:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'localauth'}";
 3009:                                 } else {
 3010:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'krb'}";
 3011:                                 }
 3012:                             }
 3013:                         }
 3014:                     }
 3015:                 }
 3016:             }
 3017:         }
 3018:     } else if (setting == 'lcmenu') {
 3019:         var menus = new Array('lti_topmenu_'+item,'lti_inlinemenu_'+item);
 3020:         var divid = 'lti_menufield_'+item;
 3021:         var setvis = '';
 3022:         for (var i=0; i<menus.length; i++) {
 3023:             var radioname = menus[i];  
 3024:             var num = form.elements[radioname].length;
 3025:             if (num) {
 3026:                 for (var j=0; j<num; j++) {
 3027:                     if (form.elements[radioname][j].checked) {
 3028:                         if (form.elements[radioname][j].value == '1') {
 3029:                             if (document.getElementById(divid)) {
 3030:                                 document.getElementById(divid).style.display = 'inline-block';
 3031:                             }
 3032:                             setvis = 1;
 3033:                             break;
 3034:                         }
 3035:                     }
 3036:                 }
 3037:             }
 3038:             if (setvis == 1) {
 3039:                 break;
 3040:             }
 3041:         }
 3042:         if (!setvis) {
 3043:             if (document.getElementById(divid)) {
 3044:                 document.getElementById(divid).style.display = 'none';
 3045:             }
 3046:         }
 3047:     }
 3048:     return;
 3049: }
 3050: // ]]>
 3051: </script>
 3052: 
 3053: ENDSCRIPT
 3054: }
 3055: 
 3056: sub print_autoenroll {
 3057:     my ($dom,$settings,$rowtotal) = @_;
 3058:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 3059:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,$failsafe);
 3060:     if (ref($settings) eq 'HASH') {
 3061:         if (exists($settings->{'run'})) {
 3062:             if ($settings->{'run'} eq '0') {
 3063:                 $runoff = ' checked="checked" ';
 3064:                 $runon = ' ';
 3065:             } else {
 3066:                 $runon = ' checked="checked" ';
 3067:                 $runoff = ' ';
 3068:             }
 3069:         } else {
 3070:             if ($autorun) {
 3071:                 $runon = ' checked="checked" ';
 3072:                 $runoff = ' ';
 3073:             } else {
 3074:                 $runoff = ' checked="checked" ';
 3075:                 $runon = ' ';
 3076:             }
 3077:         }
 3078:         if (exists($settings->{'co-owners'})) {
 3079:             if ($settings->{'co-owners'} eq '0') {
 3080:                 $coownersoff = ' checked="checked" ';
 3081:                 $coownerson = ' ';
 3082:             } else {
 3083:                 $coownerson = ' checked="checked" ';
 3084:                 $coownersoff = ' ';
 3085:             }
 3086:         } else {
 3087:             $coownersoff = ' checked="checked" ';
 3088:             $coownerson = ' ';
 3089:         }
 3090:         if (exists($settings->{'sender_domain'})) {
 3091:             $defdom = $settings->{'sender_domain'};
 3092:         }
 3093:         if (exists($settings->{'autofailsafe'})) {
 3094:             $failsafe = $settings->{'autofailsafe'};
 3095:         }
 3096:     } else {
 3097:         if ($autorun) {
 3098:             $runon = ' checked="checked" ';
 3099:             $runoff = ' ';
 3100:         } else {
 3101:             $runoff = ' checked="checked" ';
 3102:             $runon = ' ';
 3103:         }
 3104:     }
 3105:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 3106:     my $notif_sender;
 3107:     if (ref($settings) eq 'HASH') {
 3108:         $notif_sender = $settings->{'sender_uname'};
 3109:     }
 3110:     my $datatable='<tr class="LC_odd_row">'.
 3111:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 3112:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3113:                   '<input type="radio" name="autoenroll_run"'.
 3114:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3115:                   '<label><input type="radio" name="autoenroll_run"'.
 3116:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3117:                   '</tr><tr>'.
 3118:                   '<td>'.&mt('Notification messages - sender').
 3119:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 3120:                   &mt('username').':&nbsp;'.
 3121:                   '<input type="text" name="sender_uname" value="'.
 3122:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 3123:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 3124:                   '<tr class="LC_odd_row">'.
 3125:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 3126:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3127:                   '<input type="radio" name="autoassign_coowners"'.
 3128:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3129:                   '<label><input type="radio" name="autoassign_coowners"'.
 3130:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3131:                   '</tr><tr>'.
 3132:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 3133:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 3134:                   '<input type="text" name="autoenroll_failsafe"'.
 3135:                   ' value="'.$failsafe.'" size="4" /></span></td></tr>';
 3136:     $$rowtotal += 4;
 3137:     return $datatable;
 3138: }
 3139: 
 3140: sub print_autoupdate {
 3141:     my ($position,$dom,$settings,$rowtotal) = @_;
 3142:     my $datatable;
 3143:     if ($position eq 'top') {
 3144:         my $updateon = ' ';
 3145:         my $updateoff = ' checked="checked" ';
 3146:         my $classlistson = ' ';
 3147:         my $classlistsoff = ' checked="checked" ';
 3148:         if (ref($settings) eq 'HASH') {
 3149:             if ($settings->{'run'} eq '1') {
 3150:                 $updateon = $updateoff;
 3151:                 $updateoff = ' ';
 3152:             }
 3153:             if ($settings->{'classlists'} eq '1') {
 3154:                 $classlistson = $classlistsoff;
 3155:                 $classlistsoff = ' ';
 3156:             }
 3157:         }
 3158:         my %title = (
 3159:                    run => 'Auto-update active?',
 3160:                    classlists => 'Update information in classlists?',
 3161:                     );
 3162:         $datatable = '<tr class="LC_odd_row">'. 
 3163:                   '<td>'.&mt($title{'run'}).'</td>'.
 3164:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3165:                   '<input type="radio" name="autoupdate_run"'.
 3166:                   $updateon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3167:                   '<label><input type="radio" name="autoupdate_run"'.
 3168:                   $updateoff.'value="0" />'.&mt('No').'</label></span></td>'.
 3169:                   '</tr><tr>'.
 3170:                   '<td>'.&mt($title{'classlists'}).'</td>'.
 3171:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 3172:                   '<label><input type="radio" name="classlists"'.
 3173:                   $classlistson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3174:                   '<label><input type="radio" name="classlists"'.
 3175:                   $classlistsoff.'value="0" />'.&mt('No').'</label></span></td>'.
 3176:                   '</tr>';
 3177:         $$rowtotal += 2;
 3178:     } elsif ($position eq 'middle') {
 3179:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3180:         my $numinrow = 3;
 3181:         my $locknamesettings;
 3182:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 3183:                                      $dom,$numinrow,$othertitle,
 3184:                                     'lockablenames',$rowtotal);
 3185:         $$rowtotal ++;
 3186:     } else {
 3187:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3188:         my @fields = ('lastname','firstname','middlename','generation',
 3189:                       'permanentemail','id');
 3190:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3191:         my $numrows = 0;
 3192:         if (ref($types) eq 'ARRAY') {
 3193:             if (@{$types} > 0) {
 3194:                 $datatable = 
 3195:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 3196:                                          \@fields,$types,\$numrows);
 3197:                     $$rowtotal += @{$types}; 
 3198:             }
 3199:         }
 3200:         $datatable .= 
 3201:             &usertype_update_row($settings,{'default' => $othertitle},
 3202:                                  \%fieldtitles,\@fields,['default'],
 3203:                                  \$numrows);
 3204:         $$rowtotal ++;     
 3205:     }
 3206:     return $datatable;
 3207: }
 3208: 
 3209: sub print_autocreate {
 3210:     my ($dom,$settings,$rowtotal) = @_;
 3211:     my (%createon,%createoff,%currhash);
 3212:     my @types = ('xml','req');
 3213:     if (ref($settings) eq 'HASH') {
 3214:         foreach my $item (@types) {
 3215:             $createoff{$item} = ' checked="checked" ';
 3216:             $createon{$item} = ' ';
 3217:             if (exists($settings->{$item})) {
 3218:                 if ($settings->{$item}) {
 3219:                     $createon{$item} = ' checked="checked" ';
 3220:                     $createoff{$item} = ' ';
 3221:                 }
 3222:             }
 3223:         }
 3224:         if ($settings->{'xmldc'} ne '') {
 3225:             $currhash{$settings->{'xmldc'}} = 1;
 3226:         }
 3227:     } else {
 3228:         foreach my $item (@types) {
 3229:             $createoff{$item} = ' checked="checked" ';
 3230:             $createon{$item} = ' ';
 3231:         }
 3232:     }
 3233:     $$rowtotal += 2;
 3234:     my $numinrow = 2;
 3235:     my $datatable='<tr class="LC_odd_row">'.
 3236:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 3237:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3238:                   '<input type="radio" name="autocreate_xml"'.
 3239:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3240:                   '<label><input type="radio" name="autocreate_xml"'.
 3241:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 3242:                   '</td></tr><tr>'.
 3243:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 3244:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3245:                   '<input type="radio" name="autocreate_req"'.
 3246:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3247:                   '<label><input type="radio" name="autocreate_req"'.
 3248:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 3249:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 3250:                                                    'autocreate_xmldc',%currhash);
 3251:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 3252:     if ($numdc > 1) {
 3253:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 3254:                       '</td><td class="LC_left_item">';
 3255:     } else {
 3256:         $datatable .= &mt('Course creation processed as:').
 3257:                       '</td><td class="LC_right_item">';
 3258:     }
 3259:     $datatable .= $dctable.'</td></tr>';
 3260:     $$rowtotal += $rows;
 3261:     return $datatable;
 3262: }
 3263: 
 3264: sub print_directorysrch {
 3265:     my ($position,$dom,$settings,$rowtotal) = @_;
 3266:     my $datatable;
 3267:     if ($position eq 'top') {
 3268:         my $instsrchon = ' ';
 3269:         my $instsrchoff = ' checked="checked" ';
 3270:         my ($exacton,$containson,$beginson);
 3271:         my $instlocalon = ' ';
 3272:         my $instlocaloff = ' checked="checked" ';
 3273:         if (ref($settings) eq 'HASH') {
 3274:             if ($settings->{'available'} eq '1') {
 3275:                 $instsrchon = $instsrchoff;
 3276:                 $instsrchoff = ' ';
 3277:             }
 3278:             if ($settings->{'localonly'} eq '1') {
 3279:                 $instlocalon = $instlocaloff;
 3280:                 $instlocaloff = ' ';
 3281:             }
 3282:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 3283:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 3284:                     if ($type eq 'exact') {
 3285:                         $exacton = ' checked="checked" ';
 3286:                     } elsif ($type eq 'contains') {
 3287:                         $containson = ' checked="checked" ';
 3288:                     } elsif ($type eq 'begins') {
 3289:                         $beginson = ' checked="checked" ';
 3290:                     }
 3291:                 }
 3292:             } else {
 3293:                 if ($settings->{'searchtypes'} eq 'exact') {
 3294:                     $exacton = ' checked="checked" ';
 3295:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 3296:                     $containson = ' checked="checked" ';
 3297:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 3298:                     $exacton = ' checked="checked" ';
 3299:                     $containson = ' checked="checked" ';
 3300:                 }
 3301:             }
 3302:         }
 3303:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 3304:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3305: 
 3306:         my $numinrow = 4;
 3307:         my $cansrchrow = 0;
 3308:         $datatable='<tr class="LC_odd_row">'.
 3309:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 3310:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3311:                    '<input type="radio" name="dirsrch_available"'.
 3312:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3313:                    '<label><input type="radio" name="dirsrch_available"'.
 3314:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3315:                    '</tr><tr>'.
 3316:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 3317:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3318:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 3319:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3320:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 3321:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3322:                    '</tr>';
 3323:         $$rowtotal += 2;
 3324:         if (ref($usertypes) eq 'HASH') {
 3325:             if (keys(%{$usertypes}) > 0) {
 3326:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 3327:                                              $numinrow,$othertitle,'cansearch',
 3328:                                              $rowtotal);
 3329:                 $cansrchrow = 1;
 3330:             }
 3331:         }
 3332:         if ($cansrchrow) {
 3333:             $$rowtotal ++;
 3334:             $datatable .= '<tr>';
 3335:         } else {
 3336:             $datatable .= '<tr class="LC_odd_row">';
 3337:         }
 3338:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 3339:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 3340:         foreach my $title (@{$titleorder}) {
 3341:             if (defined($searchtitles->{$title})) {
 3342:                 my $check = ' ';
 3343:                 if (ref($settings) eq 'HASH') {
 3344:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 3345:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 3346:                             $check = ' checked="checked" ';
 3347:                         }
 3348:                     }
 3349:                 }
 3350:                 $datatable .= '<td class="LC_left_item">'.
 3351:                               '<span class="LC_nobreak"><label>'.
 3352:                               '<input type="checkbox" name="searchby" '.
 3353:                               'value="'.$title.'"'.$check.'/>'.
 3354:                               $searchtitles->{$title}.'</label></span></td>';
 3355:             }
 3356:         }
 3357:         $datatable .= '</tr></table></td></tr>';
 3358:         $$rowtotal ++;
 3359:         if ($cansrchrow) {
 3360:             $datatable .= '<tr class="LC_odd_row">';
 3361:         } else {
 3362:             $datatable .= '<tr>';
 3363:         }
 3364:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 3365:                       '<td class="LC_left_item" colspan="2">'.
 3366:                       '<span class="LC_nobreak"><label>'.
 3367:                       '<input type="checkbox" name="searchtypes" '.
 3368:                       $exacton.' value="exact" />'.&mt('Exact match').
 3369:                       '</label>&nbsp;'.
 3370:                       '<label><input type="checkbox" name="searchtypes" '.
 3371:                       $beginson.' value="begins" />'.&mt('Begins with').
 3372:                       '</label>&nbsp;'.
 3373:                       '<label><input type="checkbox" name="searchtypes" '.
 3374:                       $containson.' value="contains" />'.&mt('Contains').
 3375:                       '</label></span></td></tr>';
 3376:         $$rowtotal ++;
 3377:     } else {
 3378:         my $domsrchon = ' checked="checked" ';
 3379:         my $domsrchoff = ' ';
 3380:         my $domlocalon = ' ';
 3381:         my $domlocaloff = ' checked="checked" ';
 3382:         if (ref($settings) eq 'HASH') {
 3383:             if ($settings->{'lclocalonly'} eq '1') {
 3384:                 $domlocalon = $domlocaloff;
 3385:                 $domlocaloff = ' ';
 3386:             }
 3387:             if ($settings->{'lcavailable'} eq '0') {
 3388:                 $domsrchoff = $domsrchon;
 3389:                 $domsrchon = ' ';
 3390:             }
 3391:         }
 3392:         $datatable='<tr class="LC_odd_row">'.
 3393:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 3394:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3395:                       '<input type="radio" name="dirsrch_domavailable"'.
 3396:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3397:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 3398:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3399:                       '</tr><tr>'.
 3400:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 3401:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3402:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 3403:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3404:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 3405:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3406:                       '</tr>';
 3407:         $$rowtotal += 2;
 3408:     }
 3409:     return $datatable;
 3410: }
 3411: 
 3412: sub print_contacts {
 3413:     my ($position,$dom,$settings,$rowtotal) = @_;
 3414:     my $datatable;
 3415:     my @contacts = ('adminemail','supportemail');
 3416:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 3417:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings,%lonstatus);
 3418:     if ($position eq 'top') {
 3419:         if (ref($settings) eq 'HASH') {
 3420:             foreach my $item (@contacts) {
 3421:                 if (exists($settings->{$item})) {
 3422:                     $to{$item} = $settings->{$item};
 3423:                 }
 3424:             }
 3425:         }
 3426:     } elsif ($position eq 'middle') {
 3427:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 3428:                      'updatesmail','idconflictsmail','hostipmail');
 3429:         foreach my $type (@mailings) {
 3430:             $otheremails{$type} = '';
 3431:         }
 3432:     } elsif ($position eq 'lower') {
 3433:         if (ref($settings) eq 'HASH') {
 3434:             if (ref($settings->{'lonstatus'}) eq 'HASH') {
 3435:                 %lonstatus = %{$settings->{'lonstatus'}};
 3436:             }
 3437:         }
 3438:     } else {
 3439:         @mailings = ('helpdeskmail','otherdomsmail');
 3440:         foreach my $type (@mailings) {
 3441:             $otheremails{$type} = '';
 3442:         }
 3443:         $bccemails{'helpdeskmail'} = '';
 3444:         $bccemails{'otherdomsmail'} = '';
 3445:         $includestr{'helpdeskmail'} = '';
 3446:         $includestr{'otherdomsmail'} = '';
 3447:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 3448:     }
 3449:     if (ref($settings) eq 'HASH') {
 3450:         unless (($position eq 'top') || ($position eq 'lower')) {
 3451:             foreach my $type (@mailings) {
 3452:                 if (exists($settings->{$type})) {
 3453:                     if (ref($settings->{$type}) eq 'HASH') {
 3454:                         foreach my $item (@contacts) {
 3455:                             if ($settings->{$type}{$item}) {
 3456:                                 $checked{$type}{$item} = ' checked="checked" ';
 3457:                             }
 3458:                         }
 3459:                         $otheremails{$type} = $settings->{$type}{'others'};
 3460:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3461:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 3462:                             if ($settings->{$type}{'include'} ne '') {
 3463:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3464:                                 $includestr{$type} = &unescape($includestr{$type});
 3465:                             }
 3466:                         }
 3467:                     }
 3468:                 } elsif ($type eq 'lonstatusmail') {
 3469:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3470:                 }
 3471:             }
 3472:         }
 3473:         if ($position eq 'bottom') {
 3474:             foreach my $type (@mailings) {
 3475:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 3476:                 if ($settings->{$type}{'include'} ne '') {
 3477:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3478:                     $includestr{$type} = &unescape($includestr{$type});
 3479:                 }
 3480:             }
 3481:             if (ref($settings->{'helpform'}) eq 'HASH') {
 3482:                 if (ref($fields) eq 'ARRAY') {
 3483:                     foreach my $field (@{$fields}) {
 3484:                         $currfield{$field} = $settings->{'helpform'}{$field};
 3485:                     }
 3486:                 }
 3487:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 3488:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 3489:                 } else {
 3490:                     $maxsize = '1.0';
 3491:                 }
 3492:             } else {
 3493:                 if (ref($fields) eq 'ARRAY') {
 3494:                     foreach my $field (@{$fields}) {
 3495:                         $currfield{$field} = 'yes';
 3496:                     }
 3497:                 }
 3498:                 $maxsize = '1.0';
 3499:             }
 3500:         }
 3501:     } else {
 3502:         if ($position eq 'top') {
 3503:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 3504:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 3505:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 3506:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 3507:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3508:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 3509:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 3510:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 3511:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 3512:         } elsif ($position eq 'bottom') {
 3513:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 3514:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 3515:             if (ref($fields) eq 'ARRAY') {
 3516:                 foreach my $field (@{$fields}) {
 3517:                     $currfield{$field} = 'yes';
 3518:                 }
 3519:             }
 3520:             $maxsize = '1.0';
 3521:         }
 3522:     }
 3523:     my ($titles,$short_titles) = &contact_titles();
 3524:     my $rownum = 0;
 3525:     my $css_class;
 3526:     if ($position eq 'top') {
 3527:         foreach my $item (@contacts) {
 3528:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3529:             $datatable .= '<tr'.$css_class.'>'. 
 3530:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 3531:                           '</span></td><td class="LC_right_item">'.
 3532:                           '<input type="text" name="'.$item.'" value="'.
 3533:                           $to{$item}.'" /></td></tr>';
 3534:             $rownum ++;
 3535:         }
 3536:     } elsif ($position eq 'bottom') {
 3537:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3538:         $datatable .= '<tr'.$css_class.'>'.
 3539:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 3540:                       &mt('(e-mail, subject, and description always shown)').
 3541:                       '</td><td class="LC_left_item">';
 3542:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 3543:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 3544:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 3545:             foreach my $field (@{$fields}) {
 3546:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 3547:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 3548:                     $datatable .= ' '.&mt('(logged-in users)');
 3549:                 }
 3550:                 $datatable .='</td><td>';
 3551:                 my $clickaction;
 3552:                 if ($field eq 'screenshot') {
 3553:                     $clickaction = ' onclick="screenshotSize(this);"';
 3554:                 }
 3555:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 3556:                     foreach my $option (@{$possoptions->{$field}}) {
 3557:                         my $checked;
 3558:                         if ($currfield{$field} eq $option) {
 3559:                             $checked = ' checked="checked"';
 3560:                         }
 3561:                         $datatable .= '<span class="LC_nobreak"><label>'.
 3562:                                       '<input type="radio" name="helpform_'.$field.'" '.
 3563:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 3564:                                       '</label></span>'.('&nbsp;'x2);
 3565:                     }
 3566:                 }
 3567:                 if ($field eq 'screenshot') {
 3568:                     my $display;
 3569:                     if ($currfield{$field} eq 'no') {
 3570:                         $display = ' style="display:none"';
 3571:                     }
 3572:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 3573:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 3574:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 3575:                 }
 3576:                 $datatable .= '</td></tr>';
 3577:             }
 3578:             $datatable .= '</table>';
 3579:         }
 3580:         $datatable .= '</td></tr>'."\n";
 3581:         $rownum ++;
 3582:     }
 3583:     unless (($position eq 'top') || ($position eq 'lower')) {
 3584:         foreach my $type (@mailings) {
 3585:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3586:             $datatable .= '<tr'.$css_class.'>'.
 3587:                           '<td><span class="LC_nobreak">'.
 3588:                           $titles->{$type}.': </span></td>'.
 3589:                           '<td class="LC_left_item">';
 3590:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3591:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 3592:             }
 3593:             $datatable .= '<span class="LC_nobreak">';
 3594:             foreach my $item (@contacts) {
 3595:                 $datatable .= '<label>'.
 3596:                               '<input type="checkbox" name="'.$type.'"'.
 3597:                               $checked{$type}{$item}.
 3598:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 3599:                               '</label>&nbsp;';
 3600:             }
 3601:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 3602:                           '<input type="text" name="'.$type.'_others" '.
 3603:                           'value="'.$otheremails{$type}.'"  />';
 3604:             my %locchecked;
 3605:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3606:                 foreach my $loc ('s','b') {
 3607:                     if ($includeloc{$type} eq $loc) {
 3608:                         $locchecked{$loc} = ' checked="checked"';
 3609:                         last;
 3610:                     }
 3611:                 }
 3612:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 3613:                               '<input type="text" name="'.$type.'_bcc" '.
 3614:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 3615:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 3616:                               &mt('Text automatically added to e-mail:').' '.
 3617:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 3618:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 3619:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 3620:                               ('&nbsp;'x2).
 3621:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 3622:                               '</span></fieldset>';
 3623:             }
 3624:             $datatable .= '</td></tr>'."\n";
 3625:             $rownum ++;
 3626:         }
 3627:     }
 3628:     if ($position eq 'middle') {
 3629:         my %choices;
 3630:         my $corelink = &core_link_msu();
 3631:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',$corelink);
 3632:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 3633:                                         $corelink);
 3634:         $choices{'reportstatus'} = &mt('E-mail status if errors above threshold to [_1]',$corelink);
 3635:         my @toggles = ('reporterrors','reportupdates','reportstatus');
 3636:         my %defaultchecked = ('reporterrors'  => 'on',
 3637:                               'reportupdates' => 'on',
 3638:                               'reportstatus'  => 'on');
 3639:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3640:                                                    \%choices,$rownum);
 3641:         $datatable .= $reports;
 3642:     } elsif ($position eq 'lower') {
 3643:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3644:         my ($threshold,$sysmail,%excluded,%weights);
 3645:         my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 3646:         if ($lonstatus{'threshold'} =~ /^\d+$/) {
 3647:             $threshold = $lonstatus{'threshold'};
 3648:         } else {
 3649:             $threshold = $defaults->{'threshold'};
 3650:         }
 3651:         if ($lonstatus{'sysmail'} =~ /^\d+$/) {
 3652:             $sysmail = $lonstatus{'sysmail'};
 3653:         } else {
 3654:             $sysmail = $defaults->{'sysmail'};
 3655:         }
 3656:         if (ref($lonstatus{'weights'}) eq 'HASH') {
 3657:             foreach my $type ('E','W','N','U') {
 3658:                 if ($lonstatus{'weights'}{$type} =~ /^\d+$/) {
 3659:                     $weights{$type} = $lonstatus{'weights'}{$type};
 3660:                 } else {
 3661:                     $weights{$type} = $defaults->{$type};
 3662:                 }
 3663:             }
 3664:         } else {
 3665:             foreach my $type ('E','W','N','U') {
 3666:                 $weights{$type} = $defaults->{$type};
 3667:             }
 3668:         }
 3669:         if (ref($lonstatus{'excluded'}) eq 'ARRAY') {
 3670:             if (@{$lonstatus{'excluded'}} > 0) {
 3671:                 map {$excluded{$_} = 1; } @{$lonstatus{'excluded'}};
 3672:             }
 3673:         }
 3674:         $datatable .= '<tr'.$css_class.'>'.
 3675:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 3676:                       $titles->{'errorthreshold'}.
 3677:                       '</span></td><td class="LC_left_item">'.
 3678:                       '<input type="text" name="errorthreshold" value="'.
 3679:                       $threshold.'" size="5" /></td></tr>';
 3680:         $rownum ++;
 3681:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3682:         $datatable .= '<tr'.$css_class.'>'.
 3683:                       '<td class="LC_left_item">'.
 3684:                       '<span class="LC_nobreak">'.$titles->{'errorweights'}.
 3685:                       '</span></td><td class="LC_left_item"><table><tr>';
 3686:         foreach my $type ('E','W','N','U') {
 3687:             $datatable .= '<td>'.$names->{$type}.'<br />'.
 3688:                           '<input type="text" name="errorweights_'.$type.'" value="'.
 3689:                           $weights{$type}.'" size="5" /></td>';
 3690:         }
 3691:         $datatable .= '</tr></table></tr>';
 3692:         $rownum ++;
 3693:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3694:         $datatable .= '<tr'.$css_class.'><td class="LC_left_item">'.
 3695:                       $titles->{'errorexcluded'}.'</td>'.
 3696:                       '<td class="LC_left_item"><table>';
 3697:         my $numinrow = 4;
 3698:         my @ids = sort(values(%Apache::lonnet::serverhomeIDs));
 3699:         for (my $i=0; $i<@ids; $i++) {
 3700:             my $rem = $i%($numinrow);
 3701:             if ($rem == 0) {
 3702:                 if ($i > 0) {
 3703:                     $datatable .= '</tr>';
 3704:                 }
 3705:                 $datatable .= '<tr>';
 3706:             }
 3707:             my $check;
 3708:             if ($excluded{$ids[$i]}) {
 3709:                 $check = ' checked="checked" ';
 3710:             }
 3711:             $datatable .= '<td class="LC_left_item">'.
 3712:                           '<span class="LC_nobreak"><label>'.
 3713:                           '<input type="checkbox" name="errorexcluded" '.
 3714:                           'value="'.$ids[$i].'"'.$check.' />'.
 3715:                           $ids[$i].'</label></span></td>';
 3716:         }
 3717:         my $colsleft = $numinrow - @ids%($numinrow);
 3718:         if ($colsleft > 1 ) {
 3719:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 3720:                           '&nbsp;</td>';
 3721:         } elsif ($colsleft == 1) {
 3722:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 3723:         }
 3724:         $datatable .= '</tr></table></td></tr>';
 3725:         $rownum ++;
 3726:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3727:         $datatable .= '<tr'.$css_class.'>'.
 3728:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 3729:                       $titles->{'errorsysmail'}.
 3730:                       '</span></td><td class="LC_left_item">'.
 3731:                       '<input type="text" name="errorsysmail" value="'.
 3732:                       $sysmail.'" size="5" /></td></tr>';
 3733:         $rownum ++;
 3734:     } elsif ($position eq 'bottom') {
 3735:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3736:         my (@posstypes,%usertypeshash);
 3737:         if (ref($types) eq 'ARRAY') {
 3738:             @posstypes = @{$types};
 3739:         }
 3740:         if (@posstypes) {
 3741:             if (ref($usertypes) eq 'HASH') {
 3742:                 %usertypeshash = %{$usertypes};
 3743:             }
 3744:             my @overridden;
 3745:             my $numinrow = 4;
 3746:             if (ref($settings) eq 'HASH') {
 3747:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 3748:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 3749:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 3750:                             push(@overridden,$key);
 3751:                             foreach my $item (@contacts) {
 3752:                                 if ($settings->{'overrides'}{$key}{$item}) {
 3753:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 3754:                                 }
 3755:                             }
 3756:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 3757:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 3758:                             $includeloc{'override_'.$key} = '';
 3759:                             $includestr{'override_'.$key} = '';
 3760:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 3761:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) = 
 3762:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 3763:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 3764:                             }
 3765:                         }
 3766:                     }
 3767:                 }
 3768:             }
 3769:             my $customclass = 'LC_helpdesk_override';
 3770:             my $optionsprefix = 'LC_options_helpdesk_';
 3771: 
 3772:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 3773:  
 3774:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 3775:                                          $numinrow,$othertitle,'overrides',
 3776:                                          \$rownum,$onclicktypes,$customclass);
 3777:             $rownum ++;
 3778:             $usertypeshash{'default'} = $othertitle;
 3779:             foreach my $status (@posstypes) {
 3780:                 my $css_class;
 3781:                 if ($rownum%2) {
 3782:                     $css_class = 'LC_odd_row ';
 3783:                 }
 3784:                 $css_class .= $customclass;
 3785:                 my $rowid = $optionsprefix.$status;
 3786:                 my $hidden = 1;
 3787:                 my $currstyle = 'display:none';
 3788:                 if (grep(/^\Q$status\E$/,@overridden)) {
 3789:                     $currstyle = 'display:table-row';
 3790:                     $hidden = 0;
 3791:                 }
 3792:                 my $key = 'override_'.$status;
 3793:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 3794:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 3795:                                                   $usertypeshash{$status},$css_class,$currstyle,
 3796:                                                   \@contacts,$short_titles);
 3797:                 unless ($hidden) {
 3798:                     $rownum ++;
 3799:                 }
 3800:             }
 3801:         }
 3802:     }
 3803:     $$rowtotal += $rownum;
 3804:     return $datatable;
 3805: }
 3806: 
 3807: sub core_link_msu {
 3808:     return &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 3809:                                           &mt('LON-CAPA core group - MSU'),600,500);
 3810: }
 3811: 
 3812: sub overridden_helpdesk {
 3813:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 3814:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 3815:     my $class = 'LC_left_item';
 3816:     if ($css_class) {
 3817:         $css_class = ' class="'.$css_class.'"';
 3818:     }
 3819:     if ($rowid) {
 3820:         $rowid = ' id="'.$rowid.'"';
 3821:     }
 3822:     if ($rowstyle) {
 3823:         $rowstyle = ' style="'.$rowstyle.'"';
 3824:     }
 3825:     my ($output,$description);
 3826:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 3827:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 3828:               "<td>$description</td>\n".
 3829:               '<td class="'.$class.'" colspan="2">'.
 3830:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 3831:               '<span class="LC_nobreak">';
 3832:     if (ref($contacts) eq 'ARRAY') {
 3833:         foreach my $item (@{$contacts}) {
 3834:             my $check;
 3835:             if (ref($checked) eq 'HASH') {
 3836:                $check = $checked->{$item};
 3837:             }
 3838:             my $title;
 3839:             if (ref($short_titles) eq 'HASH') {
 3840:                 $title = $short_titles->{$item}; 
 3841:             }
 3842:             $output .= '<label>'.
 3843:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 3844:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 3845:         }
 3846:     }
 3847:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 3848:                '<input type="text" name="override_'.$type.'_others" '.
 3849:                'value="'.$otheremails.'"  />';
 3850:     my %locchecked;
 3851:     foreach my $loc ('s','b') {
 3852:         if ($includeloc eq $loc) {
 3853:             $locchecked{$loc} = ' checked="checked"';
 3854:             last;
 3855:         }
 3856:     }
 3857:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 3858:                '<input type="text" name="override_'.$type.'_bcc" '.
 3859:                'value="'.$bccemails.'"  /></fieldset>'.
 3860:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 3861:                &mt('Text automatically added to e-mail:').' '.
 3862:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 3863:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 3864:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 3865:                ('&nbsp;'x2).
 3866:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 3867:                '</span></fieldset>'.
 3868:                '</td></tr>'."\n";
 3869:     return $output;
 3870: }
 3871: 
 3872: sub contacts_javascript {
 3873:     return <<"ENDSCRIPT";
 3874: 
 3875: <script type="text/javascript">
 3876: // <![CDATA[
 3877: 
 3878: function screenshotSize(field) {
 3879:     if (document.getElementById('help_screenshotsize')) {
 3880:         if (field.value == 'no') {
 3881:             document.getElementById('help_screenshotsize').style.display="none";
 3882:         } else {
 3883:             document.getElementById('help_screenshotsize').style.display="";
 3884:         }
 3885:     }
 3886:     return;
 3887: }
 3888: 
 3889: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 3890:     if (form.elements[checkbox].length != undefined) {
 3891:         var count = 0;
 3892:         if (docount) {
 3893:             for (var i=0; i<form.elements[checkbox].length; i++) {
 3894:                 if (form.elements[checkbox][i].checked) {
 3895:                     count ++;
 3896:                 }
 3897:             }
 3898:         }
 3899:         for (var i=0; i<form.elements[checkbox].length; i++) {
 3900:             var type = form.elements[checkbox][i].value;
 3901:             if (document.getElementById(prefix+type)) {
 3902:                 if (form.elements[checkbox][i].checked) {
 3903:                     document.getElementById(prefix+type).style.display = 'table-row';
 3904:                     if (count % 2 == 1) {
 3905:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 3906:                     } else {
 3907:                         document.getElementById(prefix+type).className = target;
 3908:                     }
 3909:                     count ++;
 3910:                 } else {
 3911:                     document.getElementById(prefix+type).style.display = 'none';
 3912:                 }
 3913:             }
 3914:         }
 3915:     }
 3916:     return;
 3917: }
 3918: 
 3919: 
 3920: // ]]>
 3921: </script>
 3922: 
 3923: ENDSCRIPT
 3924: }
 3925: 
 3926: sub print_helpsettings {
 3927:     my ($position,$dom,$settings,$rowtotal) = @_;
 3928:     my $confname = $dom.'-domainconfig';
 3929:     my $formname = 'display';
 3930:     my ($datatable,$itemcount);
 3931:     if ($position eq 'top') {
 3932:         $itemcount = 1;
 3933:         my (%choices,%defaultchecked,@toggles);
 3934:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 3935:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 3936:                                      &mt('LON-CAPA bug tracker'),600,500));
 3937:         %defaultchecked = ('submitbugs' => 'on');
 3938:         @toggles = ('submitbugs');
 3939:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3940:                                                      \%choices,$itemcount);
 3941:         $$rowtotal ++;
 3942:     } else {
 3943:         my $css_class;
 3944:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 3945:         my (%customroles,%ordered,%current);
 3946:         if (ref($settings) eq 'HASH') {
 3947:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 3948:                 %current = %{$settings->{'adhoc'}};
 3949:             }
 3950:         }
 3951:         my $count = 0;
 3952:         foreach my $key (sort(keys(%existing))) {
 3953:             if ($key=~/^rolesdef\_(\w+)$/) {
 3954:                 my $rolename = $1;
 3955:                 my (%privs,$order);
 3956:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 3957:                 $customroles{$rolename} = \%privs;
 3958:                 if (ref($current{$rolename}) eq 'HASH') {
 3959:                     $order = $current{$rolename}{'order'};
 3960:                 }
 3961:                 if ($order eq '') {
 3962:                     $order = $count;
 3963:                 }
 3964:                 $ordered{$order} = $rolename;
 3965:                 $count++;
 3966:             }
 3967:         }
 3968:         my $maxnum = scalar(keys(%ordered));
 3969:         my @roles_by_num = ();
 3970:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3971:             push(@roles_by_num,$item);
 3972:         }
 3973:         my $context = 'domprefs';
 3974:         my $crstype = 'Course';
 3975:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3976:         my @accesstypes = ('all','dh','da','none');
 3977:         my ($numstatustypes,@jsarray);
 3978:         if (ref($types) eq 'ARRAY') {
 3979:             if (@{$types} > 0) {
 3980:                 $numstatustypes = scalar(@{$types});
 3981:                 push(@accesstypes,'status');
 3982:                 @jsarray = ('bystatus');
 3983:             }
 3984:         }
 3985:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 3986:         if (keys(%domhelpdesk)) {
 3987:             push(@accesstypes,('inc','exc'));
 3988:             push(@jsarray,('notinc','notexc'));
 3989:         }
 3990:         my $hiddenstr = join("','",@jsarray);
 3991:         my $context = 'domprefs';
 3992:         my $crstype = 'Course';
 3993:         my $prefix = 'helproles_';
 3994:         my $add_class = 'LC_hidden';
 3995:         foreach my $num (@roles_by_num) {
 3996:             my $role = $ordered{$num};
 3997:             my ($desc,$access,@statuses);
 3998:             if (ref($current{$role}) eq 'HASH') {
 3999:                 $desc = $current{$role}{'desc'};
 4000:                 $access = $current{$role}{'access'};
 4001:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 4002:                     @statuses = @{$current{$role}{'insttypes'}};
 4003:                 }
 4004:             }
 4005:             if ($desc eq '') {
 4006:                 $desc = $role;
 4007:             }
 4008:             my $identifier = 'custhelp'.$num;
 4009:             my %full=();
 4010:             my %levels= (
 4011:                          course => {},
 4012:                          domain => {},
 4013:                          system => {},
 4014:                         );
 4015:             my %levelscurrent=(
 4016:                                course => {},
 4017:                                domain => {},
 4018:                                system => {},
 4019:                               );
 4020:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 4021:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4022:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4023:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 4024:             $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><b>'.$role.'</b><br />'.
 4025:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 4026:             for (my $k=0; $k<=$maxnum; $k++) {
 4027:                 my $vpos = $k+1;
 4028:                 my $selstr;
 4029:                 if ($k == $num) {
 4030:                     $selstr = ' selected="selected" ';
 4031:                 }
 4032:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4033:             }
 4034:             $datatable .= '</select>'.('&nbsp;'x2).
 4035:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 4036:                           '</td>'.
 4037:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4038:                           &mt('Name shown to users:').
 4039:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 4040:                           '</fieldset>'.
 4041:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 4042:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 4043:                           '<fieldset>'.
 4044:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 4045:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4046:                                                                    \%levelscurrent,$identifier,
 4047:                                                                    'LC_hidden',$prefix.$num.'_privs').
 4048:                           '</fieldset></td>';
 4049:             $itemcount ++;
 4050:         }
 4051:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4052:         my $newcust = 'custhelp'.$count;
 4053:         my (%privs,%levelscurrent);
 4054:         my %full=();
 4055:         my %levels= (
 4056:                      course => {},
 4057:                      domain => {},
 4058:                      system => {},
 4059:                     );
 4060:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4061:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4062:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 4063:         $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><span class="LC_nobreak"><label>'.
 4064:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 4065:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 4066:         for (my $k=0; $k<$maxnum+1; $k++) {
 4067:             my $vpos = $k+1;
 4068:             my $selstr;
 4069:             if ($k == $maxnum) {
 4070:                 $selstr = ' selected="selected" ';
 4071:             }
 4072:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4073:         }
 4074:         $datatable .= '</select>&nbsp;'."\n".
 4075:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 4076:                       '</label></span></td>'.
 4077:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4078:                       '<span class="LC_nobreak">'.
 4079:                       &mt('Internal name:').
 4080:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 4081:                       '</span>'.('&nbsp;'x4).
 4082:                       '<span class="LC_nobreak">'.
 4083:                       &mt('Name shown to users:').
 4084:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 4085:                       '</span></fieldset>'.
 4086:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 4087:                                              $usertypes,$types,\%domhelpdesk).
 4088:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 4089:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 4090:                                                                 \@templateroles,$newcust).
 4091:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 4092:                                                                \%levelscurrent,$newcust).
 4093:                       '</fieldset>'.
 4094:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 4095:                       '</td></tr>';
 4096:         $count ++;
 4097:         $$rowtotal += $count;
 4098:     }
 4099:     return $datatable;
 4100: }
 4101: 
 4102: sub adhocbutton {
 4103:     my ($prefix,$num,$field,$visibility) = @_;
 4104:     my %lt = &Apache::lonlocal::texthash(
 4105:                                           show => 'Show details',
 4106:                                           hide => 'Hide details',
 4107:                                         );
 4108:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 4109:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 4110:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 4111:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 4112: }
 4113: 
 4114: sub helpsettings_javascript {
 4115:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 4116:     return unless(ref($roles_by_num) eq 'ARRAY');
 4117:     my %html_js_lt = &Apache::lonlocal::texthash(
 4118:                                           show => 'Show details',
 4119:                                           hide => 'Hide details',
 4120:                                         );
 4121:     &html_escape(\%html_js_lt);
 4122:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 4123:     return <<"ENDSCRIPT";
 4124: <script type="text/javascript">
 4125: // <![CDATA[
 4126: 
 4127: function reorderHelpRoles(form,item) {
 4128:     var changedVal;
 4129: $jstext
 4130:     var newpos = 'helproles_${total}_pos';
 4131:     var maxh = 1 + $total;
 4132:     var current = new Array();
 4133:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 4134:     if (item == newpos) {
 4135:         changedVal = newitemVal;
 4136:     } else {
 4137:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 4138:         current[newitemVal] = newpos;
 4139:     }
 4140:     for (var i=0; i<helproles.length; i++) {
 4141:         var elementName = 'helproles_'+helproles[i]+'_pos';
 4142:         if (elementName != item) {
 4143:             if (form.elements[elementName]) {
 4144:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 4145:                 current[currVal] = elementName;
 4146:             }
 4147:         }
 4148:     }
 4149:     var oldVal;
 4150:     for (var j=0; j<maxh; j++) {
 4151:         if (current[j] == undefined) {
 4152:             oldVal = j;
 4153:         }
 4154:     }
 4155:     if (oldVal < changedVal) {
 4156:         for (var k=oldVal+1; k<=changedVal ; k++) {
 4157:            var elementName = current[k];
 4158:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 4159:         }
 4160:     } else {
 4161:         for (var k=changedVal; k<oldVal; k++) {
 4162:             var elementName = current[k];
 4163:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 4164:         }
 4165:     }
 4166:     return;
 4167: }
 4168: 
 4169: function helpdeskAccess(num) {
 4170:     var curraccess = null;
 4171:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 4172:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 4173:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 4174:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 4175:             }
 4176:         }
 4177:     }
 4178:     var shown = Array();
 4179:     var hidden = Array();
 4180:     if (curraccess == 'none') {
 4181:         hidden = Array('$hiddenstr');
 4182:     } else {
 4183:         if (curraccess == 'status') {
 4184:             shown = Array('bystatus');
 4185:             hidden = Array('notinc','notexc');
 4186:         } else {
 4187:             if (curraccess == 'exc') {
 4188:                 shown = Array('notexc');
 4189:                 hidden = Array('notinc','bystatus');
 4190:             }
 4191:             if (curraccess == 'inc') {
 4192:                 shown = Array('notinc');
 4193:                 hidden = Array('notexc','bystatus');
 4194:             }
 4195:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 4196:                 hidden = Array('notinc','notexc','bystatus');
 4197:             }
 4198:         }
 4199:     }
 4200:     if (hidden.length > 0) {
 4201:         for (var i=0; i<hidden.length; i++) {
 4202:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 4203:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 4204:             }
 4205:         }
 4206:     }
 4207:     if (shown.length > 0) {
 4208:         for (var i=0; i<shown.length; i++) {
 4209:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 4210:                 if (shown[i] == 'privs') {
 4211:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 4212:                 } else {
 4213:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 4214:                 }
 4215:             }
 4216:         }
 4217:     }
 4218:     return;
 4219: }
 4220: 
 4221: function toggleHelpdeskItem(num,field) {
 4222:     if (document.getElementById('helproles_'+num+'_'+field)) {
 4223:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 4224:             document.getElementById('helproles_'+num+'_'+field).className =
 4225:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 4226:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4227:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 4228:             }
 4229:         } else {
 4230:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 4231:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4232:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 4233:             }
 4234:         }
 4235:     }
 4236:     return;
 4237: }
 4238: 
 4239: // ]]>
 4240: </script>
 4241: 
 4242: ENDSCRIPT
 4243: }
 4244: 
 4245: sub helpdeskroles_access {
 4246:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 4247:         $usertypes,$types,$domhelpdesk) = @_;
 4248:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 4249:     my %lt = &Apache::lonlocal::texthash(
 4250:                     'rou'    => 'Role usage',
 4251:                     'whi'    => 'Which helpdesk personnel may use this role?',
 4252:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 4253:                     'dh'     => 'All with domain helpdesk role',
 4254:                     'da'     => 'All with domain helpdesk assistant role',
 4255:                     'none'   => 'None',
 4256:                     'status' => 'Determined based on institutional status',
 4257:                     'inc'    => 'Include all, but exclude specific personnel',
 4258:                     'exc'    => 'Exclude all, but include specific personnel',
 4259:                   );
 4260:     my %usecheck = (
 4261:                      all => ' checked="checked"',
 4262:                    );
 4263:     my %displaydiv = (
 4264:                       status => 'none',
 4265:                       inc    => 'none',
 4266:                       exc    => 'none',
 4267:                       priv   => 'block',
 4268:                      );
 4269:     my $output;
 4270:     if (ref($current) eq 'HASH') {
 4271:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 4272:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 4273:                 $usecheck{$current->{access}} = $usecheck{'all'};
 4274:                 delete($usecheck{'all'});
 4275:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 4276:                     my $access = $1;
 4277:                     $displaydiv{$access} = 'inline';
 4278:                 } elsif ($current->{access} eq 'none') {
 4279:                     $displaydiv{'priv'} = 'none';
 4280:                 }
 4281:             }
 4282:         }
 4283:     }
 4284:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 4285:               '<p>'.$lt{'whi'}.'</p>';
 4286:     foreach my $access (@{$accesstypes}) {
 4287:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 4288:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 4289:                    $lt{$access}.'</label>';
 4290:         if ($access eq 'status') {
 4291:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 4292:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 4293:                                                                  $othertitle,$usertypes,$types).
 4294:                        '</div>';
 4295:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 4296:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 4297:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4298:                        '</div>';
 4299:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 4300:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 4301:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4302:                        '</div>';
 4303:         }
 4304:         $output .= '</p>';
 4305:     }
 4306:     $output .= '</fieldset>';
 4307:     return $output;
 4308: }
 4309: 
 4310: sub radiobutton_prefs {
 4311:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 4312:         $additional,$align) = @_;
 4313:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 4314:                    (ref($choices) eq 'HASH'));
 4315: 
 4316:     my (%checkedon,%checkedoff,$datatable,$css_class);
 4317: 
 4318:     foreach my $item (@{$toggles}) {
 4319:         if ($defaultchecked->{$item} eq 'on') {
 4320:             $checkedon{$item} = ' checked="checked" ';
 4321:             $checkedoff{$item} = ' ';
 4322:         } elsif ($defaultchecked->{$item} eq 'off') {
 4323:             $checkedoff{$item} = ' checked="checked" ';
 4324:             $checkedon{$item} = ' ';
 4325:         }
 4326:     }
 4327:     if (ref($settings) eq 'HASH') {
 4328:         foreach my $item (@{$toggles}) {
 4329:             if ($settings->{$item} eq '1') {
 4330:                 $checkedon{$item} =  ' checked="checked" ';
 4331:                 $checkedoff{$item} = ' ';
 4332:             } elsif ($settings->{$item} eq '0') {
 4333:                 $checkedoff{$item} =  ' checked="checked" ';
 4334:                 $checkedon{$item} = ' ';
 4335:             }
 4336:         }
 4337:     }
 4338:     if ($onclick) {
 4339:         $onclick = ' onclick="'.$onclick.'"';
 4340:     }
 4341:     foreach my $item (@{$toggles}) {
 4342:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4343:         $datatable .=
 4344:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 4345:             '<span class="LC_nobreak">'.$choices->{$item}.
 4346:             '</span></td>';
 4347:         if ($align eq 'left') {
 4348:             $datatable .= '<td class="LC_left_item">';
 4349:         } else {
 4350:             $datatable .= '<td class="LC_right_item">';
 4351:         }
 4352:         $datatable .=
 4353:             '<span class="LC_nobreak">'.
 4354:             '<label><input type="radio" name="'.
 4355:             $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 4356:             '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 4357:             $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>'.
 4358:             '</span>'.$additional.
 4359:             '</td>'.
 4360:             '</tr>';
 4361:         $itemcount ++;
 4362:     }
 4363:     return ($datatable,$itemcount);
 4364: }
 4365: 
 4366: sub print_ltitools {
 4367:     my ($dom,$settings,$rowtotal) = @_;
 4368:     my $rownum = 0;
 4369:     my $css_class;
 4370:     my $itemcount = 1;
 4371:     my $maxnum = 0;
 4372:     my %ordered;
 4373:     if (ref($settings) eq 'HASH') {
 4374:         foreach my $item (keys(%{$settings})) {
 4375:             if (ref($settings->{$item}) eq 'HASH') {
 4376:                 my $num = $settings->{$item}{'order'};
 4377:                 $ordered{$num} = $item;
 4378:             }
 4379:         }
 4380:     }
 4381:     my $confname = $dom.'-domainconfig';
 4382:     my $switchserver = &check_switchserver($dom,$confname);
 4383:     my $maxnum = scalar(keys(%ordered));
 4384:     my $datatable;
 4385:     my %lt = &ltitools_names();
 4386:     my @courseroles = ('cc','in','ta','ep','st');
 4387:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
 4388:     my @fields = ('fullname','firstname','lastname','email','roles','user');
 4389:     if (keys(%ordered)) {
 4390:         my @items = sort { $a <=> $b } keys(%ordered);
 4391:         for (my $i=0; $i<@items; $i++) {
 4392:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4393:             my $item = $ordered{$items[$i]};
 4394:             my ($title,$key,$secret,$url,$lifetime,$imgsrc,%sigsel);
 4395:             if (ref($settings->{$item}) eq 'HASH') {
 4396:                 $title = $settings->{$item}->{'title'};
 4397:                 $url = $settings->{$item}->{'url'};
 4398:                 $key = $settings->{$item}->{'key'};
 4399:                 $secret = $settings->{$item}->{'secret'};
 4400:                 $lifetime = $settings->{$item}->{'lifetime'};
 4401:                 my $image = $settings->{$item}->{'image'};
 4402:                 if ($image ne '') {
 4403:                     $imgsrc = '<img src="'.$image.'" alt="'.&mt('Tool Provider icon').'" />';
 4404:                 }
 4405:                 if ($settings->{$item}->{'sigmethod'} eq 'HMAC-256') {
 4406:                     $sigsel{'HMAC-256'} = ' selected="selected"';
 4407:                 } else {
 4408:                     $sigsel{'HMAC-SHA1'} = ' selected="selected"';
 4409:                 }
 4410:             }
 4411:             my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_".$item."'".');"';
 4412:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 4413:                          .'<select name="ltitools_'.$item.'"'.$chgstr.'>';
 4414:             for (my $k=0; $k<=$maxnum; $k++) {
 4415:                 my $vpos = $k+1;
 4416:                 my $selstr;
 4417:                 if ($k == $i) {
 4418:                     $selstr = ' selected="selected" ';
 4419:                 }
 4420:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4421:             }
 4422:             $datatable .= '</select>'.('&nbsp;'x2).
 4423:                 '<label><input type="checkbox" name="ltitools_del" value="'.$item.'" />'.
 4424:                 &mt('Delete?').'</label></span></td>'.
 4425:                 '<td colspan="2">'.
 4426:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 4427:                 '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_title_'.$i.'" value="'.$title.'" /></span> '.
 4428:                 ('&nbsp;'x2).
 4429:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_version_'.$i.'">'.
 4430:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 4431:                 ('&nbsp;'x2).
 4432:                 '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_msgtype_'.$i.'">'.
 4433:                 '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 4434:                 ('&nbsp;'x2).
 4435:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_sigmethod_'.$i.'">'.
 4436:                 '<option value="HMAC-SHA1"'.$sigsel{'HMAC-SHA1'}.'>HMAC-SHA1</option>'.
 4437:                 '<option value="HMAC-SHA256"'.$sigsel{'HMAC-SHA256'}.'>HMAC-SHA256</option></select></span>'.
 4438:                 '<br /><br />'.
 4439:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_url_'.$i.'"'.
 4440:                 ' value="'.$url.'" /></span>'.
 4441:                 ('&nbsp;'x2).
 4442:                 '<span class="LC_nobreak">'.$lt{'key'}.':'.
 4443:                 '<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" /></span> '.
 4444:                 ('&nbsp;'x2).
 4445:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':'.
 4446:                 '<input type="text" size="5" name="ltitools_lifetime_'.$i.'" value="'.$lifetime.'" /></span> '.
 4447:                 ('&nbsp;'x2).
 4448:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 4449:                 '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="'.$secret.'" />'.
 4450:                 '<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>'.
 4451:                 '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span>'.
 4452:                 '</fieldset>'.
 4453:                 '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 4454:                 '<span class="LC_nobreak">'.&mt('Display target:');
 4455:             my %currdisp;
 4456:             if (ref($settings->{$item}->{'display'}) eq 'HASH') {
 4457:                 if ($settings->{$item}->{'display'}->{'target'} eq 'window') {
 4458:                     $currdisp{'window'} = ' checked="checked"';
 4459:                 } elsif ($settings->{$item}->{'display'}->{'target'} eq 'tab') {
 4460:                     $currdisp{'tab'} = ' checked="checked"';
 4461:                 } else {
 4462:                     $currdisp{'iframe'} = ' checked="checked"';
 4463:                 }
 4464:                 if ($settings->{$item}->{'display'}->{'width'} =~ /^(\d+)$/) {
 4465:                     $currdisp{'width'} = $1;
 4466:                 }
 4467:                 if ($settings->{$item}->{'display'}->{'height'} =~ /^(\d+)$/) {
 4468:                      $currdisp{'height'} = $1;
 4469:                 }
 4470:                 $currdisp{'linktext'} = $settings->{$item}->{'display'}->{'linktext'};
 4471:                 $currdisp{'explanation'} = $settings->{$item}->{'display'}->{'explanation'};
 4472:             } else {
 4473:                 $currdisp{'iframe'} = ' checked="checked"';
 4474:             }
 4475:             foreach my $disp ('iframe','tab','window') {
 4476:                 $datatable .= '<label><input type="radio" name="ltitools_target_'.$i.'" value="'.$disp.'"'.$currdisp{$disp}.' />'.
 4477:                               $lt{$disp}.'</label>'.('&nbsp;'x2);
 4478:             }
 4479:             $datatable .= ('&nbsp;'x4);
 4480:             foreach my $dimen ('width','height') {
 4481:                 $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 4482:                               '<input type="text" name="ltitools_'.$dimen.'_'.$i.'" size="5" value="'.$currdisp{$dimen}.'" /></label>'.
 4483:                               ('&nbsp;'x2);
 4484:             }
 4485:             $datatable .= '</span><br />'.
 4486:                           '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 4487:                           '<input type="text" name="ltitools_linktext_'.$i.'" size="25" value="'.$currdisp{'linktext'}.'" /></div>'.
 4488:                           '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 4489:                           '<textarea name="ltitools_explanation_'.$i.'" rows="5" cols="40">'.$currdisp{'explanation'}.
 4490:                           '</textarea></div><div style=""></div><br />';
 4491:             my %units = (
 4492:                           'passback' => 'days',
 4493:                           'roster'   => 'seconds',
 4494:                         );
 4495:             foreach my $extra ('passback','roster') {
 4496:                 my $validsty = 'none';
 4497:                 my $currvalid;
 4498:                 my $checkedon = '';
 4499:                 my $checkedoff = ' checked="checked"';
 4500:                 if ($settings->{$item}->{$extra}) {
 4501:                     $checkedon = $checkedoff;
 4502:                     $checkedoff = '';
 4503:                     $validsty = 'inline-block';
 4504:                     if ($settings->{$item}->{$extra.'valid'} =~ /^\d+\.?\d*$/) {
 4505:                         $currvalid = $settings->{$item}->{$extra.'valid'};
 4506:                     }
 4507:                 }
 4508:                 my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','$i'".');"';
 4509:                 $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 4510:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="0"'.$checkedoff.$onclick.' />'.
 4511:                               &mt('No').'</label>'.('&nbsp;'x2).
 4512:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="1"'.$checkedon.$onclick.' />'.
 4513:                               &mt('Yes').'</label></span></div>'.
 4514:                               '<div class="LC_floatleft" style="display:'.$validsty.';" id="ltitools_'.$extra.'time_'.$i.'">'.
 4515:                               '<span class="LC_nobreak">'.
 4516:                               &mt("at least [_1] $units{$extra} after launch",
 4517:                                   '<input type="text" name="ltitools_'.$extra.'valid_'.$i.'" value="'.$currvalid.'" />').
 4518:                               '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 4519:             }
 4520:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 4521:             if ($imgsrc) {
 4522:                 $datatable .= $imgsrc.
 4523:                               '<label><input type="checkbox" name="ltitools_image_del"'.
 4524:                               ' value="'.$item.'" />'.&mt('Delete?').'</label></span> '.
 4525:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 4526:             } else {
 4527:                 $datatable .= '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 4528:             }
 4529:             if ($switchserver) {
 4530:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 4531:             } else {
 4532:                 $datatable .= '<input type="file" name="ltitools_image_'.$i.'" value="" />';
 4533:             }
 4534:             $datatable .= '</span></fieldset>';
 4535:             my (%checkedfields,%rolemaps,$userincdom);
 4536:             if (ref($settings->{$item}) eq 'HASH') {
 4537:                 if (ref($settings->{$item}->{'fields'}) eq 'HASH') {
 4538:                     %checkedfields = %{$settings->{$item}->{'fields'}};
 4539:                 }
 4540:                 $userincdom = $settings->{$item}->{'incdom'};
 4541:                 if (ref($settings->{$item}->{'roles'}) eq 'HASH') {
 4542:                     %rolemaps = %{$settings->{$item}->{'roles'}};
 4543:                     $checkedfields{'roles'} = 1;
 4544:                 }
 4545:             }
 4546:             $datatable .= '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 4547:                           '<span class="LC_nobreak">';
 4548:             my $userfieldstyle = 'display:none;';
 4549:             my $seluserdom = '';
 4550:             my $unseluserdom = ' selected="selected"';
 4551:             foreach my $field (@fields) {
 4552:                 my ($checked,$onclick,$id,$spacer);
 4553:                 if ($checkedfields{$field}) {
 4554:                     $checked = ' checked="checked"';
 4555:                 }
 4556:                 if ($field eq 'user') {
 4557:                     $id = ' id="ltitools_user_field_'.$i.'"';
 4558:                     $onclick = ' onclick="toggleLTITools(this.form,'."'$field','$i'".')"';
 4559:                     if ($checked) {
 4560:                         $userfieldstyle = 'display:inline-block';
 4561:                         if ($userincdom) {
 4562:                             $seluserdom = $unseluserdom;
 4563:                             $unseluserdom = '';
 4564:                         }
 4565:                     }
 4566:                 } else {
 4567:                     $spacer = ('&nbsp;' x2);
 4568:                 }
 4569:                 $datatable .= '<label>'.
 4570:                               '<input type="checkbox" name="ltitools_fields_'.$i.'" value="'.$field.'"'.$id.$checked.$onclick.' />'.
 4571:                               $lt{$field}.'</label>'.$spacer;
 4572:             }
 4573:             $datatable .= '</span>';
 4574:             $datatable .= '<div style="'.$userfieldstyle.'" id="ltitools_user_div_'.$i.'">'.
 4575:                           '<span class="LC_nobreak"> : '.
 4576:                           '<select name="ltitools_userincdom_'.$i.'">'.
 4577:                           '<option value="">'.&mt('Select').'</option>'.
 4578:                           '<option value="0"'.$unseluserdom.'>'.&mt('username').'</option>'.
 4579:                           '<option value="1"'.$seluserdom.'>'.&mt('username:domain').'</option>'.
 4580:                           '</select></span></div>';
 4581:             $datatable .= '</fieldset>'.
 4582:                           '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 4583:             foreach my $role (@courseroles) {
 4584:                 my ($selected,$selectnone);
 4585:                 if (!$rolemaps{$role}) {
 4586:                     $selectnone = ' selected="selected"';
 4587:                 }
 4588:                 $datatable .= '<td style="text-align: center">'. 
 4589:                               &Apache::lonnet::plaintext($role,'Course').'<br />'.
 4590:                               '<select name="ltitools_roles_'.$role.'_'.$i.'">'.
 4591:                               '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 4592:                 foreach my $ltirole (@ltiroles) {
 4593:                     unless ($selectnone) {
 4594:                         if ($rolemaps{$role} eq $ltirole) {
 4595:                             $selected = ' selected="selected"';
 4596:                         } else {
 4597:                             $selected = '';
 4598:                         }
 4599:                     }
 4600:                     $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 4601:                 }
 4602:                 $datatable .= '</select></td>';
 4603:             }
 4604:             $datatable .= '</tr></table></fieldset>';
 4605:             my %courseconfig;
 4606:             if (ref($settings->{$item}) eq 'HASH') {
 4607:                 if (ref($settings->{$item}->{'crsconf'}) eq 'HASH') {
 4608:                     %courseconfig = %{$settings->{$item}->{'crsconf'}};
 4609:                 }
 4610:             }
 4611:             $datatable .= '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 4612:             foreach my $item ('label','title','target','linktext','explanation','append') {
 4613:                 my $checked;
 4614:                 if ($courseconfig{$item}) {
 4615:                     $checked = ' checked="checked"';
 4616:                 }
 4617:                 $datatable .= '<label>'.
 4618:                        '<input type="checkbox" name="ltitools_courseconfig_'.$i.'" value="'.$item.'"'.$checked.' />'.
 4619:                        $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 4620:             }
 4621:             $datatable .= '</span></fieldset>'.
 4622:                           '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 4623:                           '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>';
 4624:             if (ref($settings->{$item}->{'custom'}) eq 'HASH') {
 4625:                 my %custom = %{$settings->{$item}->{'custom'}};
 4626:                 if (keys(%custom) > 0) {
 4627:                     foreach my $key (sort(keys(%custom))) {
 4628:                         $datatable .= '<tr><td><span class="LC_nobreak">'.
 4629:                                       '<label><input type="checkbox" name="ltitools_customdel_'.$i.'" value="'.
 4630:                                       $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 4631:                                       '<td><input type="text" name="ltitools_customval_'.$key.'_'.$i.'"'.
 4632:                                       ' value="'.$custom{$key}.'" /></td></tr>';
 4633:                     }
 4634:                 }
 4635:             }
 4636:             $datatable .= '<tr><td><span class="LC_nobreak">'.
 4637:                           '<label><input type="checkbox" name="ltitools_customadd" value="'.$i.'" />'.
 4638:                           &mt('Add').'</label></span></td><td><input type="text" name="ltitools_custom_name_'.$i.'" />'.
 4639:                           '</td><td><input type="text" name="ltitools_custom_value_'.$i.'" /></td></tr>';
 4640:             $datatable .= '</table></fieldset></td></tr>'."\n";
 4641:             $itemcount ++;
 4642:         }
 4643:     }
 4644:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4645:     my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_add_pos'".');"';
 4646:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 4647:                   '<input type="hidden" name="ltitools_maxnum" value="'.$maxnum.'" />'."\n".
 4648:                   '<select name="ltitools_add_pos"'.$chgstr.'>';
 4649:     for (my $k=0; $k<$maxnum+1; $k++) {
 4650:         my $vpos = $k+1;
 4651:         my $selstr;
 4652:         if ($k == $maxnum) {
 4653:             $selstr = ' selected="selected" ';
 4654:         }
 4655:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4656:     }
 4657:     $datatable .= '</select>&nbsp;'."\n".
 4658:                   '<input type="checkbox" name="ltitools_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 4659:                   '<td colspan="2">'.
 4660:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 4661:                   '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_add_title" value="" /></span> '."\n".
 4662:                   ('&nbsp;'x2).
 4663:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_add_version">'.
 4664:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 4665:                   ('&nbsp;'x2).
 4666:                   '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_add_msgtype">'.
 4667:                   '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 4668:                   '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_add_sigmethod">'.
 4669:                   '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 4670:                   '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 4671:                   '<br />'.
 4672:                   '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_add_url" value="" /></span> '."\n".
 4673:                   ('&nbsp;'x2).
 4674:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="ltitools_add_key" value="" /></span> '."\n".
 4675:                   ('&nbsp;'x2).
 4676:                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="ltitools_add_lifetime" value="300" /></span> '."\n".
 4677:                   ('&nbsp;'x2).
 4678:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="ltitools_add_secret" value="" />'.
 4679:                   '<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".
 4680:                   '</fieldset>'.
 4681:                   '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 4682:                   '<span class="LC_nobreak">'.&mt('Display target:');
 4683:     my %defaultdisp;
 4684:     $defaultdisp{'iframe'} = ' checked="checked"';
 4685:     foreach my $disp ('iframe','tab','window') {
 4686:         $datatable .= '<label><input type="radio" name="ltitools_add_target" value="'.$disp.'"'.$defaultdisp{$disp}.' />'.
 4687:                       $lt{$disp}.'</label>'.('&nbsp;'x2);
 4688:     }
 4689:     $datatable .= ('&nbsp;'x4);
 4690:     foreach my $dimen ('width','height') {
 4691:         $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 4692:                       '<input type="text" name="ltitools_add_'.$dimen.'" size="5" /></label>'.
 4693:                       ('&nbsp;'x2);
 4694:     }
 4695:     $datatable .= '</span><br />'.
 4696:                   '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 4697:                   '<input type="text" name="ltitools_add_linktext" size="5" /></div>'.
 4698:                   '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 4699:                   '<textarea name="ltitools_add_explanation" rows="5" cols="40"></textarea>'.
 4700:                   '</div><div style=""></div><br />';
 4701:     my %units = (
 4702:                   'passback' => 'days',
 4703:                   'roster'   => 'seconds',
 4704:                 );
 4705:     my %defaulttimes = (
 4706:                      'passback' => '7',
 4707:                      'roster'   => '300',
 4708:                    );
 4709:     foreach my $extra ('passback','roster') {
 4710:         my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','add'".');"';
 4711:         $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 4712:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="0" checked="checked"'.$onclick.' />'.
 4713:                       &mt('No').'</label></span>'.('&nbsp;'x2).'<span class="LC_nobreak">'.
 4714:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="1"'.$onclick.' />'.
 4715:                       &mt('Yes').'</label></span></div>'.
 4716:                       '<div class="LC_floatleft" style="display:none;" id="ltitools_'.$extra.'time_add">'.
 4717:                       '<span class="LC_nobreak">'.
 4718:                       &mt("at least [_1] $units{$extra} after launch",
 4719:                           '<input type="text" name="ltitools_'.$extra.'valid_add" value="'.$defaulttimes{$extra}.'" />').
 4720:                       '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 4721:     }
 4722:     $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;'.
 4723:                   '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 4724:     if ($switchserver) {
 4725:         $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 4726:     } else {
 4727:         $datatable .= '<input type="file" name="ltitools_add_image" value="" />';
 4728:     }
 4729:     $datatable .= '</span></fieldset>'.
 4730:                   '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 4731:                   '<span class="LC_nobreak">';
 4732:     foreach my $field (@fields) {
 4733:         my ($id,$onclick,$spacer);
 4734:         if ($field eq 'user') {
 4735:             $id = ' id="ltitools_user_field_add"';
 4736:             $onclick = ' onclick="toggleLTITools(this.form,'."'$field','add'".')"';
 4737:         } else {
 4738:             $spacer = ('&nbsp;' x2);
 4739:         }
 4740:         $datatable .= '<label>'.
 4741:                       '<input type="checkbox" name="ltitools_add_fields" value="'.$field.'"'.$id.$onclick.' />'.
 4742:                       $lt{$field}.'</label>'.$spacer;
 4743:     }
 4744:     $datatable .= '</span>'.
 4745:                   '<div style="display:none;" id="ltitools_user_div_add">'.
 4746:                   '<span class="LC_nobreak"> : '.
 4747:                   '<select name="ltitools_userincdom_add">'.
 4748:                   '<option value="" selected="selected">'.&mt('Select').'</option>'.
 4749:                   '<option value="0">'.&mt('username').'</option>'.
 4750:                   '<option value="1">'.&mt('username:domain').'</option>'.
 4751:                   '</select></span></div></fieldset>';
 4752:     $datatable .= '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 4753:     foreach my $role (@courseroles) {
 4754:         my ($checked,$checkednone);
 4755:         $datatable .= '<td style="text-align: center">'.
 4756:                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 4757:                       '<select name="ltitools_add_roles_'.$role.'">'.
 4758:                       '<option value="" selected="selected">'.&mt('Select').'</option>';
 4759:         foreach my $ltirole (@ltiroles) {
 4760:             $datatable .= '<option value="'.$ltirole.'">'.$ltirole.'</option>';
 4761:         }
 4762:         $datatable .= '</select></td>';
 4763:     }
 4764:     $datatable .= '</tr></table></fieldset>'.
 4765:                   '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 4766:     foreach my $item ('label','title','target','linktext','explanation','append') {
 4767:         $datatable .= '<label>'.
 4768:                       '<input type="checkbox" name="ltitools_courseconfig" value="'.$item.'" checked="checked" />'.
 4769:                       $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 4770:     }
 4771:     $datatable .= '</span></fieldset>'.
 4772:                   '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 4773:                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 4774:                   '<tr><td><span class="LC_nobreak">'.
 4775:                   '<label><input type="checkbox" name="ltitools_add_custom" value="1" />'.
 4776:                   &mt('Add').'</label></span></td><td><input type="text" name="ltitools_add_custom_name" />'.
 4777:                   '</td><td><input type="text" name="ltitools_add_custom_value" /></td></tr>'.
 4778:                   '</table></fieldset>'."\n".
 4779:                   '</td>'."\n".
 4780:                   '</tr>'."\n";
 4781:     $itemcount ++;
 4782:     return $datatable;
 4783: }
 4784: 
 4785: sub ltitools_names {
 4786:     my %lt = &Apache::lonlocal::texthash(
 4787:                                           'title'          => 'Title',
 4788:                                           'version'        => 'Version',
 4789:                                           'msgtype'        => 'Message Type',
 4790:                                           'sigmethod'      => 'Signature Method',
 4791:                                           'url'            => 'URL',
 4792:                                           'key'            => 'Key',
 4793:                                           'lifetime'       => 'Nonce lifetime (s)',
 4794:                                           'secret'         => 'Secret',
 4795:                                           'icon'           => 'Icon',   
 4796:                                           'user'           => 'User',
 4797:                                           'fullname'       => 'Full Name',
 4798:                                           'firstname'      => 'First Name',
 4799:                                           'lastname'       => 'Last Name',
 4800:                                           'email'          => 'E-mail',
 4801:                                           'roles'          => 'Role',
 4802:                                           'window'         => 'Window',
 4803:                                           'tab'            => 'Tab',
 4804:                                           'iframe'         => 'iFrame',
 4805:                                           'height'         => 'Height',
 4806:                                           'width'          => 'Width',
 4807:                                           'linktext'       => 'Default Link Text',
 4808:                                           'explanation'    => 'Default Explanation',
 4809:                                           'passback'       => 'Tool can return grades:',
 4810:                                           'roster'         => 'Tool can retrieve roster:',
 4811:                                           'crstarget'      => 'Display target',
 4812:                                           'crslabel'       => 'Course label',
 4813:                                           'crstitle'       => 'Course title', 
 4814:                                           'crslinktext'    => 'Link Text',
 4815:                                           'crsexplanation' => 'Explanation',
 4816:                                           'crsappend'      => 'Provider URL',
 4817:                                         );
 4818:     return %lt;
 4819: }
 4820: 
 4821: sub print_lti {
 4822:     my ($dom,$settings,$rowtotal) = @_;
 4823:     my $itemcount = 1;
 4824:     my $maxnum = 0;
 4825:     my $css_class;
 4826:     my %ordered;
 4827:     if (ref($settings) eq 'HASH') {
 4828:         foreach my $item (keys(%{$settings})) {
 4829:             if (ref($settings->{$item}) eq 'HASH') {
 4830:                 my $num = $settings->{$item}{'order'};
 4831:                 $ordered{$num} = $item;
 4832:             }
 4833:         }
 4834:     }
 4835:     my $maxnum = scalar(keys(%ordered));
 4836:     my $datatable;
 4837:     my %lt = &lti_names();
 4838:     if (keys(%ordered)) {
 4839:         my @items = sort { $a <=> $b } keys(%ordered);
 4840:         for (my $i=0; $i<@items; $i++) {
 4841:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4842:             my $item = $ordered{$items[$i]};
 4843:             my ($key,$secret,$lifetime,$consumer,$requser,$current);
 4844:             if (ref($settings->{$item}) eq 'HASH') {
 4845:                 $key = $settings->{$item}->{'key'};
 4846:                 $secret = $settings->{$item}->{'secret'};
 4847:                 $lifetime = $settings->{$item}->{'lifetime'};
 4848:                 $consumer = $settings->{$item}->{'consumer'};
 4849:                 $requser = $settings->{$item}->{'requser'};
 4850:                 $current = $settings->{$item};
 4851:             }
 4852:             my $onclickrequser = ' onclick="toggleLTI(this.form,'."'requser','$i'".');"';
 4853:             my %checkedrequser = (
 4854:                                    yes => ' checked="checked"',
 4855:                                    no  => '',
 4856:                                  );
 4857:             if (!$requser) {
 4858:                 $checkedrequser{'no'} = $checkedrequser{'yes'};
 4859:                 $checkedrequser{'yes'} = '';
 4860:             }
 4861:             my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_".$item."'".');"';
 4862:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 4863:                          .'<select name="lti_pos_'.$item.'"'.$chgstr.'>';
 4864:             for (my $k=0; $k<=$maxnum; $k++) {
 4865:                 my $vpos = $k+1;
 4866:                 my $selstr;
 4867:                 if ($k == $i) {
 4868:                     $selstr = ' selected="selected" ';
 4869:                 }
 4870:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4871:             }
 4872:             $datatable .= '</select>'.('&nbsp;'x2).
 4873:                 '<label><input type="checkbox" name="lti_del" value="'.$item.'" />'.
 4874:                 &mt('Delete?').'</label></span></td>'.
 4875:                 '<td colspan="2">'.
 4876:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 4877:                 '<span class="LC_nobreak">'.$lt{'consumer'}.
 4878:                 ':<input type="text" size="15" name="lti_consumer_'.$i.'" value="'.$consumer.'" /></span> '.
 4879:                 ('&nbsp;'x2).
 4880:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_'.$i.'">'.
 4881:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 4882:                 ('&nbsp;'x2).
 4883:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" name="lti_lifetime_'.$i.'"'.
 4884:                 'value="'.$lifetime.'" size="3" /></span>'.
 4885:                 ('&nbsp;'x2).
 4886:                  '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 4887:                  '<label><input type="radio" name="lti_requser_'.$i.'" value="1"'.$onclickrequser.$checkedrequser{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 4888:                  '<label><input type="radio" name="lti_requser_'.$i.'" value="0"'.$onclickrequser.$checkedrequser{no}.' />'.&mt('No').'</label></span>'."\n".
 4889:                 '<br /><br />'.
 4890:                 '<span class="LC_nobreak">'.$lt{'key'}.
 4891:                 ':<input type="text" size="25" name="lti_key_'.$i.'" value="'.$key.'" /></span> '.
 4892:                 ('&nbsp;'x2).
 4893:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 4894:                 '<input type="password" size="20" name="lti_secret_'.$i.'" value="'.$secret.'" />'.
 4895:                 '<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>'.
 4896:                 '<input type="hidden" name="lti_id_'.$i.'" value="'.$item.'" /></span>'.
 4897:                 '</fieldset>'.&lti_options($i,$current,$itemcount,%lt).'</td></tr>';
 4898:             $itemcount ++;
 4899:         }
 4900:     }
 4901:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4902:     my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_add'".');"';
 4903:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 4904:                   '<input type="hidden" name="lti_maxnum" value="'.$maxnum.'" />'."\n".
 4905:                   '<select name="lti_pos_add"'.$chgstr.'>';
 4906:     for (my $k=0; $k<$maxnum+1; $k++) {
 4907:         my $vpos = $k+1;
 4908:         my $selstr;
 4909:         if ($k == $maxnum) {
 4910:             $selstr = ' selected="selected" ';
 4911:         }
 4912:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4913:     }
 4914:     $datatable .= '</select>&nbsp;'."\n".
 4915:                   '<input type="checkbox" name="lti_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 4916:                   '<td colspan="2">'.
 4917:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 4918:                   '<span class="LC_nobreak">'.$lt{'consumer'}.
 4919:                   ':<input type="text" size="15" name="lti_consumer_add" value="" /></span> '."\n".
 4920:                   ('&nbsp;'x2).
 4921:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_add">'.
 4922:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 4923:                   ('&nbsp;'x2).
 4924:                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="3" name="lti_lifetime_add" value="300" /></span> '."\n".
 4925:                   ('&nbsp;'x2).
 4926:                   '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 4927:                   '<label><input type="radio" name="lti_requser_add" value="1" onclick="toggleLTI(this.form,'."'requser','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 4928:                   '<label><input type="radio" name="lti_requser_add" value="0" onclick="toggleLTI(this.form,'."'requser','add'".');" />'.&mt('No').'</label></span>'."\n".
 4929:                   '<br /><br />'.
 4930:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="lti_key_add" value="" /></span> '."\n".
 4931:                   ('&nbsp;'x2).
 4932:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="lti_secret_add" value="" />'.
 4933:                   '<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".
 4934:                   '</fieldset>'.&lti_options('add',undef,$itemcount,%lt).
 4935:                   '</td>'."\n".
 4936:                   '</tr>'."\n";
 4937:     $$rowtotal ++;
 4938:     return $datatable;;
 4939: }
 4940: 
 4941: sub lti_names {
 4942:     my %lt = &Apache::lonlocal::texthash(
 4943:                                           'version'   => 'LTI Version',
 4944:                                           'url'       => 'URL',
 4945:                                           'key'       => 'Key',
 4946:                                           'lifetime'  => 'Nonce lifetime (s)',
 4947:                                           'consumer'  => 'Consumer',
 4948:                                           'secret'    => 'Secret',
 4949:                                           'requser'   => "User's identity sent",
 4950:                                           'email'     => 'Email address',
 4951:                                           'sourcedid' => 'User ID',
 4952:                                           'other'     => 'Other',
 4953:                                           'passback'  => 'Can return grades to Consumer:',
 4954:                                           'roster'    => 'Can retrieve roster from Consumer:',
 4955:                                           'topmenu'   => 'Display LON-CAPA page header',
 4956:                                           'inlinemenu'=> 'Display LON-CAPA inline menu',
 4957:                                         );
 4958:     return %lt;
 4959: }
 4960: 
 4961: sub lti_options {
 4962:     my ($num,$current,$itemcount,%lt) = @_;
 4963:     my (%checked,%rolemaps,$crssecsrc,$userfield,$cidfield,$callback);
 4964:     $checked{'mapuser'}{'sourcedid'} = ' checked="checked"';
 4965:     $checked{'mapcrs'}{'course_offering_sourcedid'} = ' checked="checked"';
 4966:     $checked{'makecrs'}{'N'} = '  checked="checked"';
 4967:     $checked{'mapcrstype'} = {};
 4968:     $checked{'makeuser'} = {};
 4969:     $checked{'selfenroll'} = {};
 4970:     $checked{'crssec'} = {};
 4971:     $checked{'crssecsrc'} = {};
 4972:     $checked{'lcauth'} = {};
 4973:     $checked{'menuitem'} = {};
 4974:     if ($num eq 'add') {
 4975:         $checked{'lcauth'}{'lti'} = ' checked="checked"';
 4976:     }
 4977:     my $userfieldsty = 'none';
 4978:     my $crsfieldsty = 'none';
 4979:     my $crssecfieldsty = 'none';
 4980:     my $secsrcfieldsty = 'none';
 4981:     my $callbacksty = 'none';
 4982:     my $passbacksty = 'none';
 4983:     my $optionsty = 'block';
 4984:     my $lcauthparm;
 4985:     my $lcauthparmstyle = 'display:none';
 4986:     my $lcauthparmtext;
 4987:     my $menusty;
 4988:     my $numinrow = 4;
 4989:     my %menutitles = &ltimenu_titles();
 4990: 
 4991:     if (ref($current) eq 'HASH') {
 4992:         if (!$current->{'requser'}) {
 4993:             $optionsty = 'none';
 4994:         }
 4995:         if (($current->{'mapuser'} ne '') && ($current->{'mapuser'} ne 'lis_person_sourcedid')) {
 4996:             $checked{'mapuser'}{'sourcedid'} = '';
 4997:             if ($current->{'mapuser'} eq 'lis_person_contact_email_primary') {
 4998:                 $checked{'mapuser'}{'email'} = ' checked="checked"'; 
 4999:             } else {
 5000:                 $checked{'mapuser'}{'other'} = ' checked="checked"';
 5001:                 $userfield = $current->{'mapuser'};
 5002:                 $userfieldsty = 'inline-block';
 5003:             }
 5004:         }
 5005:         if (($current->{'mapcrs'} ne '') && ($current->{'mapcrs'} ne 'course_offering_sourcedid')) {
 5006:             $checked{'mapcrs'}{'course_offering_sourcedid'} = '';
 5007:             if ($current->{'mapcrs'} eq 'context_id') {
 5008:                 $checked{'mapcrs'}{'context_id'} = ' checked="checked"'; 
 5009:             } else {
 5010:                 $checked{'mapcrs'}{'other'} = ' checked="checked"';
 5011:                 $cidfield = $current->{'mapcrs'};
 5012:                 $crsfieldsty = 'inline-block';
 5013:             }
 5014:         }
 5015:         if (ref($current->{'mapcrstype'}) eq 'ARRAY') {
 5016:             foreach my $type (@{$current->{'mapcrstype'}}) {
 5017:                 $checked{'mapcrstype'}{$type} = ' checked="checked"';
 5018:             }
 5019:         }
 5020:         if ($current->{'makecrs'}) {
 5021:             $checked{'makecrs'}{'Y'} = '  checked="checked"';
 5022:         }
 5023:         if (ref($current->{'makeuser'}) eq 'ARRAY') {
 5024:             foreach my $role (@{$current->{'makeuser'}}) {
 5025:                 $checked{'makeuser'}{$role} = ' checked="checked"';
 5026:             }
 5027:         }
 5028:         if ($current->{'lcauth'} =~ /^(internal|localauth|krb4|krb5|lti)$/) {
 5029:             $checked{'lcauth'}{$1} = ' checked="checked"';
 5030:             unless (($current->{'lcauth'} eq 'lti') || ($current->{'lcauth'} eq 'internal')) {
 5031:                 $lcauthparm = $current->{'lcauthparm'};
 5032:                 $lcauthparmstyle = 'display:table-row'; 
 5033:                 if ($current->{'lcauth'} eq 'localauth') {
 5034:                     $lcauthparmtext = &mt('Local auth argument');
 5035:                 } else {
 5036:                     $lcauthparmtext = &mt('Kerberos domain');
 5037:                 }
 5038:             }
 5039:         }
 5040:         if (ref($current->{'selfenroll'}) eq 'ARRAY') {
 5041:             foreach my $role (@{$current->{'selfenroll'}}) {
 5042:                 $checked{'selfenroll'}{$role} = ' checked="checked"';
 5043:             }
 5044:         }
 5045:         if (ref($current->{'maproles'}) eq 'HASH') {
 5046:             %rolemaps = %{$current->{'maproles'}};
 5047:         }
 5048:         if ($current->{'section'} ne '') {
 5049:             $checked{'crssec'}{'Y'} = '  checked="checked"'; 
 5050:             $crssecfieldsty = 'inline-block';
 5051:             if ($current->{'section'} eq 'course_section_sourcedid') {
 5052:                 $checked{'crssecsrc'}{'sourcedid'} = ' checked="checked"';
 5053:             } else {
 5054:                 $checked{'crssecsrc'}{'other'} = ' checked="checked"';
 5055:                 $crssecsrc = $current->{'section'};
 5056:                 $secsrcfieldsty = 'inline-block';
 5057:             }
 5058:         } else {
 5059:             $checked{'crssec'}{'N'} = ' checked="checked"';
 5060:         }
 5061:         if ($current->{'callback'} ne '') {
 5062:             $callback = $current->{'callback'};
 5063:             $checked{'callback'}{'Y'} = ' checked="checked"';
 5064:             $callbacksty = 'inline-block';
 5065:         } else {
 5066:             $checked{'callback'}{'N'} = ' checked="checked"';
 5067:         }
 5068:         if ($current->{'topmenu'}) {
 5069:             $checked{'topmenu'}{'Y'} = ' checked="checked"';
 5070:         } else {
 5071:             $checked{'topmenu'}{'N'} = ' checked="checked"';
 5072:         }
 5073:         if ($current->{'inlinemenu'}) {
 5074:             $checked{'inlinemenu'}{'Y'} = ' checked="checked"';
 5075:         } else {
 5076:             $checked{'inlinemenu'}{'N'} = ' checked="checked"';
 5077:         }
 5078:         if (($current->{'topmenu'}) || ($current->{'inlinemenu'})) {
 5079:             $menusty = 'inline-block';
 5080:             if (ref($current->{'lcmenu'}) eq 'ARRAY') {
 5081:                 foreach my $item (@{$current->{'lcmenu'}}) {
 5082:                     if (exists($menutitles{$item})) {
 5083:                         $checked{'menuitem'}{$item} = ' checked="checked"';
 5084:                     }
 5085:                 }
 5086:             }
 5087:         } else {
 5088:             $menusty = 'none';
 5089:         }
 5090:     } else {
 5091:         $checked{'makecrs'}{'N'} = ' checked="checked"';
 5092:         $checked{'crssec'}{'N'} = ' checked="checked"';
 5093:         $checked{'callback'}{'N'} = ' checked="checked"';
 5094:         $checked{'topmenu'}{'N'} = ' checked="checked"';
 5095:         $checked{'inlinemenu'}{'Y'} = ' checked="checked"'; 
 5096:         $checked{'menuitem'}{'grades'} = ' checked="checked"';
 5097:         $menusty = 'inline-block'; 
 5098:     }
 5099:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
 5100:     my %coursetypetitles = &Apache::lonlocal::texthash (
 5101:                                official   => 'Official',
 5102:                                unofficial => 'Unofficial',
 5103:                                community  => 'Community',
 5104:                                textbook   => 'Textbook',
 5105:                                placement  => 'Placement Test',
 5106:                                lti        => 'LTI Provider',
 5107:     );
 5108:     my @authtypes = ('internal','krb4','krb5','localauth');
 5109:     my %shortauth = (
 5110:                      internal => 'int',
 5111:                      krb4 => 'krb4',
 5112:                      krb5 => 'krb5',
 5113:                      localauth  => 'loc'
 5114:                     );
 5115:     my %authnames = &authtype_names();
 5116:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
 5117:     my @lticourseroles = qw(Learner Instructor TeachingAssistant Mentor);
 5118:     my @courseroles = ('cc','in','ta','ep','st');
 5119:     my $onclickuser = ' onclick="toggleLTI(this.form,'."'user','$num'".');"';
 5120:     my $onclickcrs = ' onclick="toggleLTI(this.form,'."'crs','$num'".');"';
 5121:     my $onclicksec = ' onclick="toggleLTI(this.form,'."'sec','$num'".');"';
 5122:     my $onclickcallback = ' onclick="toggleLTI(this.form,'."'callback','$num'".');"';
 5123:     my $onclicksecsrc = ' onclick="toggleLTI(this.form,'."'secsrc','$num'".')"';
 5124:     my $onclicklcauth = ' onclick="toggleLTI(this.form,'."'lcauth','$num'".')"';
 5125:     my $onclickmenu = ' onclick="toggleLTI(this.form,'."'lcmenu','$num'".');"';
 5126:     my $output = '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping users').'</legend>'.
 5127:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('LON-CAPA username').':&nbsp;';
 5128:     foreach my $option ('sourcedid','email','other') {
 5129:         $output .= '<label><input type="radio" name="lti_mapuser_'.$num.'" value="'.$option.'"'.
 5130:                    $checked{'mapuser'}{$option}.$onclickuser.' />'.$lt{$option}.'</label>'.
 5131:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 5132:     }
 5133:     $output .= '</span></div>'.
 5134:                '<div class="LC_floatleft" style="display:'.$userfieldsty.';" id="lti_userfield_'.$num.'">'.
 5135:                '<input type="text" name="lti_customuser_'.$num.'" '.
 5136:                'value="'.$userfield.'" /></div></fieldset>'. 
 5137:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping course roles').'</legend><table><tr>';
 5138:     foreach my $ltirole (@lticourseroles) {
 5139:         my ($selected,$selectnone);
 5140:         if ($rolemaps{$ltirole} eq '') {
 5141:             $selectnone = ' selected="selected"';
 5142:         }
 5143:         $output .= '<td style="text-align: center">'.$ltirole.'<br />'.
 5144:                    '<select name="lti_maprole_'.$ltirole.'_'.$num.'">'.
 5145:                    '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 5146:         foreach my $role (@courseroles) {
 5147:             unless ($selectnone) {
 5148:                 if ($rolemaps{$ltirole} eq $role) {
 5149:                     $selected = ' selected="selected"';
 5150:                 } else {
 5151:                     $selected = '';
 5152:                 }
 5153:             }
 5154:             $output .= '<option value="'.$role.'"'.$selected.'>'.
 5155:                        &Apache::lonnet::plaintext($role,'Course').
 5156:                        '</option>';
 5157:         }
 5158:         $output .= '</select></td>';
 5159:     }
 5160:     $output .= '</tr></table></fieldset>'.
 5161:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Roles which may create user accounts').'</legend>';
 5162:     foreach my $ltirole (@ltiroles) {
 5163:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_makeuser_'.$num.'" value="'.$ltirole.'"'.
 5164:                    $checked{'makeuser'}{$ltirole}.' />'.$ltirole.'</label>&nbsp;</span> ';     
 5165:     }
 5166:     $output .= '</fieldset>'.
 5167:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('New user accounts created for LTI users').'</legend>'.
 5168:                '<table>'.
 5169:                &modifiable_userdata_row('lti','instdata_'.$num,$current,$numinrow,$itemcount).
 5170:                '</table>'.
 5171:                '<table class="LC_nested"><tr><td class="LC_left_item">LON-CAPA Authentication</td>'.
 5172:                '<td class="LC_left_item">';
 5173:     foreach my $auth ('lti',@authtypes) {
 5174:         my $authtext;
 5175:         if ($auth eq 'lti') {
 5176:             $authtext = &mt('None');
 5177:         } else {
 5178:             $authtext = $authnames{$shortauth{$auth}};
 5179:         }
 5180:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="lti_lcauth_'.$num.
 5181:                    '" value="'.$auth.'"'.$checked{'lcauth'}{$auth}.$onclicklcauth.' />'.
 5182:                    $authtext.'</label></span> &nbsp;';
 5183:     }
 5184:     $output .= '</td></tr>'.
 5185:                '<tr id="lti_lcauth_parmrow_'.$num.'" style="'.$lcauthparmstyle.'">'.
 5186:                '<td class="LC_right_item" colspan="2"><span class="LC_nobreak">'.
 5187:                '<span id="lti_lcauth_parmtext_'.$num.'">'.$lcauthparmtext.'</span>'.
 5188:                '<input type="text" name="lti_lcauthparm_'.$num.'" value="" /></span></td></tr>'.
 5189:                '</table></fieldset>'.
 5190:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping courses').'</legend>'.
 5191:                '<div class="LC_floatleft"><span class="LC_nobreak">'.
 5192:                &mt('Unique course identifier').':&nbsp;';
 5193:     foreach my $option ('course_offering_sourcedid','context_id','other') {
 5194:         $output .= '<label><input type="radio" name="lti_mapcrs_'.$num.'" value="'.$option.'"'.
 5195:                    $checked{'mapcrs'}{$option}.$onclickcrs.' />'.$option.'</label>'.
 5196:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 5197:     }
 5198:     $output .= '</span></div><div class="LC_floatleft" style="display:'.$crsfieldsty.';" id="lti_crsfield_'.$num.'">'.
 5199:                '<input type="text" name="lti_mapcrsfield_'.$num.'" value="'.$cidfield.'" />'.
 5200:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>'.
 5201:                '<span class="LC_nobreak">'.&mt('LON-CAPA course type(s)').':&nbsp;';
 5202:     foreach my $type (@coursetypes) {
 5203:         $output .= '<label><input type="checkbox" name="lti_mapcrstype_'.$num.'" value="'.$type.'"'.
 5204:                    $checked{'mapcrstype'}{$type}.' />'.$coursetypetitles{$type}.'</label>'.
 5205:                    ('&nbsp;'x2);
 5206:     }
 5207:     $output .= '</span></fieldset>'.
 5208:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Creating courses').'</legend>'.
 5209:                '<span class="LC_nobreak">'.&mt('Course created (if absent) on Instructor access').':&nbsp;'.
 5210:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="0"'.
 5211:                $checked{'makecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5212:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="1"'.
 5213:                $checked{'makecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 5214:                '</fieldset>'.
 5215:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Roles which may self-enroll').'</legend>';
 5216:     foreach my $lticrsrole (@lticourseroles) {
 5217:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_selfenroll_'.$num.'" value="'.$lticrsrole.'"'.
 5218:                    $checked{'selfenroll'}{$lticrsrole}.' />'.$lticrsrole.'</label>&nbsp;</span> ';
 5219:     }
 5220:     $output .= '</fieldset>'.
 5221:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Course options').'</legend>'.
 5222:                '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Assign users to sections').':&nbsp;'.
 5223:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="0"'.
 5224:                $checked{'crssec'}{'N'}.$onclicksec.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5225:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="1"'.
 5226:                $checked{'crssec'}{'Y'}.$onclicksec.' />'.&mt('Yes').'</label></span></div>'.
 5227:                '<div class="LC_floatleft" style="display:'.$crssecfieldsty.';" id="lti_crssecfield_'.$num.'">'.
 5228:                '<span class="LC_nobreak">'.&mt('From').':<label>'.
 5229:                '<input type="radio" name="lti_crssecsrc_'.$num.'" value="course_section_sourcedid"'.
 5230:                $checked{'crssecsrc'}{'sourcedid'}.$onclicksecsrc.' />'.
 5231:                &mt('Standard field').'</label>'.('&nbsp;'x2).
 5232:                '<label><input type="radio" name="lti_crssecsrc_'.$num.'" value="other"'.
 5233:                $checked{'crssecsrc'}{'other'}.$onclicksecsrc.' />'.&mt('Other').
 5234:                '</label></span></div><div class="LC_floatleft" style="display:'.$secsrcfieldsty.';" id="lti_secsrcfield_'.$num.'">'.
 5235:                '<input type="text" name="lti_customsection_'.$num.'" value="'.$crssecsrc.'" />'.
 5236:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 5237:     my ($pb1p1chk,$pb1p0chk,$onclickpb);
 5238:     foreach my $extra ('roster','passback') {
 5239:         my $checkedon = '';
 5240:         my $checkedoff = ' checked="checked"';
 5241:         if ($extra eq 'passback') {
 5242:             $pb1p1chk = ' checked="checked"';
 5243:             $pb1p0chk = '';
 5244:             $onclickpb = ' onclick="toggleLTI(this.form,'."'passback','$num'".');"'; 
 5245:         } else {
 5246:             $onclickpb = ''; 
 5247:         }
 5248:         if (ref($current) eq 'HASH') {
 5249:             if (($current->{$extra})) {
 5250:                 $checkedon = $checkedoff;
 5251:                 $checkedoff = '';
 5252:                 if ($extra eq 'passback') {
 5253:                     $passbacksty = 'inline-block';
 5254:                 }
 5255:                 if ($current->{'passbackformat'} eq '1.0') {
 5256:                     $pb1p0chk =  ' checked="checked"';
 5257:                     $pb1p1chk = '';
 5258:                 }
 5259:             }
 5260:         }
 5261:         $output .= $lt{$extra}.'&nbsp;'.
 5262:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="0"'.$checkedoff.$onclickpb.' />'.
 5263:                    &mt('No').'</label>'.('&nbsp;'x2).
 5264:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="1"'.$checkedon.$onclickpb.' />'.
 5265:                    &mt('Yes').'</label><br />';
 5266:     }
 5267:     $output .= '<div class="LC_floatleft" style="display:'.$passbacksty.';" id="lti_passback_'.$num.'">'.
 5268:                '<span class="LC_nobreak">'.&mt('Grade format').
 5269:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.1"'.$pb1p1chk.' />'.
 5270:                &mt('Outcomes Service (1.1)').'</label>'.('&nbsp;'x2).
 5271:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.0"'.$pb1p0chk.'/>'.
 5272:                &mt('Outcomes Extension (1.0)').'</label></span></div>'.
 5273:                '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 5274:                '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Callback on logout').':&nbsp;'.
 5275:                '<label><input type="radio" name="lti_callback_'.$num.'" value="0"'.
 5276:                $checked{'callback'}{'N'}.$onclickcallback.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5277:                '<label><input type="radio" name="lti_callback_'.$num.'" value="1"'.
 5278:                $checked{'callback'}{'Y'}.$onclickcallback.' />'.&mt('Yes').'</label></span></div>'.
 5279:                '<div class="LC_floatleft" style="display:'.$callbacksty.';" id="lti_callbackfield_'.$num.'">'.
 5280:                '<span class="LC_nobreak">'.&mt('Parameter').': '.
 5281:                '<input type="text" name="lti_callbackparam_'.$num.'" value="'.$callback.'" /></span>'.
 5282:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>'.
 5283:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Course defaults (Course Coordinator can override)').'</legend>'.
 5284:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'topmenu'}.':&nbsp;'.
 5285:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="0"'.
 5286:                $checked{'topmenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5287:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="1"'.
 5288:                $checked{'topmenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>'.
 5289:                '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 5290:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'inlinemenu'}.':&nbsp;'.
 5291:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="0"'.
 5292:                $checked{'inlinemenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5293:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="1"'.
 5294:                $checked{'inlinemenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>';
 5295:      $output .='<div style="padding:0;clear:both;margin:0;border:0"></div>'. 
 5296:                '<div class="LC_floatleft" style="display:'.$menusty.';" id="lti_menufield_'.$num.'">'.
 5297:                '<span class="LC_nobreak">'.&mt('Menu items').':&nbsp;';
 5298:     foreach my $type ('fullname','coursetitle','role','logout','grades') {
 5299:         $output .= '<label><input type="checkbox" name="lti_menuitem_'.$num.'" value="'.$type.'"'.
 5300:                    $checked{'menuitem'}{$type}.' />'.$menutitles{$type}.'</label>'.
 5301:                    ('&nbsp;'x2);
 5302:     }
 5303:     $output .= '</span></div></fieldset>';
 5304: #        '<fieldset><legend>'.&mt('Assigning author roles').'</legend>';
 5305: #
 5306: #    $output .= '</fieldset>'.
 5307: #        '<fieldset><legend>'.&mt('Assigning domain roles').'</legend>';
 5308:     return $output;
 5309: }
 5310: 
 5311: sub ltimenu_titles {
 5312:     return &Apache::lonlocal::texthash(
 5313:                                         fullname    => 'Full name',
 5314:                                         coursetitle => 'Course title',
 5315:                                         role        => 'Role',
 5316:                                         logout      => 'Logout',
 5317:                                         grades      => 'Grades',
 5318:     );
 5319: }
 5320: 
 5321: sub print_coursedefaults {
 5322:     my ($position,$dom,$settings,$rowtotal) = @_;
 5323:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 5324:     my $itemcount = 1;
 5325:     my %choices =  &Apache::lonlocal::texthash (
 5326:         canuse_pdfforms      => 'Course/Community users can create/upload PDF forms',
 5327:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 5328:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 5329:         coursecredits        => 'Credits can be specified for courses',
 5330:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 5331:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 5332:         texengine            => 'Default method to display mathematics',
 5333:         postsubmit           => 'Disable submit button/keypress following student submission',
 5334:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 5335:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 5336:     );
 5337:     my %staticdefaults = (
 5338:                            anonsurvey_threshold => 10,
 5339:                            uploadquota          => 500,
 5340:                            postsubmit           => 60,
 5341:                            mysqltables          => 172800,
 5342:                          );
 5343:     if ($position eq 'top') {
 5344:         %defaultchecked = (
 5345:                             'canuse_pdfforms' => 'off',
 5346:                             'uselcmath'       => 'on',
 5347:                             'usejsme'         => 'on',
 5348:                             'canclone'        => 'none',
 5349:                           );
 5350:         @toggles = ('canuse_pdfforms','uselcmath','usejsme');
 5351:         my $deftex = $Apache::lonnet::deftex;
 5352:         if (ref($settings) eq 'HASH') {
 5353:             if ($settings->{'texengine'}) {
 5354:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 5355:                     $deftex = $settings->{'texengine'};
 5356:                 }
 5357:             }
 5358:         }
 5359:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5360:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 5361:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 5362:                        '</span></td><td class="LC_right_item">'.
 5363:                        '<select name="texengine">'."\n";
 5364:         my %texoptions = (
 5365:                             MathJax  => 'MathJax',
 5366:                             mimetex  => &mt('Convert to Images'),
 5367:                             tth      => &mt('TeX to HTML'),
 5368:                          );
 5369:         foreach my $renderer ('MathJax','mimetex','tth') {
 5370:             my $selected = '';
 5371:             if ($renderer eq $deftex) {
 5372:                 $selected = ' selected="selected"';
 5373:             }
 5374:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 5375:         }
 5376:         $mathdisp .= '</select></td></tr>'."\n";
 5377:         $itemcount ++;
 5378:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 5379:                                                      \%choices,$itemcount);
 5380:         $datatable = $mathdisp.$datatable;
 5381:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5382:         $datatable .=
 5383:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 5384:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 5385:             '</span></td><td class="LC_left_item">';
 5386:         my $currcanclone = 'none';
 5387:         my $onclick;
 5388:         my @cloneoptions = ('none','domain');
 5389:         my %clonetitles = (
 5390:                              none     => 'No additional course requesters',
 5391:                              domain   => "Any course requester in course's domain",
 5392:                              instcode => 'Course requests for official courses ...',
 5393:                           );
 5394:         my (%codedefaults,@code_order,@posscodes);
 5395:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 5396:                                                     \@code_order) eq 'ok') {
 5397:             if (@code_order > 0) {
 5398:                 push(@cloneoptions,'instcode');
 5399:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 5400:             }
 5401:         }
 5402:         if (ref($settings) eq 'HASH') {
 5403:             if ($settings->{'canclone'}) {
 5404:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 5405:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 5406:                         if (@code_order > 0) {
 5407:                             $currcanclone = 'instcode';
 5408:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 5409:                         }
 5410:                     }
 5411:                 } elsif ($settings->{'canclone'} eq 'domain') {
 5412:                     $currcanclone = $settings->{'canclone'};
 5413:                 }
 5414:             }
 5415:         }
 5416:         foreach my $option (@cloneoptions) {
 5417:             my ($checked,$additional);
 5418:             if ($currcanclone eq $option) {
 5419:                 $checked = ' checked="checked"';
 5420:             }
 5421:             if ($option eq 'instcode') {
 5422:                 if (@code_order) {
 5423:                     my $show = 'none';
 5424:                     if ($checked) {
 5425:                         $show = 'block';
 5426:                     }
 5427:                     $additional = '<div id="cloneinstcode" style="display:'.$show.';" />'.
 5428:                                   &mt('Institutional codes for new and cloned course have identical:').
 5429:                                   '<br />';
 5430:                     foreach my $item (@code_order) {
 5431:                         my $codechk;
 5432:                         if ($checked) {
 5433:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 5434:                                 $codechk = ' checked="checked"';
 5435:                             }
 5436:                         }
 5437:                         $additional .= '<label>'.
 5438:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 5439:                                        $item.'</label>';
 5440:                     }
 5441:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 5442:                 }
 5443:             }
 5444:             $datatable .=
 5445:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 5446:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 5447:                 '</label>&nbsp;'.$additional.'</span><br />';
 5448:         }
 5449:         $datatable .= '</td>'.
 5450:                       '</tr>';
 5451:         $itemcount ++;
 5452:     } else {
 5453:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5454:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 5455:         my $currusecredits = 0;
 5456:         my $postsubmitclient = 1;
 5457:         my @types = ('official','unofficial','community','textbook','placement');
 5458:         if (ref($settings) eq 'HASH') {
 5459:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 5460:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 5461:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 5462:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 5463:                 }
 5464:             }
 5465:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 5466:                 foreach my $type (@types) {
 5467:                     next if ($type eq 'community');
 5468:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 5469:                     if ($defcredits{$type} ne '') {
 5470:                         $currusecredits = 1;
 5471:                     }
 5472:                 }
 5473:             }
 5474:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 5475:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 5476:                     $postsubmitclient = 0;
 5477:                     foreach my $type (@types) {
 5478:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5479:                     }
 5480:                 } else {
 5481:                     foreach my $type (@types) {
 5482:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 5483:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 5484:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 5485:                             } else {
 5486:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5487:                             }
 5488:                         } else {
 5489:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5490:                         }
 5491:                     }
 5492:                 }
 5493:             } else {
 5494:                 foreach my $type (@types) {
 5495:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5496:                 }
 5497:             }
 5498:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 5499:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 5500:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 5501:                 }
 5502:             } else {
 5503:                 foreach my $type (@types) {
 5504:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 5505:                 }
 5506:             }
 5507:         } else {
 5508:             foreach my $type (@types) {
 5509:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5510:             }
 5511:         }
 5512:         if (!$currdefresponder) {
 5513:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 5514:         } elsif ($currdefresponder < 1) {
 5515:             $currdefresponder = 1;
 5516:         }
 5517:         foreach my $type (@types) {
 5518:             if ($curruploadquota{$type} eq '') {
 5519:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 5520:             }
 5521:         }
 5522:         $datatable .=
 5523:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5524:                 $choices{'anonsurvey_threshold'}.
 5525:                 '</span></td>'.
 5526:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 5527:                 '<input type="text" name="anonsurvey_threshold"'.
 5528:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 5529:                 '</td></tr>'."\n";
 5530:         $itemcount ++;
 5531:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5532:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5533:                       $choices{'uploadquota'}.
 5534:                       '</span></td>'.
 5535:                       '<td style="text-align: right" class="LC_right_item">'.
 5536:                       '<table><tr>';
 5537:         foreach my $type (@types) {
 5538:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 5539:                            '<input type="text" name="uploadquota_'.$type.'"'.
 5540:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 5541:         }
 5542:         $datatable .= '</tr></table></td></tr>'."\n";
 5543:         $itemcount ++;
 5544:         my $onclick = "toggleDisplay(this.form,'credits');";
 5545:         my $display = 'none';
 5546:         if ($currusecredits) {
 5547:             $display = 'block';
 5548:         }
 5549:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 5550:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 5551:         foreach my $type (@types) {
 5552:             next if ($type eq 'community');
 5553:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 5554:                            '<input type="text" name="'.$type.'_credits"'.
 5555:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 5556:         }
 5557:         $additional .= '</tr></table></div>'."\n";
 5558:         %defaultchecked = ('coursecredits' => 'off');
 5559:         @toggles = ('coursecredits');
 5560:         my $current = {
 5561:                         'coursecredits' => $currusecredits,
 5562:                       };
 5563:         (my $table,$itemcount) =
 5564:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 5565:                                \%choices,$itemcount,$onclick,$additional,'left');
 5566:         $datatable .= $table;
 5567:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 5568:         my $display = 'none';
 5569:         if ($postsubmitclient) {
 5570:             $display = 'block';
 5571:         }
 5572:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 5573:                       &mt('Number of seconds submit is disabled').'<br />'.
 5574:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 5575:                       '<table><tr>';
 5576:         foreach my $type (@types) {
 5577:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 5578:                            '<input type="text" name="'.$type.'_timeout" value="'.
 5579:                            $deftimeout{$type}.'" size="5" /></td>';
 5580:         }
 5581:         $additional .= '</tr></table></div>'."\n";
 5582:         %defaultchecked = ('postsubmit' => 'on');
 5583:         @toggles = ('postsubmit');
 5584:         $current = {
 5585:                        'postsubmit' => $postsubmitclient,
 5586:                    };
 5587:         ($table,$itemcount) =
 5588:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 5589:                                \%choices,$itemcount,$onclick,$additional,'left');
 5590:         $datatable .= $table;
 5591:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5592:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5593:                       $choices{'mysqltables'}.
 5594:                       '</span></td>'.
 5595:                       '<td style="text-align: right" class="LC_right_item">'.
 5596:                       '<table><tr>';
 5597:         foreach my $type (@types) {
 5598:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 5599:                            '<input type="text" name="mysqltables_'.$type.'"'.
 5600:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 5601:         }
 5602:         $datatable .= '</tr></table></td></tr>'."\n";
 5603:         $itemcount ++;
 5604: 
 5605:     }
 5606:     $$rowtotal += $itemcount;
 5607:     return $datatable;
 5608: }
 5609: 
 5610: sub print_selfenrollment {
 5611:     my ($position,$dom,$settings,$rowtotal) = @_;
 5612:     my ($css_class,$datatable);
 5613:     my $itemcount = 1;
 5614:     my @types = ('official','unofficial','community','textbook','placement');
 5615:     if (($position eq 'top') || ($position eq 'middle')) {
 5616:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 5617:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 5618:         my @rows;
 5619:         my $key;
 5620:         if ($position eq 'top') {
 5621:             $key = 'admin'; 
 5622:             if (ref($rowsref) eq 'ARRAY') {
 5623:                 @rows = @{$rowsref};
 5624:             }
 5625:         } elsif ($position eq 'middle') {
 5626:             $key = 'default';
 5627:             @rows = ('types','registered','approval','limit');
 5628:         }
 5629:         foreach my $row (@rows) {
 5630:             if (defined($titlesref->{$row})) {
 5631:                 $itemcount ++;
 5632:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5633:                 $datatable .= '<tr'.$css_class.'>'.
 5634:                               '<td>'.$titlesref->{$row}.'</td>'.
 5635:                               '<td class="LC_left_item">'.
 5636:                               '<table><tr>';
 5637:                 my (%current,%currentcap);
 5638:                 if (ref($settings) eq 'HASH') {
 5639:                     if (ref($settings->{$key}) eq 'HASH') {
 5640:                         foreach my $type (@types) {
 5641:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 5642:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 5643:                             }
 5644:                             if (($row eq 'limit') && ($key eq 'default')) {
 5645:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 5646:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 5647:                                 }
 5648:                             }
 5649:                         }
 5650:                     }
 5651:                 }
 5652:                 my %roles = (
 5653:                              '0' => &Apache::lonnet::plaintext('dc'),
 5654:                             ); 
 5655:             
 5656:                 foreach my $type (@types) {
 5657:                     unless (($row eq 'registered') && ($key eq 'default')) {
 5658:                         $datatable .= '<th>'.&mt($type).'</th>';
 5659:                     }
 5660:                 }
 5661:                 unless (($row eq 'registered') && ($key eq 'default')) {
 5662:                     $datatable .= '</tr><tr>';
 5663:                 }
 5664:                 foreach my $type (@types) {
 5665:                     if ($type eq 'community') {
 5666:                         $roles{'1'} = &mt('Community personnel');
 5667:                     } else {
 5668:                         $roles{'1'} = &mt('Course personnel');
 5669:                     }
 5670:                     $datatable .= '<td style="vertical-align: top">';
 5671:                     if ($position eq 'top') {
 5672:                         my %checked;
 5673:                         if ($current{$type} eq '0') {
 5674:                             $checked{'0'} = ' checked="checked"';
 5675:                         } else {
 5676:                             $checked{'1'} = ' checked="checked"';
 5677:                         }
 5678:                         foreach my $role ('1','0') {
 5679:                             $datatable .= '<span class="LC_nobreak"><label>'.
 5680:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 5681:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 5682:                                           $roles{$role}.'</label></span> ';
 5683:                         }
 5684:                     } else {
 5685:                         if ($row eq 'types') {
 5686:                             my %checked;
 5687:                             if ($current{$type} =~ /^(all|dom)$/) {
 5688:                                 $checked{$1} = ' checked="checked"';
 5689:                             } else {
 5690:                                 $checked{''} = ' checked="checked"';
 5691:                             }
 5692:                             foreach my $val ('','dom','all') {
 5693:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5694:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5695:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5696:                             }
 5697:                         } elsif ($row eq 'registered') {
 5698:                             my %checked;
 5699:                             if ($current{$type} eq '1') {
 5700:                                 $checked{'1'} = ' checked="checked"';
 5701:                             } else {
 5702:                                 $checked{'0'} = ' checked="checked"';
 5703:                             }
 5704:                             foreach my $val ('0','1') {
 5705:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5706:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5707:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5708:                             }
 5709:                         } elsif ($row eq 'approval') {
 5710:                             my %checked;
 5711:                             if ($current{$type} =~ /^([12])$/) {
 5712:                                 $checked{$1} = ' checked="checked"';
 5713:                             } else {
 5714:                                 $checked{'0'} = ' checked="checked"';
 5715:                             }
 5716:                             for my $val (0..2) {
 5717:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5718:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5719:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5720:                             }
 5721:                         } elsif ($row eq 'limit') {
 5722:                             my %checked;
 5723:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 5724:                                 $checked{$1} = ' checked="checked"';
 5725:                             } else {
 5726:                                 $checked{'none'} = ' checked="checked"';
 5727:                             }
 5728:                             my $cap;
 5729:                             if ($currentcap{$type} =~ /^\d+$/) {
 5730:                                 $cap = $currentcap{$type};
 5731:                             }
 5732:                             foreach my $val ('none','allstudents','selfenrolled') {
 5733:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5734:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5735:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5736:                             }
 5737:                             $datatable .= '<br />'.
 5738:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 5739:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 5740:                                           '</span>'; 
 5741:                         }
 5742:                     }
 5743:                     $datatable .= '</td>';
 5744:                 }
 5745:                 $datatable .= '</tr>';
 5746:             }
 5747:             $datatable .= '</table></td></tr>';
 5748:         }
 5749:     } elsif ($position eq 'bottom') {
 5750:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 5751:     }
 5752:     $$rowtotal += $itemcount;
 5753:     return $datatable;
 5754: }
 5755: 
 5756: sub print_validation_rows {
 5757:     my ($caller,$dom,$settings,$rowtotal) = @_;
 5758:     my ($itemsref,$namesref,$fieldsref);
 5759:     if ($caller eq 'selfenroll') { 
 5760:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 5761:     } elsif ($caller eq 'requestcourses') {
 5762:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 5763:     }
 5764:     my %currvalidation;
 5765:     if (ref($settings) eq 'HASH') {
 5766:         if (ref($settings->{'validation'}) eq 'HASH') {
 5767:             %currvalidation = %{$settings->{'validation'}};
 5768:         }
 5769:     }
 5770:     my $datatable;
 5771:     my $itemcount = 0;
 5772:     foreach my $item (@{$itemsref}) {
 5773:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5774:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5775:                       $namesref->{$item}.
 5776:                       '</span></td>'.
 5777:                       '<td class="LC_left_item">';
 5778:         if (($item eq 'url') || ($item eq 'button')) {
 5779:             $datatable .= '<span class="LC_nobreak">'.
 5780:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 5781:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 5782:         } elsif ($item eq 'fields') {
 5783:             my @currfields;
 5784:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 5785:                 @currfields = @{$currvalidation{$item}};
 5786:             }
 5787:             foreach my $field (@{$fieldsref}) {
 5788:                 my $check = '';
 5789:                 if (grep(/^\Q$field\E$/,@currfields)) {
 5790:                     $check = ' checked="checked"';
 5791:                 }
 5792:                 $datatable .= '<span class="LC_nobreak"><label>'.
 5793:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 5794:                               ' value="'.$field.'"'.$check.' />'.$field.
 5795:                               '</label></span> ';
 5796:             }
 5797:         } elsif ($item eq 'markup') {
 5798:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 5799:                            $currvalidation{$item}.
 5800:                               '</textarea>';
 5801:         }
 5802:         $datatable .= '</td></tr>'."\n";
 5803:         if (ref($rowtotal)) {
 5804:             $itemcount ++;
 5805:         }
 5806:     }
 5807:     if ($caller eq 'requestcourses') {
 5808:         my %currhash;
 5809:         if (ref($settings) eq 'HASH') {
 5810:             if (ref($settings->{'validation'}) eq 'HASH') {
 5811:                 if ($settings->{'validation'}{'dc'} ne '') {
 5812:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 5813:                 }
 5814:             }
 5815:         }
 5816:         my $numinrow = 2;
 5817:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 5818:                                                        'validationdc',%currhash);
 5819:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5820:         $datatable .= '<tr'.$css_class.'><td>';
 5821:         if ($numdc > 1) {
 5822:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 5823:         } else {
 5824:             $datatable .=  &mt('Course creation processed as: ');
 5825:         }
 5826:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 5827:         $itemcount ++;
 5828:     }
 5829:     if (ref($rowtotal)) {
 5830:         $$rowtotal += $itemcount;
 5831:     }
 5832:     return $datatable;
 5833: }
 5834: 
 5835: sub print_privacy {
 5836:     my ($position,$dom,$settings,$rowtotal) = @_;
 5837:     my ($datatable,$css_class,$numinrow,@items,%names,$othertitle,$usertypes,$types);
 5838:     my $itemcount = 0;
 5839:     unless ($position eq 'top') {
 5840:         @items = ('domain','author','course','community');
 5841:         %names = &Apache::lonlocal::texthash (
 5842:                      domain => 'Assigned domain role(s)',
 5843:                      author => 'Assigned co-author role(s)',
 5844:                      course => 'Assigned course role(s)',
 5845:                      community => 'Assigned community role',
 5846:                  );
 5847:         $numinrow = 4;
 5848:         ($othertitle,$usertypes,$types) =
 5849:             &Apache::loncommon::sorted_inst_types($dom);
 5850:     }
 5851:     if (($position eq 'top') || ($position eq 'middle')) {
 5852:         my (%by_ip,%by_location,@intdoms,@instdoms);
 5853:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 5854:         if ($position eq 'top') {
 5855:             my %curr;
 5856:             my @options = ('none','user','domain','auto');
 5857:             my %titles = &Apache::lonlocal::texthash (
 5858:                 none   => 'Not allowed',
 5859:                 user   => 'User authorizes',
 5860:                 domain => 'DC authorizes',
 5861:                 auto   => 'Unrestricted',
 5862:                 instdom => 'Other domain shares institution/provider',
 5863:                 extdom => 'Other domain has different institution/provider',
 5864:             );
 5865:             my %names = &Apache::lonlocal::texthash (
 5866:                 domain => 'Domain role',
 5867:                 author => 'Co-author role',
 5868:                 course => 'Course role',
 5869:                 community => 'Community role',
 5870:             );
 5871:             my $primary_id = &Apache::lonnet::domain($dom,'primary');
 5872:             my $intdom = &Apache::lonnet::internet_dom($primary_id);
 5873:             foreach my $domtype ('instdom','extdom') {
 5874:                 my (%checked,$skip);
 5875:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5876:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$domtype}.'</td>'.
 5877:                               '<td class="LC_left_item">';
 5878:                 if ($domtype eq 'instdom') {
 5879:                     unless (@instdoms > 1) {
 5880:                         $datatable .= &mt('Nothing to set, as no domains besides [_1] are hosted by [_2]',$dom,$intdom);
 5881:                         $skip = 1;
 5882:                     }
 5883:                 } elsif ($domtype eq 'extdom') {
 5884:                     if (keys(%by_location) == 0) {
 5885:                         $datatable .= &mt('Nothing to set, as no other hosts besides [_1]',$intdom);
 5886:                         $skip = 1;
 5887:                     }
 5888:                 }
 5889:                 unless ($skip) {
 5890:                     foreach my $roletype ('domain','author','course','community') {
 5891:                         $checked{'auto'} = ' checked="checked"';
 5892:                         if (ref($settings) eq 'HASH') {
 5893:                             if (ref($settings->{approval}) eq 'HASH') {
 5894:                                 if (ref($settings->{approval}->{$domtype}) eq 'HASH') {
 5895:                                     if ($settings->{approval}->{$domtype}->{$roletype}=~ /^(none|user|domain)$/) {
 5896:                                         $checked{$1} = ' checked="checked"';
 5897:                                         $checked{'auto'} = '';
 5898:                                     }
 5899:                                 }
 5900:                             }
 5901:                         }
 5902:                         $datatable .= '<fieldset><legend>'.$names{$roletype}.'</legend>';
 5903:                         foreach my $option (@options) {
 5904:                             $datatable .= '<span class="LC_nobreak"><label>'.
 5905:                                           '<input type="radio" name="privacy_approval_'.$domtype.'_'.$roletype.'" '.
 5906:                                           'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 5907:                                           '</label></span>&nbsp; ';
 5908:                         }
 5909:                         $datatable .= '</fieldset>';
 5910:                     }
 5911:                 }
 5912:                 $datatable .= '</td></tr>';
 5913:                 $itemcount ++;
 5914:             }
 5915:         } elsif ($position eq 'middle') {
 5916:             if ((@instdoms > 1) || (keys(%by_location) > 0)) {
 5917:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5918:                     foreach my $item (@{$types}) {
 5919:                         $datatable .= &modifiable_userdata_row('privacy','othdom_'.$item,$settings,
 5920:                                                                $numinrow,$itemcount,'','','','','',
 5921:                                                                '',$usertypes->{$item});
 5922:                         $itemcount ++;
 5923:                     }
 5924:                 }
 5925:                 $datatable .= &modifiable_userdata_row('privacy','othdom_default',$settings,
 5926:                                                        $numinrow,$itemcount,'','','','','',
 5927:                                                        '',$othertitle);
 5928:                 $itemcount ++;
 5929:             } else {
 5930:                 my (@insttypes,%insttitles);
 5931:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5932:                     @insttypes = @{$types};
 5933:                     %insttitles = %{$usertypes};
 5934:                 }
 5935:                 foreach my $item (@insttypes,'default') {
 5936:                     my $title;
 5937:                     if ($item eq 'default') {
 5938:                         $title = $othertitle;
 5939:                     } else {
 5940:                         $title = $insttitles{$item};
 5941:                     }
 5942:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5943:                     $datatable .= '<tr'.$css_class.'>'.
 5944:                                   '<td class="LC_left_item">'.$title.'</td>'.
 5945:                                   '<td class="LC_left_item">'.
 5946:                                   &mt('Nothing to set here, as there are no other domains').
 5947:                                   '</td></tr>';
 5948:                     $itemcount ++;
 5949:                 }
 5950:             }
 5951:         }
 5952:     } else {
 5953:         my $prefix;
 5954:         if ($position eq 'lower') {
 5955:             $prefix = 'priv';
 5956:         } else {
 5957:             $prefix = 'unpriv';
 5958:         }
 5959:         foreach my $item (@items) {
 5960:             $datatable .= &modifiable_userdata_row('privacy',$prefix.'_'.$item,$settings,
 5961:                                                    $numinrow,$itemcount,'','','','','',
 5962:                                                    '',$names{$item});
 5963:             $itemcount ++;
 5964:         }
 5965:     }
 5966:     if (ref($rowtotal)) {
 5967:         $$rowtotal += $itemcount;
 5968:     }
 5969:     return $datatable;
 5970: }
 5971: 
 5972: sub print_passwords {
 5973:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 5974:     my ($datatable,$css_class);
 5975:     my $itemcount = 0;
 5976:     my %titles = &Apache::lonlocal::texthash (
 5977:         captcha        => '"Forgot Password" CAPTCHA validation',
 5978:         link           => 'Reset link expiration (hours)',
 5979:         case           => 'Case-sensitive usernames/e-mail',
 5980:         prelink        => 'Information required (form 1)',
 5981:         postlink       => 'Information required (form 2)',
 5982:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 5983:         customtext     => 'Domain specific text (HTML)',
 5984:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 5985:         intauth_check  => 'Check bcrypt cost if authenticated',
 5986:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 5987:         permanent      => 'Permanent e-mail address',
 5988:         critical       => 'Critical notification address',
 5989:         notify         => 'Notification address',
 5990:         min            => 'Minimum password length',
 5991:         max            => 'Maximum password length',
 5992:         chars          => 'Required characters',
 5993:         expire         => 'Password expiration (days)',
 5994:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 5995:     );
 5996:     if ($position eq 'top') {
 5997:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5998:         my $shownlinklife = 2;
 5999:         my $prelink = 'both';
 6000:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 6001:         if (ref($settings) eq 'HASH') {
 6002:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 6003:                 $shownlinklife = $settings->{resetlink};
 6004:             }
 6005:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 6006:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 6007:             }
 6008:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 6009:                 $prelink = $settings->{resetprelink};
 6010:             }
 6011:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 6012:                 %postlink = %{$settings->{resetpostlink}};
 6013:             }
 6014:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 6015:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 6016:             }
 6017:             if ($settings->{resetremove}) {
 6018:                 $nostdtext = 1;
 6019:             }
 6020:             if ($settings->{resetcustom}) {
 6021:                 $customurl = $settings->{resetcustom};
 6022:             }
 6023:         } else {
 6024:             if (ref($types) eq 'ARRAY') {
 6025:                 foreach my $item (@{$types}) {
 6026:                     $casesens{$item} = 1;
 6027:                     $postlink{$item} = ['username','email'];
 6028:                 }
 6029:             }
 6030:             $casesens{'default'} = 1;
 6031:             $postlink{'default'} = ['username','email'];
 6032:             $prelink = 'both';
 6033:             %emailsrc = (
 6034:                           permanent => 1,
 6035:                           critical  => 1,
 6036:                           notify    => 1,
 6037:             );
 6038:         }
 6039:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 6040:         $itemcount ++;
 6041:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6042:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 6043:                       '<td class="LC_left_item">'.
 6044:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 6045:                       'name="passwords_link" size="3" /></td></tr>';
 6046:         $itemcount ++;
 6047:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6048:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 6049:                       '<td class="LC_left_item">';
 6050:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6051:             foreach my $item (@{$types}) {
 6052:                 my $checkedcase;
 6053:                 if ($casesens{$item}) {
 6054:                     $checkedcase = ' checked="checked"';
 6055:                 }
 6056:                 $datatable .= '<span class="LC_nobreak"><label>'.
 6057:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 6058:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 6059:                               '<span>&nbsp;&nbsp; ';
 6060:             }
 6061:         }
 6062:         my $checkedcase;
 6063:         if ($casesens{'default'}) {
 6064:             $checkedcase = ' checked="checked"';
 6065:         }
 6066:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 6067:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 6068:                       $othertitle.'</label></span></td>';
 6069:         $itemcount ++;
 6070:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6071:         my %checkedpre = (
 6072:                              both => ' checked="checked"',
 6073:                              either => '',
 6074:                          );
 6075:         if ($prelink eq 'either') {
 6076:             $checkedpre{either} = ' checked="checked"';
 6077:             $checkedpre{both} = '';
 6078:         }
 6079:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 6080:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6081:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 6082:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 6083:                       '<span class="LC_nobreak"><label>'.
 6084:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 6085:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 6086:         $itemcount ++;
 6087:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6088:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 6089:                       '<td class="LC_left_item">';
 6090:         my %postlinked;
 6091:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6092:             foreach my $item (@{$types}) {
 6093:                 undef(%postlinked);
 6094:                 $datatable .= '<fieldset style="display: inline-block;">'.
 6095:                               '<legend>'.$usertypes->{$item}.'</legend>';
 6096:                 if (ref($postlink{$item}) eq 'ARRAY') {
 6097:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 6098:                 }
 6099:                 foreach my $field ('email','username') {
 6100:                     my $checked;
 6101:                     if ($postlinked{$field}) {
 6102:                         $checked = ' checked="checked"';
 6103:                     }
 6104:                     $datatable .= '<span class="LC_nobreak"><label>'.
 6105:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 6106:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 6107:                                   '<span>&nbsp;&nbsp; ';
 6108:                 }
 6109:                 $datatable .= '</fieldset>';
 6110:             }
 6111:         }
 6112:         if (ref($postlink{'default'}) eq 'ARRAY') {
 6113:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 6114:         }
 6115:         $datatable .= '<fieldset style="display: inline-block;">'.
 6116:                       '<legend>'.$othertitle.'</legend>';
 6117:         foreach my $field ('email','username') {
 6118:             my $checked;
 6119:             if ($postlinked{$field}) {
 6120:                 $checked = ' checked="checked"';
 6121:             }
 6122:             $datatable .= '<span class="LC_nobreak"><label>'.
 6123:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 6124:                           $field.'"'.$checked.' />'.$field.'</label>'.
 6125:                           '<span>&nbsp;&nbsp; ';
 6126:         }
 6127:         $datatable .= '</fieldset></td></tr>';
 6128:         $itemcount ++;
 6129:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6130:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 6131:                       '<td class="LC_left_item">';
 6132:         foreach my $type ('permanent','critical','notify') {
 6133:             my $checkedemail;
 6134:             if ($emailsrc{$type}) {
 6135:                 $checkedemail = ' checked="checked"';
 6136:             }
 6137:             $datatable .= '<span class="LC_nobreak"><label>'.
 6138:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 6139:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 6140:                           '<span>&nbsp;&nbsp; ';
 6141:         }
 6142:         $datatable .= '</td></tr>';
 6143:         $itemcount ++;
 6144:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6145:         my $switchserver = &check_switchserver($dom,$confname);
 6146:         my ($showstd,$noshowstd);
 6147:         if ($nostdtext) {
 6148:             $noshowstd = ' checked="checked"';
 6149:         } else {
 6150:             $showstd = ' checked="checked"';
 6151:         }
 6152:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 6153:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6154:                       &mt('Retain standard text:').
 6155:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 6156:                       &mt('Yes').'</label>'.'&nbsp;'.
 6157:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 6158:                       &mt('No').'</label></span><br />'.
 6159:                       '<span class="LC_fontsize_small">'.
 6160:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 6161:                       &mt('Include custom text:');
 6162:         if ($customurl) {
 6163:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('Custom text file'),600,500,
 6164:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 6165:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 6166:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 6167:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 6168:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 6169:         }
 6170:         if ($switchserver) {
 6171:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 6172:         } else {
 6173:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 6174:                          '<input type="file" name="passwords_customfile" /></span>';
 6175:         }
 6176:         $datatable .= '</td></tr>';
 6177:     } elsif ($position eq 'middle') {
 6178:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 6179:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 6180:         my %defaults;
 6181:         if (ref($domconf{'defaults'}) eq 'HASH') {
 6182:             %defaults = %{$domconf{'defaults'}};
 6183:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 6184:                 $defaults{'intauth_cost'} = 10;
 6185:             }
 6186:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 6187:                 $defaults{'intauth_check'} = 0;
 6188:             }
 6189:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 6190:                 $defaults{'intauth_switch'} = 0;
 6191:             }
 6192:         } else {
 6193:             %defaults = (
 6194:                           'intauth_cost'   => 10,
 6195:                           'intauth_check'  => 0,
 6196:                           'intauth_switch' => 0,
 6197:                         );
 6198:         }
 6199:         foreach my $item (@items) {
 6200:             if ($itemcount%2) {
 6201:                 $css_class = '';
 6202:             } else {
 6203:                 $css_class = ' class="LC_odd_row" ';
 6204:             }
 6205:             $datatable .= '<tr'.$css_class.'>'.
 6206:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 6207:                           '</span></td><td class="LC_left_item" colspan="3">';
 6208:             if ($item eq 'intauth_switch') {
 6209:                 my @options = (0,1,2);
 6210:                 my %optiondesc = &Apache::lonlocal::texthash (
 6211:                                    0 => 'No',
 6212:                                    1 => 'Yes',
 6213:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 6214:                                  );
 6215:                 $datatable .= '<table width="100%">';
 6216:                 foreach my $option (@options) {
 6217:                     my $checked = ' ';
 6218:                     if ($defaults{$item} eq $option) {
 6219:                         $checked = ' checked="checked"';
 6220:                     }
 6221:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 6222:                                   '<label><input type="radio" name="'.$item.
 6223:                                   '" value="'.$option.'"'.$checked.' />'.
 6224:                                   $optiondesc{$option}.'</label></span></td></tr>';
 6225:                 }
 6226:                 $datatable .= '</table>';
 6227:             } elsif ($item eq 'intauth_check') {
 6228:                 my @options = (0,1,2);
 6229:                 my %optiondesc = &Apache::lonlocal::texthash (
 6230:                                    0 => 'No',
 6231:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 6232:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 6233:                                  );
 6234:                 $datatable .= '<table width="100%">';
 6235:                 foreach my $option (@options) {
 6236:                     my $checked = ' ';
 6237:                     my $onclick;
 6238:                     if ($defaults{$item} eq $option) {
 6239:                         $checked = ' checked="checked"';
 6240:                     }
 6241:                     if ($option == 2) {
 6242:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 6243:                     }
 6244:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 6245:                                   '<label><input type="radio" name="'.$item.
 6246:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 6247:                                   $optiondesc{$option}.'</label></span></td></tr>';
 6248:                 }
 6249:                 $datatable .= '</table>';
 6250:             } else {
 6251:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 6252:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 6253:             }
 6254:             $datatable .= '</td></tr>';
 6255:             $itemcount ++;
 6256:         }
 6257:     } elsif ($position eq 'lower') {
 6258:         my ($min,$max,%chars,$expire,$numsaved);
 6259:         if (ref($settings) eq 'HASH') {
 6260:             if ($settings->{min}) {
 6261:                 $min = $settings->{min};
 6262:             }
 6263:             if ($settings->{max}) {
 6264:                 $max = $settings->{max};
 6265:             }
 6266:             if (ref($settings->{chars}) eq 'ARRAY') {
 6267:                 map { $chars{$_} = 1; } (@{$settings->{chars}});
 6268:             }
 6269:             if ($settings->{expire}) {
 6270:                 $expire = $settings->{expire};
 6271:             }
 6272:             if ($settings->{numsaved}) {
 6273:                 $numsaved = $settings->{numsaved};
 6274:             }
 6275:         } else {
 6276:             $min = '7';
 6277:         }
 6278:         my %rulenames = &Apache::lonlocal::texthash(
 6279:                                                      uc => 'At least one upper case letter',
 6280:                                                      lc => 'At least one lower case letter',
 6281:                                                      num => 'At least one number',
 6282:                                                      spec => 'At least one non-alphanumeric',
 6283:                                                    );
 6284:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6285:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 6286:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6287:                       '<input type="text" name="passwords_min" value="'.$min.'" size="3" />'.
 6288:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no minimum)').'</span>'.
 6289:                       '</span></td></tr>';
 6290:         $itemcount ++;
 6291:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6292:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 6293:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6294:                       '<input type="text" name="passwords_max" value="'.$max.'" size="3" />'.
 6295:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 6296:                       '</span></td></tr>';
 6297:         $itemcount ++;
 6298:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6299:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 6300:                       '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 6301:                       '</span></td>';
 6302:         my $numinrow = 2;
 6303:         my @possrules = ('uc','lc','num','spec');
 6304:         $datatable .= '<td class="LC_left_item"><table>';
 6305:         for (my $i=0; $i<@possrules; $i++) {
 6306:             my ($rem,$checked);
 6307:             if ($chars{$possrules[$i]}) {
 6308:                 $checked = ' checked="checked"';
 6309:             }
 6310:             $rem = $i%($numinrow);
 6311:             if ($rem == 0) {
 6312:                 if ($i > 0) {
 6313:                     $datatable .= '</tr>';
 6314:                 }
 6315:                 $datatable .= '<tr>';
 6316:             }
 6317:             $datatable .= '<td><span class="LC_nobreak"><label>'.
 6318:                           '<input type="checkbox" name="passwords_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 6319:                           $rulenames{$possrules[$i]}.'</label></span></td>';
 6320:         }
 6321:         my $rem = @possrules%($numinrow);
 6322:         my $colsleft = $numinrow - $rem;
 6323:         if ($colsleft > 1 ) {
 6324:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6325:                           '&nbsp;</td>';
 6326:         } elsif ($colsleft == 1) {
 6327:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 6328:         }
 6329:         $datatable .='</table></td></tr>';
 6330:         $itemcount ++;
 6331:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6332:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'expire'}.'</td>'.
 6333:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6334:                       '<input type="text" name="passwords_expire" value="'.$expire.'" size="4" />'.
 6335:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no expiration)').'</span>'.
 6336:                       '</span></td></tr>';
 6337:         $itemcount ++;
 6338:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6339:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 6340:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6341:                       '<input type="text" name="passwords_numsaved" value="'.$numsaved.'" size="3" />'.
 6342:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 6343:                       '</span></td></tr>';
 6344:     } else {
 6345:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6346:         my %ownerchg = (
 6347:                           by  => {},
 6348:                           for => {},
 6349:                        );
 6350:         my %ownertitles = &Apache::lonlocal::texthash (
 6351:                             by  => 'Course owner status(es) allowed',
 6352:                             for => 'Student status(es) allowed',
 6353:                           );
 6354:         if (ref($settings) eq 'HASH') {
 6355:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 6356:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 6357:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 6358:                 }
 6359:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 6360:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 6361:                 }
 6362:             }
 6363:         }
 6364:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6365:         $datatable .= '<tr '.$css_class.'>'.
 6366:                       '<td>'.
 6367:                       &mt('Requirements').'<ul>'.
 6368:                       '<li>'.&mt("Course 'type' is not a Community or Placement Test").'</li>'.
 6369:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 6370:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 6371:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 6372:                       '</ul>'.
 6373:                       '</td>'.
 6374:                       '<td class="LC_left_item">';
 6375:         foreach my $item ('by','for') {
 6376:             $datatable .= '<fieldset style="display: inline-block;">'.
 6377:                           '<legend>'.$ownertitles{$item}.'</legend>';
 6378:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6379:                 foreach my $type (@{$types}) {
 6380:                     my $checked;
 6381:                     if ($ownerchg{$item}{$type}) {
 6382:                         $checked = ' checked="checked"';
 6383:                     }
 6384:                     $datatable .= '<span class="LC_nobreak"><label>'.
 6385:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 6386:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 6387:                                   '<span>&nbsp;&nbsp; ';
 6388:                 }
 6389:             }
 6390:             my $checked;
 6391:             if ($ownerchg{$item}{'default'}) {
 6392:                 $checked = ' checked="checked"';
 6393:             }
 6394:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 6395:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 6396:                           $othertitle.'</label></span></fieldset>';
 6397:         }
 6398:         $datatable .= '</td></tr>';
 6399:     }
 6400:     return $datatable;
 6401: }
 6402: 
 6403: sub print_usersessions {
 6404:     my ($position,$dom,$settings,$rowtotal) = @_;
 6405:     my ($css_class,$datatable,$itemcount,%checked,%choices);
 6406:     my (%by_ip,%by_location,@intdoms,@instdoms);
 6407:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 6408: 
 6409:     my @alldoms = &Apache::lonnet::all_domains();
 6410:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 6411:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 6412:     my %altids = &id_for_thisdom(%servers);
 6413:     if ($position eq 'top') {
 6414:         if (keys(%serverhomes) > 1) {
 6415:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 6416:             my $curroffloadnow;
 6417:             if (ref($settings) eq 'HASH') {
 6418:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 6419:                     $curroffloadnow = $settings->{'offloadnow'};
 6420:                 }
 6421:             }
 6422:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,$curroffloadnow,$rowtotal);
 6423:         } else {
 6424:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 6425:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.').
 6426:                           '</td></tr>';
 6427:         }
 6428:     } else {
 6429:         my %titles = &usersession_titles();
 6430:         my ($prefix,@types);
 6431:         if ($position eq 'bottom') {
 6432:             $prefix = 'remote';
 6433:             @types = ('version','excludedomain','includedomain');
 6434:         } else {
 6435:             $prefix = 'hosted';
 6436:             @types = ('excludedomain','includedomain');
 6437:         }
 6438:         ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 6439:     }
 6440:     $$rowtotal += $itemcount;
 6441:     return $datatable;
 6442: }
 6443: 
 6444: sub rules_by_location {
 6445:     my ($settings,$prefix,$by_location,$by_ip,$types,$titles) = @_; 
 6446:     my ($datatable,$itemcount,$css_class);
 6447:     if (keys(%{$by_location}) == 0) {
 6448:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6449:         $datatable = '<tr'.$css_class.'><td colspan="2">'.
 6450:                      &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.').
 6451:                      '</td></tr>';
 6452:         $itemcount = 1;
 6453:     } else {
 6454:         $itemcount = 0;
 6455:         my $numinrow = 5;
 6456:         my (%current,%checkedon,%checkedoff);
 6457:         my @locations = sort(keys(%{$by_location}));
 6458:         foreach my $type (@{$types}) {
 6459:             $checkedon{$type} = '';
 6460:             $checkedoff{$type} = ' checked="checked"';
 6461:         }
 6462:         if (ref($settings) eq 'HASH') {
 6463:             if (ref($settings->{$prefix}) eq 'HASH') {
 6464:                 foreach my $key (keys(%{$settings->{$prefix}})) {
 6465:                     $current{$key} = $settings->{$prefix}{$key};
 6466:                     if ($key eq 'version') {
 6467:                         if ($current{$key} ne '') {
 6468:                             $checkedon{$key} = ' checked="checked"';
 6469:                             $checkedoff{$key} = '';
 6470:                         }
 6471:                     } elsif (ref($current{$key}) eq 'ARRAY') {
 6472:                         $checkedon{$key} = ' checked="checked"';
 6473:                         $checkedoff{$key} = '';
 6474:                     }
 6475:                 }
 6476:             }
 6477:         }
 6478:         foreach my $type (@{$types}) {
 6479:             next if ($type ne 'version' && !@locations);
 6480:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6481:             $datatable .= '<tr'.$css_class.'>
 6482:                            <td><span class="LC_nobreak">'.$titles->{$type}.'</span><br />
 6483:                            <span class="LC_nobreak">&nbsp;
 6484:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 6485:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 6486:             if ($type eq 'version') {
 6487:                 my @lcversions = &Apache::lonnet::all_loncaparevs();
 6488:                 my $selector = '<select name="'.$prefix.'_version">';
 6489:                 foreach my $version (@lcversions) {
 6490:                     my $selected = '';
 6491:                     if ($current{'version'} eq $version) {
 6492:                         $selected = ' selected="selected"';
 6493:                     }
 6494:                     $selector .= ' <option value="'.$version.'"'.
 6495:                                  $selected.'>'.$version.'</option>';
 6496:                 }
 6497:                 $selector .= '</select> ';
 6498:                 $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 6499:             } else {
 6500:                 $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 6501:                              'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 6502:                              ' />'.('&nbsp;'x2).
 6503:                              '<input type="button" value="'.&mt('uncheck all').'" '.
 6504:                              'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 6505:                              "\n".
 6506:                              '</div><div><table>';
 6507:                 my $rem;
 6508:                 for (my $i=0; $i<@locations; $i++) {
 6509:                     my ($showloc,$value,$checkedtype);
 6510:                     if (ref($by_location->{$locations[$i]}) eq 'ARRAY') {
 6511:                         my $ip = $by_location->{$locations[$i]}->[0];
 6512:                         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 6513:                             $value = join(':',@{$by_ip->{$ip}});
 6514:                             $showloc = join(', ',@{$by_ip->{$ip}});
 6515:                             if (ref($current{$type}) eq 'ARRAY') {
 6516:                                 foreach my $loc (@{$by_ip->{$ip}}) {
 6517:                                     if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 6518:                                         $checkedtype = ' checked="checked"';
 6519:                                         last;
 6520:                                     }
 6521:                                 }
 6522:                             }
 6523:                         }
 6524:                     }
 6525:                     $rem = $i%($numinrow);
 6526:                     if ($rem == 0) {
 6527:                         if ($i > 0) {
 6528:                             $datatable .= '</tr>';
 6529:                         }
 6530:                         $datatable .= '<tr>';
 6531:                     }
 6532:                     $datatable .= '<td class="LC_left_item">'.
 6533:                                   '<span class="LC_nobreak"><label>'.
 6534:                                   '<input type="checkbox" name="'.$prefix.'_'.$type.
 6535:                                   '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 6536:                                   '</label></span></td>';
 6537:                 }
 6538:                 $rem = @locations%($numinrow);
 6539:                 my $colsleft = $numinrow - $rem;
 6540:                 if ($colsleft > 1 ) {
 6541:                     $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6542:                                   '&nbsp;</td>';
 6543:                 } elsif ($colsleft == 1) {
 6544:                     $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 6545:                 }
 6546:                 $datatable .= '</tr></table>';
 6547:             }
 6548:             $datatable .= '</td></tr>';
 6549:             $itemcount ++;
 6550:         }
 6551:     }
 6552:     return ($datatable,$itemcount);
 6553: }
 6554: 
 6555: sub print_ssl {
 6556:     my ($position,$dom,$settings,$rowtotal) = @_;
 6557:     my ($css_class,$datatable);
 6558:     my $itemcount = 1;
 6559:     if ($position eq 'top') {
 6560:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 6561:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 6562:         my $same_institution;
 6563:         if ($intdom ne '') {
 6564:             my $internet_names = &Apache::lonnet::get_internet_names($Apache::lonnet::perlvar{'lonHostID'});
 6565:             if (ref($internet_names) eq 'ARRAY') {
 6566:                 if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 6567:                     $same_institution = 1;
 6568:                 }
 6569:             }
 6570:         }
 6571:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6572:         $datatable = '<tr'.$css_class.'><td colspan="2">';
 6573:         if ($same_institution) {
 6574:             my %domservers = &Apache::lonnet::get_servers($dom);
 6575:             $datatable .= &LONCAPA::SSL::print_certstatus(\%domservers,'web','domprefs');
 6576:         } else {
 6577:             $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.");
 6578:         }
 6579:         $datatable .= '</td></tr>';
 6580:         $itemcount ++;
 6581:     } else {
 6582:         my %titles = &ssl_titles();
 6583:         my (%by_ip,%by_location,@intdoms,@instdoms);
 6584:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 6585:         my @alldoms = &Apache::lonnet::all_domains();
 6586:         my %serverhomes = %Apache::lonnet::serverhomeIDs;
 6587:         my @domservers = &Apache::lonnet::get_servers($dom);
 6588:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 6589:         my %altids = &id_for_thisdom(%servers);
 6590:         if (($position eq 'connto') || ($position eq 'connfrom')) {
 6591:             my $legacy;
 6592:             unless (ref($settings) eq 'HASH') {
 6593:                 my $name;
 6594:                 if ($position eq 'connto') {
 6595:                     $name = 'loncAllowInsecure';
 6596:                 } else {
 6597:                     $name = 'londAllowInsecure';
 6598:                 }
 6599:                 my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
 6600:                 my @ids=&Apache::lonnet::current_machine_ids();
 6601:                 if (($primarylibserv ne '') && (!grep(/^\Q$primarylibserv\E$/,@ids))) {
 6602:                     my %what = (
 6603:                                    $name => 1,
 6604:                                );
 6605:                     my ($result,$returnhash) =
 6606:                         &Apache::lonnet::get_remote_globals($primarylibserv,\%what);
 6607:                     if ($result eq 'ok') {
 6608:                         if (ref($returnhash) eq 'HASH') {
 6609:                             $legacy = $returnhash->{$name};
 6610:                         }
 6611:                     }
 6612:                 } else {
 6613:                     $legacy = $Apache::lonnet::perlvar{$name};
 6614:                 }
 6615:             }
 6616:             foreach my $type ('dom','intdom','other') {
 6617:                 my %checked;
 6618:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6619:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$type}.'</td>'.
 6620:                               '<td class="LC_right_item">';
 6621:                 my $skip; 
 6622:                 if ($type eq 'dom') {
 6623:                     unless (keys(%servers) > 1) {
 6624:                         $datatable .= &mt('Nothing to set here, as there are no other servers/VMs');    
 6625:                         $skip = 1;
 6626:                     }
 6627:                 }
 6628:                 if ($type eq 'intdom') {
 6629:                     unless (@instdoms > 1) {
 6630:                         $datatable .= &mt('Nothing to set here, as there are no other domains for this institution');
 6631:                         $skip = 1;
 6632:                     } 
 6633:                 } elsif ($type eq 'other') {
 6634:                     if (keys(%by_location) == 0) {
 6635:                         $datatable .= &mt('Nothing to set here, as there are no other institutions');
 6636:                         $skip = 1;
 6637:                     }
 6638:                 }
 6639:                 unless ($skip) {
 6640:                     $checked{'yes'} = ' checked="checked"'; 
 6641:                     if (ref($settings) eq 'HASH') {
 6642:                         if (ref($settings->{$position}) eq 'HASH') {
 6643:                             if ($settings->{$position}->{$type} =~ /^(no|req)$/) {
 6644:                                 $checked{$1} = $checked{'yes'};
 6645:                                 delete($checked{'yes'}); 
 6646:                             }
 6647:                         }
 6648:                     } else {
 6649:                         if ($legacy == 0) {
 6650:                             $checked{'req'} = $checked{'yes'};
 6651:                             delete($checked{'yes'});    
 6652:                         }
 6653:                     }
 6654:                     foreach my $option ('no','yes','req') {
 6655:                         $datatable .= '<span class="LC_nobreak"><label>'.
 6656:                                       '<input type="radio" name="'.$position.'_'.$type.'" '.
 6657:                                       'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 6658:                                       '</label></span>'.('&nbsp;'x2);
 6659:                     }
 6660:                 }
 6661:                 $datatable .= '</td></tr>';
 6662:                 $itemcount ++; 
 6663:             }
 6664:         } else {
 6665:             my $prefix = 'replication';
 6666:             my @types = ('certreq','nocertreq');
 6667:             if (keys(%by_location) == 0) {
 6668:                 $datatable .= '<tr'.$css_class.'><td>'.
 6669:                               &mt('Nothing to set here, as there are no other institutions').
 6670:                               '</td></tr>';
 6671:                 $itemcount ++;
 6672:             } else {
 6673:                 ($datatable,$itemcount) = 
 6674:                     &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 6675:             }
 6676:         }
 6677:     }
 6678:     $$rowtotal += $itemcount;
 6679:     return $datatable;
 6680: }
 6681: 
 6682: sub ssl_titles {
 6683:     return &Apache::lonlocal::texthash (
 6684:                dom           => 'LON-CAPA servers/VMs from same domain',
 6685:                intdom        => 'LON-CAPA servers/VMs from same "internet" domain',
 6686:                other         => 'External LON-CAPA servers/VMs',
 6687:                connto        => 'Connections to other servers',
 6688:                connfrom      => 'Connections from other servers',
 6689:                replication   => 'Replicating content to other institutions',
 6690:                certreq       => 'Client certificate required, but specific domains exempt',
 6691:                nocertreq     => 'No client certificate required, except for specific domains',
 6692:                no            => 'SSL not used',
 6693:                yes           => 'SSL Optional (used if available)',
 6694:                req           => 'SSL Required',
 6695:     );
 6696: }
 6697: 
 6698: sub print_trust {
 6699:     my ($prefix,$dom,$settings,$rowtotal) = @_;
 6700:     my ($css_class,$datatable,%checked,%choices);
 6701:     my (%by_ip,%by_location,@intdoms,@instdoms);
 6702:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 6703:     my $itemcount = 1;
 6704:     my %titles = &trust_titles();
 6705:     my @types = ('exc','inc');
 6706:     if ($prefix eq 'top') {
 6707:         $prefix = 'content';
 6708:     } elsif ($prefix eq 'bottom') {
 6709:         $prefix = 'msg';
 6710:     }
 6711:     ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 6712:     $$rowtotal += $itemcount;
 6713:     return $datatable;
 6714: }
 6715: 
 6716: sub trust_titles {
 6717:     return &Apache::lonlocal::texthash(
 6718:                content  => "Access to this domain's content by others",
 6719:                shared   => "Access to other domain's content by this domain",
 6720:                enroll   => "Enrollment in this domain's courses by others", 
 6721:                othcoau  => "Co-author roles in this domain for others",
 6722:                coaurem  => "Co-author roles for this domain's users elsewhere", 
 6723:                domroles => "Domain roles in this domain assignable to others",
 6724:                catalog  => "Course Catalog for this domain displayed elsewhere",
 6725:                reqcrs   => "Requests for creation of courses in this domain by others",
 6726:                msg      => "Users in other domains can send messages to this domain",
 6727:                exc      => "Allow all, but exclude specific domains",
 6728:                inc      => "Deny all, but include specific domains",
 6729:            );
 6730: } 
 6731: 
 6732: sub build_location_hashes {
 6733:     my ($intdoms,$by_ip,$by_location,$instdoms) = @_;
 6734:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 6735:                   (ref($by_location) eq 'HASH') && (ref($instdoms) eq 'ARRAY'));
 6736:     my %iphost = &Apache::lonnet::get_iphost();
 6737:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 6738:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 6739:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 6740:         foreach my $id (@{$iphost{$primary_ip}}) {
 6741:             my $intdom = &Apache::lonnet::internet_dom($id);
 6742:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 6743:                 push(@{$intdoms},$intdom);
 6744:             }
 6745:         }
 6746:     }
 6747:     foreach my $ip (keys(%iphost)) {
 6748:         if (ref($iphost{$ip}) eq 'ARRAY') {
 6749:             foreach my $id (@{$iphost{$ip}}) {
 6750:                 my $location = &Apache::lonnet::internet_dom($id);
 6751:                 if ($location) {
 6752:                     if (grep(/^\Q$location\E$/,@{$intdoms})) {
 6753:                         my $dom = &Apache::lonnet::host_domain($id);
 6754:                         unless (grep(/^\Q$dom\E/,@{$instdoms})) {
 6755:                             push(@{$instdoms},$dom);
 6756:                         }
 6757:                         next;
 6758:                     }
 6759:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 6760:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 6761:                             push(@{$by_ip->{$ip}},$location);
 6762:                         }
 6763:                     } else {
 6764:                         $by_ip->{$ip} = [$location];
 6765:                     }
 6766:                 }
 6767:             }
 6768:         }
 6769:     }
 6770:     foreach my $ip (sort(keys(%{$by_ip}))) {
 6771:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 6772:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 6773:             my $first = $by_ip->{$ip}->[0];
 6774:             if (ref($by_location->{$first}) eq 'ARRAY') {
 6775:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 6776:                     push(@{$by_location->{$first}},$ip);
 6777:                 }
 6778:             } else {
 6779:                 $by_location->{$first} = [$ip];
 6780:             }
 6781:         }
 6782:     }
 6783:     return;
 6784: }
 6785: 
 6786: sub current_offloads_to {
 6787:     my ($dom,$settings,$servers) = @_;
 6788:     my (%spareid,%otherdomconfigs);
 6789:     if (ref($servers) eq 'HASH') {
 6790:         foreach my $lonhost (sort(keys(%{$servers}))) {
 6791:             my $gotspares;
 6792:             if (ref($settings) eq 'HASH') {
 6793:                 if (ref($settings->{'spares'}) eq 'HASH') {
 6794:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 6795:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 6796:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 6797:                         $gotspares = 1;
 6798:                     }
 6799:                 }
 6800:             }
 6801:             unless ($gotspares) {
 6802:                 my $gotspares;
 6803:                 my $serverhomeID =
 6804:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 6805:                 my $serverhomedom =
 6806:                     &Apache::lonnet::host_domain($serverhomeID);
 6807:                 if ($serverhomedom ne $dom) {
 6808:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 6809:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 6810:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 6811:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 6812:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 6813:                                 $gotspares = 1;
 6814:                             }
 6815:                         }
 6816:                     } else {
 6817:                         $otherdomconfigs{$serverhomedom} =
 6818:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 6819:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 6820:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 6821:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 6822:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 6823:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 6824:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 6825:                                         $gotspares = 1;
 6826:                                     }
 6827:                                 }
 6828:                             }
 6829:                         }
 6830:                     }
 6831:                 }
 6832:             }
 6833:             unless ($gotspares) {
 6834:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 6835:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 6836:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 6837:                } else {
 6838:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 6839:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 6840:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 6841:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 6842:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 6843:                     } else {
 6844:                         my %what = (
 6845:                              spareid => 1,
 6846:                         );
 6847:                         my ($result,$returnhash) = 
 6848:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 6849:                         if ($result eq 'ok') { 
 6850:                             if (ref($returnhash) eq 'HASH') {
 6851:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 6852:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 6853:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 6854:                                 }
 6855:                             }
 6856:                         }
 6857:                     }
 6858:                 }
 6859:             }
 6860:         }
 6861:     }
 6862:     return %spareid;
 6863: }
 6864: 
 6865: sub spares_row {
 6866:     my ($dom,$servers,$spareid,$serverhomes,$altids,$curroffloadnow,$rowtotal) = @_;
 6867:     my $css_class;
 6868:     my $numinrow = 4;
 6869:     my $itemcount = 1;
 6870:     my $datatable;
 6871:     my %typetitles = &sparestype_titles();
 6872:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 6873:         foreach my $server (sort(keys(%{$servers}))) {
 6874:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 6875:             my ($othercontrol,$serverdom);
 6876:             if ($serverhome ne $server) {
 6877:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 6878:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 6879:             } else {
 6880:                 $serverdom = &Apache::lonnet::host_domain($server);
 6881:                 if ($serverdom ne $dom) {
 6882:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 6883:                 }
 6884:             }
 6885:             next unless (ref($spareid->{$server}) eq 'HASH');
 6886:             my $checkednow;
 6887:             if (ref($curroffloadnow) eq 'HASH') {
 6888:                 if ($curroffloadnow->{$server}) {
 6889:                     $checkednow = ' checked="checked"';
 6890:                 }
 6891:             }
 6892:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6893:             $datatable .= '<tr'.$css_class.'>
 6894:                            <td rowspan="2">
 6895:                             <span class="LC_nobreak">'.
 6896:                           &mt('[_1] when busy, offloads to:'
 6897:                               ,'<b>'.$server.'</b>').'</span><br />'.
 6898:                           '<span class="LC_nobreak">'."\n".
 6899:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 6900:                           '&nbsp;'.&mt('Switch active users on next access').'</label></span>'.
 6901:                           "\n";
 6902:             my (%current,%canselect);
 6903:             my @choices = 
 6904:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 6905:             foreach my $type ('primary','default') {
 6906:                 if (ref($spareid->{$server}) eq 'HASH') {
 6907:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 6908:                         my @spares = @{$spareid->{$server}{$type}};
 6909:                         if (@spares > 0) {
 6910:                             if ($othercontrol) {
 6911:                                 $current{$type} = join(', ',@spares);
 6912:                             } else {
 6913:                                 $current{$type} .= '<table>';
 6914:                                 my $numspares = scalar(@spares);
 6915:                                 for (my $i=0;  $i<@spares; $i++) {
 6916:                                     my $rem = $i%($numinrow);
 6917:                                     if ($rem == 0) {
 6918:                                         if ($i > 0) {
 6919:                                             $current{$type} .= '</tr>';
 6920:                                         }
 6921:                                         $current{$type} .= '<tr>';
 6922:                                     }
 6923:                                     $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;'.
 6924:                                                        $spareid->{$server}{$type}[$i].
 6925:                                                        '</label></td>'."\n";
 6926:                                 }
 6927:                                 my $rem = @spares%($numinrow);
 6928:                                 my $colsleft = $numinrow - $rem;
 6929:                                 if ($colsleft > 1 ) {
 6930:                                     $current{$type} .= '<td colspan="'.$colsleft.
 6931:                                                        '" class="LC_left_item">'.
 6932:                                                        '&nbsp;</td>';
 6933:                                 } elsif ($colsleft == 1) {
 6934:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 6935:                                 }
 6936:                                 $current{$type} .= '</tr></table>';
 6937:                             }
 6938:                         }
 6939:                     }
 6940:                     if ($current{$type} eq '') {
 6941:                         $current{$type} = &mt('None specified');
 6942:                     }
 6943:                     if ($othercontrol) {
 6944:                         if ($type eq 'primary') {
 6945:                             $canselect{$type} = $othercontrol;
 6946:                         }
 6947:                     } else {
 6948:                         $canselect{$type} = 
 6949:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 6950:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 6951:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 6952:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 6953:                         if (@choices > 0) {
 6954:                             foreach my $lonhost (@choices) {
 6955:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 6956:                             }
 6957:                         }
 6958:                         $canselect{$type} .= '</select>'."\n";
 6959:                     }
 6960:                 } else {
 6961:                     $current{$type} = &mt('Could not be determined');
 6962:                     if ($type eq 'primary') {
 6963:                         $canselect{$type} =  $othercontrol;
 6964:                     }
 6965:                 }
 6966:                 if ($type eq 'default') {
 6967:                     $datatable .= '<tr'.$css_class.'>';
 6968:                 }
 6969:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 6970:                               '<td>'.$current{$type}.'</td>'."\n".
 6971:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 6972:             }
 6973:             $itemcount ++;
 6974:         }
 6975:     }
 6976:     $$rowtotal += $itemcount;
 6977:     return $datatable;
 6978: }
 6979: 
 6980: sub possible_newspares {
 6981:     my ($server,$currspares,$serverhomes,$altids) = @_;
 6982:     my $serverhostname = &Apache::lonnet::hostname($server);
 6983:     my %excluded;
 6984:     if ($serverhostname ne '') {
 6985:         %excluded = (
 6986:                        $serverhostname => 1,
 6987:                     );
 6988:     }
 6989:     if (ref($currspares) eq 'HASH') {
 6990:         foreach my $type (keys(%{$currspares})) {
 6991:             if (ref($currspares->{$type}) eq 'ARRAY') {
 6992:                 if (@{$currspares->{$type}} > 0) {
 6993:                     foreach my $curr (@{$currspares->{$type}}) {
 6994:                         my $hostname = &Apache::lonnet::hostname($curr);
 6995:                         $excluded{$hostname} = 1;
 6996:                     }
 6997:                 }
 6998:             }
 6999:         }
 7000:     }
 7001:     my @choices;
 7002:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 7003:         if (keys(%{$serverhomes}) > 1) {
 7004:             foreach my $name (sort(keys(%{$serverhomes}))) {
 7005:                 unless ($excluded{$name}) {
 7006:                     if (exists($altids->{$serverhomes->{$name}})) {
 7007:                         push(@choices,$altids->{$serverhomes->{$name}});
 7008:                     } else {
 7009:                         push(@choices,$serverhomes->{$name});
 7010:                     }
 7011:                 }
 7012:             }
 7013:         }
 7014:     }
 7015:     return sort(@choices);
 7016: }
 7017: 
 7018: sub print_loadbalancing {
 7019:     my ($dom,$settings,$rowtotal) = @_;
 7020:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7021:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7022:     my $numinrow = 1;
 7023:     my $datatable;
 7024:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7025:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 7026:     if (ref($settings) eq 'HASH') {
 7027:         %existing = %{$settings};
 7028:     }
 7029:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 7030:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 7031:                                   \%currtargets,\%currrules,\%currcookies);
 7032:     } else {
 7033:         return;
 7034:     }
 7035:     my ($othertitle,$usertypes,$types) =
 7036:         &Apache::loncommon::sorted_inst_types($dom);
 7037:     my $rownum = 8;
 7038:     if (ref($types) eq 'ARRAY') {
 7039:         $rownum += scalar(@{$types});
 7040:     }
 7041:     my @css_class = ('LC_odd_row','LC_even_row');
 7042:     my $balnum = 0;
 7043:     my $islast;
 7044:     my (@toshow,$disabledtext);
 7045:     if (keys(%currbalancer) > 0) {
 7046:         @toshow = sort(keys(%currbalancer));
 7047:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 7048:             push(@toshow,'');
 7049:         }
 7050:     } else {
 7051:         @toshow = ('');
 7052:         $disabledtext = &mt('No existing load balancer');
 7053:     }
 7054:     foreach my $lonhost (@toshow) {
 7055:         if ($balnum == scalar(@toshow)-1) {
 7056:             $islast = 1;
 7057:         } else {
 7058:             $islast = 0;
 7059:         }
 7060:         my $cssidx = $balnum%2;
 7061:         my $targets_div_style = 'display: none';
 7062:         my $disabled_div_style = 'display: block';
 7063:         my $homedom_div_style = 'display: none';
 7064:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 7065:                       '<td rowspan="'.$rownum.'" style="vertical-align: top">'.
 7066:                       '<p>';
 7067:         if ($lonhost eq '') {
 7068:             $datatable .= '<span class="LC_nobreak">';
 7069:             if (keys(%currbalancer) > 0) {
 7070:                 $datatable .= &mt('Add balancer:');
 7071:             } else {
 7072:                 $datatable .= &mt('Enable balancer:');
 7073:             }
 7074:             $datatable .= '&nbsp;'.
 7075:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 7076:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 7077:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 7078:                           '<option value="" selected="selected">'.&mt('None').
 7079:                           '</option>'."\n";
 7080:             foreach my $server (sort(keys(%servers))) {
 7081:                 next if ($currbalancer{$server});
 7082:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 7083:             }
 7084:             $datatable .=
 7085:                 '</select>'."\n".
 7086:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 7087:         } else {
 7088:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 7089:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 7090:                            &mt('Stop balancing').'</label>'.
 7091:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 7092:             $targets_div_style = 'display: block';
 7093:             $disabled_div_style = 'display: none';
 7094:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 7095:                 $homedom_div_style = 'display: block';
 7096:             }
 7097:         }
 7098:         $datatable .= '</p></td><td rowspan="'.$rownum.'" style="vertical-align: top">'.
 7099:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 7100:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 7101:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 7102:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 7103:         my @sparestypes = ('primary','default');
 7104:         my %typetitles = &sparestype_titles();
 7105:         my %hostherechecked = (
 7106:                                   no => ' checked="checked"',
 7107:                               );
 7108:         my %balcookiechecked = (
 7109:                                   no => ' checked="checked"', 
 7110:                                );
 7111:         foreach my $sparetype (@sparestypes) {
 7112:             my $targettable;
 7113:             for (my $i=0; $i<$numspares; $i++) {
 7114:                 my $checked;
 7115:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 7116:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 7117:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 7118:                             $checked = ' checked="checked"';
 7119:                         }
 7120:                     }
 7121:                 }
 7122:                 my ($chkboxval,$disabled);
 7123:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 7124:                     $chkboxval = $spares[$i];
 7125:                 }
 7126:                 if (exists($currbalancer{$spares[$i]})) {
 7127:                     $disabled = ' disabled="disabled"';
 7128:                 }
 7129:                 $targettable .=
 7130:                     '<td><span class="LC_nobreak"><label>'.
 7131:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 7132:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 7133:                     '</span></label></span></td>';
 7134:                 my $rem = $i%($numinrow);
 7135:                 if ($rem == 0) {
 7136:                     if (($i > 0) && ($i < $numspares-1)) {
 7137:                         $targettable .= '</tr>';
 7138:                     }
 7139:                     if ($i < $numspares-1) {
 7140:                         $targettable .= '<tr>';
 7141:                     }
 7142:                 }
 7143:             }
 7144:             if ($targettable ne '') {
 7145:                 my $rem = $numspares%($numinrow);
 7146:                 my $colsleft = $numinrow - $rem;
 7147:                 if ($colsleft > 1 ) {
 7148:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7149:                                     '&nbsp;</td>';
 7150:                 } elsif ($colsleft == 1) {
 7151:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 7152:                 }
 7153:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 7154:                                '<table><tr>'.$targettable.'</tr></table><br />';
 7155:             }
 7156:             $hostherechecked{$sparetype} = '';
 7157:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 7158:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 7159:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 7160:                         $hostherechecked{$sparetype} = ' checked="checked"';
 7161:                         $hostherechecked{'no'} = '';
 7162:                     }
 7163:                 }
 7164:             }
 7165:         }
 7166:         if ($currcookies{$lonhost}) {
 7167:             %balcookiechecked = (
 7168:                                     yes => ' checked="checked"',
 7169:                                 );
 7170:         }
 7171:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 7172:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 7173:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 7174:         foreach my $sparetype (@sparestypes) {
 7175:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 7176:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 7177:                           '</i></label><br />';
 7178:         }
 7179:         $datatable .= &mt('Use balancer cookie').'<br />'.
 7180:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 7181:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 7182:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 7183:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 7184:                       '</div></td></tr>'.
 7185:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 7186:                                            $othertitle,$usertypes,$types,\%servers,
 7187:                                            \%currbalancer,$lonhost,
 7188:                                            $targets_div_style,$homedom_div_style,
 7189:                                            $css_class[$cssidx],$balnum,$islast);
 7190:         $$rowtotal += $rownum;
 7191:         $balnum ++;
 7192:     }
 7193:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 7194:     return $datatable;
 7195: }
 7196: 
 7197: sub get_loadbalancers_config {
 7198:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 7199:     return unless ((ref($servers) eq 'HASH') &&
 7200:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 7201:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 7202:                    (ref($currcookies) eq 'HASH'));
 7203:     if (keys(%{$existing}) > 0) {
 7204:         my $oldlonhost;
 7205:         foreach my $key (sort(keys(%{$existing}))) {
 7206:             if ($key eq 'lonhost') {
 7207:                 $oldlonhost = $existing->{'lonhost'};
 7208:                 $currbalancer->{$oldlonhost} = 1;
 7209:             } elsif ($key eq 'targets') {
 7210:                 if ($oldlonhost) {
 7211:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 7212:                 }
 7213:             } elsif ($key eq 'rules') {
 7214:                 if ($oldlonhost) {
 7215:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 7216:                 }
 7217:             } elsif (ref($existing->{$key}) eq 'HASH') {
 7218:                 $currbalancer->{$key} = 1;
 7219:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 7220:                 $currrules->{$key} = $existing->{$key}{'rules'};
 7221:                 if ($existing->{$key}{'cookie'}) {
 7222:                     $currcookies->{$key} = 1;
 7223:                 }
 7224:             }
 7225:         }
 7226:     } else {
 7227:         my ($balancerref,$targetsref) =
 7228:                 &Apache::lonnet::get_lonbalancer_config($servers);
 7229:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 7230:             foreach my $server (sort(keys(%{$balancerref}))) {
 7231:                 $currbalancer->{$server} = 1;
 7232:                 $currtargets->{$server} = $targetsref->{$server};
 7233:             }
 7234:         }
 7235:     }
 7236:     return;
 7237: }
 7238: 
 7239: sub loadbalancing_rules {
 7240:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 7241:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 7242:         $css_class,$balnum,$islast) = @_;
 7243:     my $output;
 7244:     my $num = 0;
 7245:     my ($alltypes,$othertypes,$titles) =
 7246:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 7247:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 7248:         foreach my $type (@{$alltypes}) {
 7249:             $num ++;
 7250:             my $current;
 7251:             if (ref($currrules) eq 'HASH') {
 7252:                 $current = $currrules->{$type};
 7253:             }
 7254:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 7255:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 7256:                     $current = '';
 7257:                 }
 7258:             }
 7259:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 7260:                                              $servers,$currbalancer,$lonhost,$dom,
 7261:                                              $targets_div_style,$homedom_div_style,
 7262:                                              $css_class,$balnum,$num,$islast);
 7263:         }
 7264:     }
 7265:     return $output;
 7266: }
 7267: 
 7268: sub loadbalancing_titles {
 7269:     my ($dom,$intdom,$usertypes,$types) = @_;
 7270:     my %othertypes = (
 7271:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 7272:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 7273:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 7274:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 7275:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 7276:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 7277:                      );
 7278:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 7279:     my @available;
 7280:     if (ref($types) eq 'ARRAY') {
 7281:         @available = @{$types};
 7282:     }
 7283:     unless (grep(/^default$/,@available)) {
 7284:         push(@available,'default');
 7285:     }
 7286:     unshift(@alltypes,@available);
 7287:     my %titles;
 7288:     foreach my $type (@alltypes) {
 7289:         if ($type =~ /^_LC_/) {
 7290:             $titles{$type} = $othertypes{$type};
 7291:         } elsif ($type eq 'default') {
 7292:             $titles{$type} = &mt('All users from [_1]',$dom);
 7293:             if (ref($types) eq 'ARRAY') {
 7294:                 if (@{$types} > 0) {
 7295:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 7296:                 }
 7297:             }
 7298:         } elsif (ref($usertypes) eq 'HASH') {
 7299:             $titles{$type} = $usertypes->{$type};
 7300:         }
 7301:     }
 7302:     return (\@alltypes,\%othertypes,\%titles);
 7303: }
 7304: 
 7305: sub loadbalance_rule_row {
 7306:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 7307:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 7308:     my @rulenames;
 7309:     my %ruletitles = &offloadtype_text();
 7310:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 7311:         @rulenames = ('balancer','offloadedto','specific');
 7312:     } else {
 7313:         @rulenames = ('default','homeserver');
 7314:         if ($type eq '_LC_external') {
 7315:             push(@rulenames,'externalbalancer');
 7316:         } else {
 7317:             push(@rulenames,'specific');
 7318:         }
 7319:         push(@rulenames,'none');
 7320:     }
 7321:     my $style = $targets_div_style;
 7322:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 7323:         $style = $homedom_div_style;
 7324:     }
 7325:     my $space;
 7326:     if ($islast && $num == 1) {
 7327:         $space = '<div style="display:inline-block;">&nbsp;</div>';
 7328:     }
 7329:     my $output =
 7330:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td style="vertical-align: top">'.$space.
 7331:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 7332:         '<td valaign="top">'.$space.
 7333:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 7334:     for (my $i=0; $i<@rulenames; $i++) {
 7335:         my $rule = $rulenames[$i];
 7336:         my ($checked,$extra);
 7337:         if ($rulenames[$i] eq 'default') {
 7338:             $rule = '';
 7339:         }
 7340:         if ($rulenames[$i] eq 'specific') {
 7341:             if (ref($servers) eq 'HASH') {
 7342:                 my $default;
 7343:                 if (($current ne '') && (exists($servers->{$current}))) {
 7344:                     $checked = ' checked="checked"';
 7345:                 }
 7346:                 unless ($checked) {
 7347:                     $default = ' selected="selected"';
 7348:                 }
 7349:                 $extra =
 7350:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 7351:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 7352:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 7353:                     '<option value=""'.$default.'></option>'."\n";
 7354:                 foreach my $server (sort(keys(%{$servers}))) {
 7355:                     if (ref($currbalancer) eq 'HASH') {
 7356:                         next if (exists($currbalancer->{$server}));
 7357:                     }
 7358:                     my $selected;
 7359:                     if ($server eq $current) {
 7360:                         $selected = ' selected="selected"';
 7361:                     }
 7362:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 7363:                 }
 7364:                 $extra .= '</select>';
 7365:             }
 7366:         } elsif ($rule eq $current) {
 7367:             $checked = ' checked="checked"';
 7368:         }
 7369:         $output .= '<span class="LC_nobreak"><label>'.
 7370:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 7371:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 7372:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 7373:                    ')"'.$checked.' />&nbsp;';
 7374:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 7375:             $output .= $ruletitles{'particular'};
 7376:         } else {
 7377:             $output .= $ruletitles{$rulenames[$i]};
 7378:         }
 7379:         $output .= '</label>'.$extra.'</span><br />'."\n";
 7380:     }
 7381:     $output .= '</div></td></tr>'."\n";
 7382:     return $output;
 7383: }
 7384: 
 7385: sub offloadtype_text {
 7386:     my %ruletitles = &Apache::lonlocal::texthash (
 7387:            'default'          => 'Offloads to default destinations',
 7388:            'homeserver'       => "Offloads to user's home server",
 7389:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 7390:            'specific'         => 'Offloads to specific server',
 7391:            'none'             => 'No offload',
 7392:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 7393:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 7394:            'particular'       => 'Session hosted (after re-auth) on server:',
 7395:     );
 7396:     return %ruletitles;
 7397: }
 7398: 
 7399: sub sparestype_titles {
 7400:     my %typestitles = &Apache::lonlocal::texthash (
 7401:                           'primary' => 'primary',
 7402:                           'default' => 'default',
 7403:                       );
 7404:     return %typestitles;
 7405: }
 7406: 
 7407: sub contact_titles {
 7408:     my %titles = &Apache::lonlocal::texthash (
 7409:                    'supportemail'    => 'Support E-mail address',
 7410:                    'adminemail'      => 'Default Server Admin E-mail address',
 7411:                    'errormail'       => 'Error reports to be e-mailed to',
 7412:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 7413:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 7414:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 7415:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 7416:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 7417:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 7418:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 7419:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 7420:                    'errorthreshold'  => 'Error/warning threshold for status e-mail',
 7421:                    'errorsysmail'    => 'Error threshold for e-mail to core group',
 7422:                    'errorweights'    => 'Weights used to compute error count',
 7423:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 7424:                  );
 7425:     my %short_titles = &Apache::lonlocal::texthash (
 7426:                            adminemail   => 'Admin E-mail address',
 7427:                            supportemail => 'Support E-mail',
 7428:                        );   
 7429:     return (\%titles,\%short_titles);
 7430: }
 7431: 
 7432: sub helpform_fields {
 7433:     my %titles =  &Apache::lonlocal::texthash (
 7434:                        'username'   => 'Name',
 7435:                        'user'       => 'Username/domain',
 7436:                        'phone'      => 'Phone',
 7437:                        'cc'         => 'Cc e-mail',
 7438:                        'course'     => 'Course Details',
 7439:                        'section'    => 'Sections',
 7440:                        'screenshot' => 'File upload',
 7441:     );
 7442:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 7443:     my %possoptions = (
 7444:                         username     => ['yes','no','req'],
 7445:                         phone        => ['yes','no','req'],
 7446:                         user         => ['yes','no'],
 7447:                         cc           => ['yes','no'],
 7448:                         course       => ['yes','no'],
 7449:                         section      => ['yes','no'],
 7450:                         screenshot   => ['yes','no'],
 7451:                       );
 7452:     my %fieldoptions = &Apache::lonlocal::texthash (
 7453:                          'yes'  => 'Optional',
 7454:                          'req'  => 'Required',
 7455:                          'no'   => "Not shown",
 7456:     );
 7457:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 7458: }
 7459: 
 7460: sub tool_titles {
 7461:     my %titles = &Apache::lonlocal::texthash (
 7462:                      aboutme    => 'Personal web page',
 7463:                      blog       => 'Blog',
 7464:                      webdav     => 'WebDAV',
 7465:                      portfolio  => 'Portfolio',
 7466:                      official   => 'Official courses (with institutional codes)',
 7467:                      unofficial => 'Unofficial courses',
 7468:                      community  => 'Communities',
 7469:                      textbook   => 'Textbook courses',
 7470:                      placement  => 'Placement tests',
 7471:                  );
 7472:     return %titles;
 7473: }
 7474: 
 7475: sub courserequest_titles {
 7476:     my %titles = &Apache::lonlocal::texthash (
 7477:                                    official   => 'Official',
 7478:                                    unofficial => 'Unofficial',
 7479:                                    community  => 'Communities',
 7480:                                    textbook   => 'Textbook',
 7481:                                    placement  => 'Placement tests',
 7482:                                    lti        => 'LTI Provider',
 7483:                                    norequest  => 'Not allowed',
 7484:                                    approval   => 'Approval by DC',
 7485:                                    validate   => 'With validation',
 7486:                                    autolimit  => 'Numerical limit',
 7487:                                    unlimited  => '(blank for unlimited)',
 7488:                  );
 7489:     return %titles;
 7490: }
 7491: 
 7492: sub authorrequest_titles {
 7493:     my %titles = &Apache::lonlocal::texthash (
 7494:                                    norequest  => 'Not allowed',
 7495:                                    approval   => 'Approval by Dom. Coord.',
 7496:                                    automatic  => 'Automatic approval',
 7497:                  );
 7498:     return %titles;
 7499: }
 7500: 
 7501: sub courserequest_conditions {
 7502:     my %conditions = &Apache::lonlocal::texthash (
 7503:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 7504:        validate   => '(Processing of request subject to institutional validation).',
 7505:                  );
 7506:     return %conditions;
 7507: }
 7508: 
 7509: 
 7510: sub print_usercreation {
 7511:     my ($position,$dom,$settings,$rowtotal) = @_;
 7512:     my $numinrow = 4;
 7513:     my $datatable;
 7514:     if ($position eq 'top') {
 7515:         $$rowtotal ++;
 7516:         my $rowcount = 0;
 7517:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 7518:         if (ref($rules) eq 'HASH') {
 7519:             if (keys(%{$rules}) > 0) {
 7520:                 $datatable .= &user_formats_row('username',$settings,$rules,
 7521:                                                 $ruleorder,$numinrow,$rowcount);
 7522:                 $$rowtotal ++;
 7523:                 $rowcount ++;
 7524:             }
 7525:         }
 7526:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 7527:         if (ref($idrules) eq 'HASH') {
 7528:             if (keys(%{$idrules}) > 0) {
 7529:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 7530:                                                 $idruleorder,$numinrow,$rowcount);
 7531:                 $$rowtotal ++;
 7532:                 $rowcount ++;
 7533:             }
 7534:         }
 7535:         if ($rowcount == 0) {
 7536:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 7537:             $$rowtotal ++;
 7538:             $rowcount ++;
 7539:         }
 7540:     } elsif ($position eq 'middle') {
 7541:         my @creators = ('author','course','requestcrs');
 7542:         my ($rules,$ruleorder) =
 7543:             &Apache::lonnet::inst_userrules($dom,'username');
 7544:         my %lt = &usercreation_types();
 7545:         my %checked;
 7546:         if (ref($settings) eq 'HASH') {
 7547:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 7548:                 foreach my $item (@creators) {
 7549:                     $checked{$item} = $settings->{'cancreate'}{$item};
 7550:                 }
 7551:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 7552:                 foreach my $item (@creators) {
 7553:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 7554:                         $checked{$item} = 'none';
 7555:                     }
 7556:                 }
 7557:             }
 7558:         }
 7559:         my $rownum = 0;
 7560:         foreach my $item (@creators) {
 7561:             $rownum ++;
 7562:             if ($checked{$item} eq '') {
 7563:                 $checked{$item} = 'any';
 7564:             }
 7565:             my $css_class;
 7566:             if ($rownum%2) {
 7567:                 $css_class = '';
 7568:             } else {
 7569:                 $css_class = ' class="LC_odd_row" ';
 7570:             }
 7571:             $datatable .= '<tr'.$css_class.'>'.
 7572:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 7573:                          '</span></td><td style="text-align: right">';
 7574:             my @options = ('any');
 7575:             if (ref($rules) eq 'HASH') {
 7576:                 if (keys(%{$rules}) > 0) {
 7577:                     push(@options,('official','unofficial'));
 7578:                 }
 7579:             }
 7580:             push(@options,'none');
 7581:             foreach my $option (@options) {
 7582:                 my $type = 'radio';
 7583:                 my $check = ' ';
 7584:                 if ($checked{$item} eq $option) {
 7585:                     $check = ' checked="checked" ';
 7586:                 } 
 7587:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7588:                               '<input type="'.$type.'" name="can_createuser_'.
 7589:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 7590:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 7591:             }
 7592:             $datatable .= '</td></tr>';
 7593:         }
 7594:     } else {
 7595:         my @contexts = ('author','course','domain');
 7596:         my @authtypes = ('int','krb4','krb5','loc','lti');
 7597:         my %checked;
 7598:         if (ref($settings) eq 'HASH') {
 7599:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 7600:                 foreach my $item (@contexts) {
 7601:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 7602:                         foreach my $auth (@authtypes) {
 7603:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 7604:                                 $checked{$item}{$auth} = ' checked="checked" ';
 7605:                             }
 7606:                         }
 7607:                     }
 7608:                 }
 7609:             }
 7610:         } else {
 7611:             foreach my $item (@contexts) {
 7612:                 foreach my $auth (@authtypes) {
 7613:                     $checked{$item}{$auth} = ' checked="checked" ';
 7614:                 }
 7615:             }
 7616:         }
 7617:         my %title = &context_names();
 7618:         my %authname = &authtype_names();
 7619:         my $rownum = 0;
 7620:         my $css_class; 
 7621:         foreach my $item (@contexts) {
 7622:             if ($rownum%2) {
 7623:                 $css_class = '';
 7624:             } else {
 7625:                 $css_class = ' class="LC_odd_row" ';
 7626:             }
 7627:             $datatable .=   '<tr'.$css_class.'>'.
 7628:                             '<td>'.$title{$item}.
 7629:                             '</td><td class="LC_left_item">'.
 7630:                             '<span class="LC_nobreak">';
 7631:             foreach my $auth (@authtypes) {
 7632:                 $datatable .= '<label>'. 
 7633:                               '<input type="checkbox" name="'.$item.'_auth" '.
 7634:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 7635:                               $authname{$auth}.'</label>&nbsp;';
 7636:             }
 7637:             $datatable .= '</span></td></tr>';
 7638:             $rownum ++;
 7639:         }
 7640:         $$rowtotal += $rownum;
 7641:     }
 7642:     return $datatable;
 7643: }
 7644: 
 7645: sub print_selfcreation {
 7646:     my ($position,$dom,$settings,$rowtotal) = @_;
 7647:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 7648:         $emaildomain,$datatable);
 7649:     if (ref($settings) eq 'HASH') {
 7650:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 7651:             $createsettings = $settings->{'cancreate'};
 7652:             if (ref($createsettings) eq 'HASH') {
 7653:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 7654:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 7655:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 7656:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 7657:                         @selfcreate = ('email','login','sso');
 7658:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 7659:                         @selfcreate = ($createsettings->{'selfcreate'});
 7660:                     }
 7661:                 }
 7662:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 7663:                     $processing = $createsettings->{'selfcreateprocessing'};
 7664:                 }
 7665:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 7666:                     $emailoptions = $createsettings->{'emailoptions'};
 7667:                 }
 7668:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 7669:                     $emailverified = $createsettings->{'emailverified'};
 7670:                 }
 7671:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 7672:                     $emaildomain = $createsettings->{'emaildomain'};
 7673:                 }
 7674:             }
 7675:         }
 7676:     }
 7677:     my %radiohash;
 7678:     my $numinrow = 4;
 7679:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 7680:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7681:     if ($position eq 'top') {
 7682:         my %choices = &Apache::lonlocal::texthash (
 7683:                                                       cancreate_login      => 'Institutional Login',
 7684:                                                       cancreate_sso        => 'Institutional Single Sign On',
 7685:                                                   );
 7686:         my @toggles = sort(keys(%choices));
 7687:         my %defaultchecked = (
 7688:                                'cancreate_login' => 'off',
 7689:                                'cancreate_sso'   => 'off',
 7690:                              );
 7691:         my ($onclick,$itemcount);
 7692:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 7693:                                                      \%choices,$itemcount,$onclick);
 7694:         $$rowtotal += $itemcount;
 7695:         
 7696:         if (ref($usertypes) eq 'HASH') {
 7697:             if (keys(%{$usertypes}) > 0) {
 7698:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 7699:                                              $dom,$numinrow,$othertitle,
 7700:                                              'statustocreate',$rowtotal);
 7701:                 $$rowtotal ++;
 7702:             }
 7703:         }
 7704:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 7705:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 7706:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 7707:         my $rem;
 7708:         my $numperrow = 2;
 7709:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 7710:         $datatable .= '<tr'.$css_class.'>'.
 7711:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 7712:                      '<td class="LC_left_item">'."\n".
 7713:                      '<table>'."\n";
 7714:         for (my $i=0; $i<@fields; $i++) {
 7715:             $rem = $i%($numperrow);
 7716:             if ($rem == 0) {
 7717:                 if ($i > 0) {
 7718:                     $datatable .= '</tr>';
 7719:                 }
 7720:                 $datatable .= '<tr>';
 7721:             }
 7722:             my $currval;
 7723:             if (ref($createsettings) eq 'HASH') {
 7724:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 7725:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 7726:                 }
 7727:             }
 7728:             $datatable .= '<td class="LC_left_item">'.
 7729:                           '<span class="LC_nobreak">'.
 7730:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 7731:                           'value="'.$currval.'" size="10" />&nbsp;'.
 7732:                           $fieldtitles{$fields[$i]}.'</span></td>';
 7733:         }
 7734:         my $colsleft = $numperrow - $rem;
 7735:         if ($colsleft > 1 ) {
 7736:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7737:                          '&nbsp;</td>';
 7738:         } elsif ($colsleft == 1) {
 7739:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 7740:         }
 7741:         $datatable .= '</tr></table></td></tr>';
 7742:         $$rowtotal ++;
 7743:     } elsif ($position eq 'middle') {
 7744:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 7745:         my @posstypes;
 7746:         if (ref($types) eq 'ARRAY') {
 7747:             @posstypes = @{$types};
 7748:         }
 7749:         unless (grep(/^default$/,@posstypes)) {
 7750:             push(@posstypes,'default');
 7751:         }
 7752:         my %usertypeshash;
 7753:         if (ref($usertypes) eq 'HASH') {
 7754:             %usertypeshash = %{$usertypes};
 7755:         }
 7756:         $usertypeshash{'default'} = $othertitle;
 7757:         foreach my $status (@posstypes) {
 7758:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 7759:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 7760:             $$rowtotal ++;
 7761:         }
 7762:     } else {
 7763:         my %choices = &Apache::lonlocal::texthash (
 7764:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 7765:                                                   );
 7766:         my @toggles = sort(keys(%choices));
 7767:         my %defaultchecked = (
 7768:                                'cancreate_email' => 'off',
 7769:                              );
 7770:         my $customclass = 'LC_selfcreate_email';
 7771:         my $classprefix = 'LC_canmodify_emailusername_';
 7772:         my $optionsprefix = 'LC_options_emailusername_';
 7773:         my $display = 'none';
 7774:         my $rowstyle = 'display:none';
 7775:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 7776:             $display = 'block';
 7777:             $rowstyle = 'display:table-row';
 7778:         }
 7779:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
 7780:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 7781:                                                      \%choices,$$rowtotal,$onclick);
 7782:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
 7783:                                          $rowstyle);
 7784:         $$rowtotal ++;
 7785:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
 7786:                                       $rowstyle);
 7787:         $$rowtotal ++;
 7788:         my (@ordered,@posstypes,%usertypeshash);
 7789:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 7790:         my ($emailrules,$emailruleorder) =
 7791:             &Apache::lonnet::inst_userrules($dom,'email');
 7792:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7793:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7794:         if (ref($types) eq 'ARRAY') {
 7795:             @posstypes = @{$types};
 7796:         }
 7797:         if (@posstypes) {
 7798:             unless (grep(/^default$/,@posstypes)) {
 7799:                 push(@posstypes,'default');
 7800:             }
 7801:             if (ref($usertypes) eq 'HASH') {
 7802:                 %usertypeshash = %{$usertypes};
 7803:             }
 7804:             my $currassign;
 7805:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
 7806:                 $currassign = {
 7807:                                   selfassign => $domdefaults{'inststatusguest'},
 7808:                               };
 7809:                 @ordered = @{$domdefaults{'inststatusguest'}};
 7810:             } else {
 7811:                 $currassign = { selfassign => [] };
 7812:             }
 7813:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
 7814:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
 7815:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
 7816:                                          $numinrow,$othertitle,'selfassign',
 7817:                                          $rowtotal,$onclicktypes,$customclass,
 7818:                                          $rowstyle);
 7819:             $$rowtotal ++;
 7820:             $usertypeshash{'default'} = $othertitle;
 7821:             foreach my $status (@posstypes) {
 7822:                 my $css_class;
 7823:                 if ($$rowtotal%2) {
 7824:                     $css_class = 'LC_odd_row ';
 7825:                 }
 7826:                 $css_class .= $customclass;
 7827:                 my $rowid = $optionsprefix.$status;
 7828:                 my $hidden = 1;
 7829:                 my $currstyle = 'display:none';
 7830:                 if (grep(/^\Q$status\E$/,@ordered)) {
 7831:                     $currstyle = $rowstyle;
 7832:                     $hidden = 0; 
 7833:                 }
 7834:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 7835:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
 7836:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
 7837:                 unless ($hidden) {
 7838:                     $$rowtotal ++;
 7839:                 }
 7840:             }
 7841:         } else {
 7842:             my $css_class;
 7843:             if ($$rowtotal%2) {
 7844:                 $css_class = 'LC_odd_row ';
 7845:             }
 7846:             $css_class .= $customclass;
 7847:             $usertypeshash{'default'} = $othertitle;
 7848:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 7849:                                          $emailrules,$emailruleorder,$settings,'default','',
 7850:                                          $othertitle,$css_class,$rowstyle,$intdom);
 7851:             $$rowtotal ++;
 7852:         }
 7853:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 7854:         $numinrow = 1;
 7855:         if (@posstypes) {
 7856:             foreach my $status (@posstypes) {
 7857:                 my $rowid = $classprefix.$status;
 7858:                 my $datarowstyle = 'display:none';
 7859:                 if (grep(/^\Q$status\E$/,@ordered)) { 
 7860:                     $datarowstyle = $rowstyle; 
 7861:                 }
 7862:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 7863:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 7864:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
 7865:                 unless ($datarowstyle eq 'display:none') {
 7866:                     $$rowtotal ++;
 7867:                 }
 7868:             }
 7869:         } else {
 7870:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
 7871:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 7872:                                                    $infotitles,'',$customclass,$rowstyle);
 7873:         }
 7874:     }
 7875:     return $datatable;
 7876: }
 7877: 
 7878: sub selfcreate_javascript {
 7879:     return <<"ENDSCRIPT";
 7880: 
 7881: <script type="text/javascript">
 7882: // <![CDATA[
 7883: 
 7884: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
 7885:     var x = document.getElementsByClassName(target);
 7886:     var insttypes = 0;
 7887:     var insttypeRegExp = new RegExp(prefix);
 7888:     if ((x.length != undefined) && (x.length > 0)) {
 7889:         if (form.elements[radio].length != undefined) {
 7890:             for (var i=0; i<form.elements[radio].length; i++) {
 7891:                 if (form.elements[radio][i].checked) {
 7892:                     if (form.elements[radio][i].value == 1) {
 7893:                         for (var j=0; j<x.length; j++) {
 7894:                             if (x[j].id == 'undefined') {
 7895:                                 x[j].style.display = 'table-row';
 7896:                             } else if (insttypeRegExp.test(x[j].id)) {
 7897:                                 insttypes ++;
 7898:                             } else {
 7899:                                 x[j].style.display = 'table-row';
 7900:                             }
 7901:                         }
 7902:                     } else {
 7903:                         for (var j=0; j<x.length; j++) {
 7904:                             x[j].style.display = 'none';
 7905:                         }
 7906:                     }
 7907:                     break;
 7908:                 }
 7909:             }
 7910:             if (insttypes > 0) {
 7911:                 toggleDataRow(form,checkbox,target,altprefix);
 7912:                 toggleDataRow(form,checkbox,target,prefix,1);
 7913:             }
 7914:         }
 7915:     }
 7916:     return;
 7917: }
 7918: 
 7919: function toggleDataRow(form,checkbox,target,prefix,docount) {
 7920:     if (form.elements[checkbox].length != undefined) {
 7921:         var count = 0;
 7922:         if (docount) {
 7923:             for (var i=0; i<form.elements[checkbox].length; i++) {
 7924:                 if (form.elements[checkbox][i].checked) {
 7925:                     count ++;
 7926:                 }
 7927:             }
 7928:         }
 7929:         for (var i=0; i<form.elements[checkbox].length; i++) {
 7930:             var type = form.elements[checkbox][i].value;
 7931:             if (document.getElementById(prefix+type)) {
 7932:                 if (form.elements[checkbox][i].checked) {
 7933:                     document.getElementById(prefix+type).style.display = 'table-row';
 7934:                     if (count % 2 == 1) {
 7935:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 7936:                     } else {
 7937:                         document.getElementById(prefix+type).className = target;
 7938:                     }
 7939:                     count ++;
 7940:                 } else {
 7941:                     document.getElementById(prefix+type).style.display = 'none';
 7942:                 }
 7943:             }
 7944:         }
 7945:     }
 7946:     return;
 7947: }
 7948: 
 7949: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
 7950:     var caller = radio+'_'+status;
 7951:     if (form.elements[caller].length != undefined) {
 7952:         for (var i=0; i<form.elements[caller].length; i++) {
 7953:             if (form.elements[caller][i].checked) {
 7954:                 if (document.getElementById(altprefix+'_inst_'+status)) {
 7955:                     var curr = form.elements[caller][i].value;
 7956:                     if (prefix) {
 7957:                         document.getElementById(prefix+'_'+status).style.display = 'none';
 7958:                     }
 7959:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
 7960:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
 7961:                     if (curr == 'custom') {
 7962:                         if (prefix) { 
 7963:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
 7964:                         }
 7965:                     } else if (curr == 'inst') {
 7966:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
 7967:                     } else if (curr == 'noninst') {
 7968:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
 7969:                     }
 7970:                     break;
 7971:                 }
 7972:             }
 7973:         }
 7974:     }
 7975: }
 7976: 
 7977: // ]]>
 7978: </script>
 7979: 
 7980: ENDSCRIPT
 7981: }
 7982: 
 7983: sub noninst_users {
 7984:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
 7985:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_; 
 7986:     my $class = 'LC_left_item';
 7987:     if ($css_class) {
 7988:         $css_class = ' class="'.$css_class.'"'; 
 7989:     }
 7990:     if ($rowid) {
 7991:         $rowid = ' id="'.$rowid.'"';
 7992:     }
 7993:     if ($rowstyle) {
 7994:         $rowstyle = ' style="'.$rowstyle.'"';
 7995:     }
 7996:     my ($output,$description);
 7997:     if ($type eq 'default') {
 7998:         $description = &mt('Requests for: [_1]',$typetitle);
 7999:     } else {
 8000:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
 8001:     }
 8002:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 8003:               "<td>$description</td>\n".           
 8004:               '<td class="'.$class.'" colspan="2">'.
 8005:               '<table><tr>';
 8006:     my %headers = &Apache::lonlocal::texthash( 
 8007:               approve  => 'Processing',
 8008:               email    => 'E-mail',
 8009:               username => 'Username',
 8010:     );
 8011:     foreach my $item ('approve','email','username') {
 8012:         $output .= '<th>'.$headers{$item}.'</th>';
 8013:     }
 8014:     $output .= '</tr><tr>';
 8015:     foreach my $item ('approve','email','username') {
 8016:         $output .= '<td style="vertical-align: top">';
 8017:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
 8018:         if ($item eq 'approve') {
 8019:             %choices = &Apache::lonlocal::texthash (
 8020:                                                      automatic => 'Automatically approved',
 8021:                                                      approval  => 'Queued for approval',
 8022:                                                    );
 8023:             @options = ('automatic','approval');
 8024:             $hashref = $processing;
 8025:             $defoption = 'automatic';
 8026:             $name = 'cancreate_emailprocess_'.$type;
 8027:         } elsif ($item eq 'email') {
 8028:             %choices = &Apache::lonlocal::texthash (
 8029:                                                      any     => 'Any e-mail',
 8030:                                                      inst    => 'Institutional only',
 8031:                                                      noninst => 'Non-institutional only',
 8032:                                                      custom  => 'Custom restrictions',
 8033:                                                    );
 8034:             @options = ('any','inst','noninst');
 8035:             my $showcustom;
 8036:             if (ref($emailrules) eq 'HASH') {
 8037:                 if (keys(%{$emailrules}) > 0) {
 8038:                     push(@options,'custom');
 8039:                     $showcustom = 'cancreate_emailrule';
 8040:                     if (ref($settings) eq 'HASH') {
 8041:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 8042:                             foreach my $rule (@{$settings->{'email_rule'}}) {
 8043:                                 if (exists($emailrules->{$rule})) {
 8044:                                     $hascustom ++;
 8045:                                 }
 8046:                             }
 8047:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
 8048:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
 8049:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
 8050:                                     if (exists($emailrules->{$rule})) {
 8051:                                         $hascustom ++;
 8052:                                     }
 8053:                                 }
 8054:                             }
 8055:                         }
 8056:                     }
 8057:                 }
 8058:             }
 8059:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
 8060:                                                      "'cancreate_emaildomain','$type'".');"';
 8061:             $hashref = $emailoptions;
 8062:             $defoption = 'any';
 8063:             $name = 'cancreate_emailoptions_'.$type;
 8064:         } elsif ($item eq 'username') {
 8065:             %choices = &Apache::lonlocal::texthash (
 8066:                                                      all    => 'Same as e-mail',
 8067:                                                      first  => 'Omit @domain',
 8068:                                                      free   => 'Free to choose',
 8069:                                                    );
 8070:             @options = ('all','first','free');
 8071:             $hashref = $emailverified;
 8072:             $defoption = 'all';
 8073:             $name = 'cancreate_usernameoptions_'.$type;
 8074:         }
 8075:         foreach my $option (@options) {
 8076:             my $checked;
 8077:             if (ref($hashref) eq 'HASH') {
 8078:                 if ($type eq '') {
 8079:                     if (!exists($hashref->{'default'})) {
 8080:                         if ($option eq $defoption) {
 8081:                             $checked = ' checked="checked"';
 8082:                         }
 8083:                     } else {
 8084:                         if ($hashref->{'default'} eq $option) {
 8085:                             $checked = ' checked="checked"';
 8086:                         }
 8087:                     }
 8088:                 } else {
 8089:                     if (!exists($hashref->{$type})) {
 8090:                         if ($option eq $defoption) {
 8091:                             $checked = ' checked="checked"';
 8092:                         }
 8093:                     } else {
 8094:                         if ($hashref->{$type} eq $option) {
 8095:                             $checked = ' checked="checked"';
 8096:                         }
 8097:                     }
 8098:                 }
 8099:             } elsif (($item eq 'email') && ($hascustom)) {
 8100:                 if ($option eq 'custom') {
 8101:                     $checked = ' checked="checked"';
 8102:                 }
 8103:             } elsif ($option eq $defoption) {
 8104:                 $checked = ' checked="checked"';
 8105:             }
 8106:             $output .= '<span class="LC_nobreak"><label>'.
 8107:                        '<input type="radio" name="'.$name.'"'.
 8108:                        $checked.' value="'.$option.'"'.$onclick.' />'.
 8109:                        $choices{$option}.'</label></span><br />';
 8110:             if ($item eq 'email') {
 8111:                 if ($option eq 'custom') {
 8112:                     my $id = 'cancreate_emailrule_'.$type;
 8113:                     my $display = 'none';
 8114:                     if ($checked) {
 8115:                         $display = 'inline';
 8116:                     }
 8117:                     my $numinrow = 2;
 8118:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
 8119:                                '<legend>'.&mt('Disallow').'</legend><table>'.
 8120:                                &user_formats_row('email',$settings,$emailrules,
 8121:                                                  $emailruleorder,$numinrow,'',$type);
 8122:                               '</table></fieldset>';
 8123:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
 8124:                     my %text = &Apache::lonlocal::texthash (
 8125:                                                              inst    => 'must end:',
 8126:                                                              noninst => 'cannot end:',
 8127:                                                            );
 8128:                     my $value;
 8129:                     if (ref($emaildomain) eq 'HASH') {
 8130:                         if (ref($emaildomain->{$type}) eq 'HASH') {
 8131:                             $value = $emaildomain->{$type}->{$option}; 
 8132:                         }
 8133:                     }
 8134:                     if ($value eq '') {
 8135:                         $value = '@'.$intdom;
 8136:                     }
 8137:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
 8138:                     my $display = 'none';
 8139:                     if ($checked) {
 8140:                         $display = 'inline';
 8141:                     }
 8142:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
 8143:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
 8144:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
 8145:                                '</div>';
 8146:                 }
 8147:             }
 8148:         }
 8149:         $output .= '</td>'."\n";
 8150:     }
 8151:     $output .= "</tr></table></td></tr>\n";
 8152:     return $output;
 8153: }
 8154: 
 8155: sub captcha_choice {
 8156:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
 8157:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
 8158:         $vertext,$currver);
 8159:     my %lt = &captcha_phrases();
 8160:     $keyentry = 'hidden';
 8161:     my $colspan=2;
 8162:     if ($context eq 'cancreate') {
 8163:         $rowname = &mt('CAPTCHA validation');
 8164:     } elsif ($context eq 'login') {
 8165:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
 8166:     } elsif ($context eq 'passwords') {
 8167:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
 8168:         $colspan=1;
 8169:     }
 8170:     if (ref($settings) eq 'HASH') {
 8171:         if ($settings->{'captcha'}) {
 8172:             $checked{$settings->{'captcha'}} = ' checked="checked"';
 8173:         } else {
 8174:             $checked{'original'} = ' checked="checked"';
 8175:         }
 8176:         if ($settings->{'captcha'} eq 'recaptcha') {
 8177:             $pubtext = $lt{'pub'};
 8178:             $privtext = $lt{'priv'};
 8179:             $keyentry = 'text';
 8180:             $vertext = $lt{'ver'};
 8181:             $currver = $settings->{'recaptchaversion'};
 8182:             if ($currver ne '2') {
 8183:                 $currver = 1;
 8184:             }
 8185:         }
 8186:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
 8187:             $currpub = $settings->{'recaptchakeys'}{'public'};
 8188:             $currpriv = $settings->{'recaptchakeys'}{'private'};
 8189:         }
 8190:     } else {
 8191:         $checked{'original'} = ' checked="checked"';
 8192:     }
 8193:     my $css_class;
 8194:     if ($itemcount%2) {
 8195:         $css_class = 'LC_odd_row';
 8196:     }
 8197:     if ($customcss) {
 8198:         $css_class .= " $customcss";
 8199:     }
 8200:     $css_class =~ s/^\s+//;
 8201:     if ($css_class) {
 8202:         $css_class = ' class="'.$css_class.'"';
 8203:     }
 8204:     if ($rowstyle) {
 8205:         $css_class .= ' style="'.$rowstyle.'"';
 8206:     }
 8207:     my $output = '<tr'.$css_class.'>'.
 8208:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
 8209:                  '<table><tr><td>'."\n";
 8210:     foreach my $option ('original','recaptcha','notused') {
 8211:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
 8212:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
 8213:                    $lt{$option}.'</label></span>';
 8214:         unless ($option eq 'notused') {
 8215:             $output .= ('&nbsp;'x2)."\n";
 8216:         }
 8217:     }
 8218: #
 8219: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
 8220: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
 8221: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
 8222: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
 8223: #
 8224:     $output .= '</td></tr>'."\n".
 8225:                '<tr><td class="LC_zero_height">'."\n".
 8226:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
 8227:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
 8228:                $currpub.'" size="40" /></span><br />'."\n".
 8229:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
 8230:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
 8231:                $currpriv.'" size="40" /></span><br />'.
 8232:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
 8233:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
 8234:                $currver.'" size="3" /></span><br />'.
 8235:                '</td></tr></table>'."\n".
 8236:                '</td></tr>';
 8237:     return $output;
 8238: }
 8239: 
 8240: sub user_formats_row {
 8241:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
 8242:     my $output;
 8243:     my %text = (
 8244:                    'username' => 'new usernames',
 8245:                    'id'       => 'IDs',
 8246:                );
 8247:     unless ($type eq 'email') {
 8248:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 8249:         $output = '<tr '.$css_class.'>'.
 8250:                   '<td><span class="LC_nobreak">'.
 8251:                   &mt("Format rules to check for $text{$type}: ").
 8252:                   '</td><td class="LC_left_item" colspan="2"><table>';
 8253:     }
 8254:     my $rem;
 8255:     if (ref($ruleorder) eq 'ARRAY') {
 8256:         for (my $i=0; $i<@{$ruleorder}; $i++) {
 8257:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
 8258:                 my $rem = $i%($numinrow);
 8259:                 if ($rem == 0) {
 8260:                     if ($i > 0) {
 8261:                         $output .= '</tr>';
 8262:                     }
 8263:                     $output .= '<tr>';
 8264:                 }
 8265:                 my $check = ' ';
 8266:                 if (ref($settings) eq 'HASH') {
 8267:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
 8268:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
 8269:                             $check = ' checked="checked" ';
 8270:                         }
 8271:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
 8272:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
 8273:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
 8274:                                 $check = ' checked="checked" ';
 8275:                             }
 8276:                         }
 8277:                     }
 8278:                 }
 8279:                 my $name = $type.'_rule';
 8280:                 if ($type eq 'email') {
 8281:                     $name .= '_'.$status;
 8282:                 }
 8283:                 $output .= '<td class="LC_left_item">'.
 8284:                            '<span class="LC_nobreak"><label>'.
 8285:                            '<input type="checkbox" name="'.$name.'" '.
 8286:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
 8287:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
 8288:             }
 8289:         }
 8290:         $rem = @{$ruleorder}%($numinrow);
 8291:     }
 8292:     my $colsleft;
 8293:     if ($rem) {
 8294:         $colsleft = $numinrow - $rem;
 8295:     }
 8296:     if ($colsleft > 1 ) {
 8297:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8298:                    '&nbsp;</td>';
 8299:     } elsif ($colsleft == 1) {
 8300:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 8301:     }
 8302:     $output .= '</tr></table>';
 8303:     unless ($type eq 'email') {
 8304:         $output .= '</td></tr>';
 8305:     }
 8306:     return $output;
 8307: }
 8308: 
 8309: sub usercreation_types {
 8310:     my %lt = &Apache::lonlocal::texthash (
 8311:                     author     => 'When adding a co-author',
 8312:                     course     => 'When adding a user to a course',
 8313:                     requestcrs => 'When requesting a course',
 8314:                     any        => 'Any',
 8315:                     official   => 'Institutional only ',
 8316:                     unofficial => 'Non-institutional only',
 8317:                     none       => 'None',
 8318:     );
 8319:     return %lt;
 8320: }
 8321: 
 8322: sub selfcreation_types {
 8323:     my %lt = &Apache::lonlocal::texthash (
 8324:                     selfcreate => 'User creates own account',
 8325:                     any        => 'Any',
 8326:                     official   => 'Institutional only ',
 8327:                     unofficial => 'Non-institutional only',
 8328:                     email      => 'E-mail address',
 8329:                     login      => 'Institutional Login',
 8330:                     sso        => 'SSO',
 8331:              );
 8332: }
 8333: 
 8334: sub authtype_names {
 8335:     my %lt = &Apache::lonlocal::texthash(
 8336:                       int    => 'Internal',
 8337:                       krb4   => 'Kerberos 4',
 8338:                       krb5   => 'Kerberos 5',
 8339:                       loc    => 'Local',
 8340:                       lti    => 'LTI',
 8341:                   );
 8342:     return %lt;
 8343: }
 8344: 
 8345: sub context_names {
 8346:     my %context_title = &Apache::lonlocal::texthash(
 8347:        author => 'Creating users when an Author',
 8348:        course => 'Creating users when in a course',
 8349:        domain => 'Creating users when a Domain Coordinator',
 8350:     );
 8351:     return %context_title;
 8352: }
 8353: 
 8354: sub print_usermodification {
 8355:     my ($position,$dom,$settings,$rowtotal) = @_;
 8356:     my $numinrow = 4;
 8357:     my ($context,$datatable,$rowcount);
 8358:     if ($position eq 'top') {
 8359:         $rowcount = 0;
 8360:         $context = 'author'; 
 8361:         foreach my $role ('ca','aa') {
 8362:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 8363:                                                    $numinrow,$rowcount);
 8364:             $$rowtotal ++;
 8365:             $rowcount ++;
 8366:         }
 8367:     } elsif ($position eq 'bottom') {
 8368:         $context = 'course';
 8369:         $rowcount = 0;
 8370:         foreach my $role ('st','ep','ta','in','cr') {
 8371:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 8372:                                                    $numinrow,$rowcount);
 8373:             $$rowtotal ++;
 8374:             $rowcount ++;
 8375:         }
 8376:     }
 8377:     return $datatable;
 8378: }
 8379: 
 8380: sub print_defaults {
 8381:     my ($position,$dom,$settings,$rowtotal) = @_;
 8382:     my $rownum = 0;
 8383:     my ($datatable,$css_class,$titles);
 8384:     unless ($position eq 'bottom') {
 8385:         $titles = &defaults_titles($dom);
 8386:     }
 8387:     if ($position eq 'top') {
 8388:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
 8389:                      'datelocale_def','portal_def');
 8390:         my %defaults;
 8391:         if (ref($settings) eq 'HASH') {
 8392:             %defaults = %{$settings};
 8393:         } else {
 8394:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 8395:             foreach my $item (@items) {
 8396:                 $defaults{$item} = $domdefaults{$item};
 8397:             }
 8398:         }
 8399:         foreach my $item (@items) {
 8400:             if ($rownum%2) {
 8401:                 $css_class = '';
 8402:             } else {
 8403:                 $css_class = ' class="LC_odd_row" ';
 8404:             }
 8405:             $datatable .= '<tr'.$css_class.'>'.
 8406:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 8407:                           '</span></td><td class="LC_right_item" colspan="3">';
 8408:             if ($item eq 'auth_def') {
 8409:                 my @authtypes = ('internal','krb4','krb5','localauth','lti');
 8410:                 my %shortauth = (
 8411:                                  internal => 'int',
 8412:                                  krb4 => 'krb4',
 8413:                                  krb5 => 'krb5',
 8414:                                  localauth  => 'loc',
 8415:                                  lti => 'lti',
 8416:                                 );
 8417:                 my %authnames = &authtype_names();
 8418:                 foreach my $auth (@authtypes) {
 8419:                     my $checked = ' ';
 8420:                     if ($defaults{$item} eq $auth) {
 8421:                         $checked = ' checked="checked" ';
 8422:                     }
 8423:                     $datatable .= '<label><input type="radio" name="'.$item.
 8424:                                   '" value="'.$auth.'"'.$checked.'/>'.
 8425:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
 8426:                 }
 8427:             } elsif ($item eq 'timezone_def') {
 8428:                 my $includeempty = 1;
 8429:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
 8430:             } elsif ($item eq 'datelocale_def') {
 8431:                 my $includeempty = 1;
 8432:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
 8433:             } elsif ($item eq 'lang_def') {
 8434:                 my $includeempty = 1;
 8435:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
 8436:             } else {
 8437:                 my $size;
 8438:                 if ($item eq 'portal_def') {
 8439:                     $size = ' size="25"';
 8440:                 }
 8441:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 8442:                               $defaults{$item}.'"'.$size.' />';
 8443:             }
 8444:             $datatable .= '</td></tr>';
 8445:             $rownum ++;
 8446:         }
 8447:     } else {
 8448:         my %defaults;
 8449:         if (ref($settings) eq 'HASH') {
 8450:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 8451:                 my $maxnum = @{$settings->{'inststatusorder'}};
 8452:                 for (my $i=0; $i<$maxnum; $i++) {
 8453:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
 8454:                     my $item = $settings->{'inststatusorder'}->[$i];
 8455:                     my $title = $settings->{'inststatustypes'}->{$item};
 8456:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
 8457:                     $datatable .= '<tr'.$css_class.'>'.
 8458:                                   '<td><span class="LC_nobreak">'.
 8459:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
 8460:                     for (my $k=0; $k<=$maxnum; $k++) {
 8461:                         my $vpos = $k+1;
 8462:                         my $selstr;
 8463:                         if ($k == $i) {
 8464:                             $selstr = ' selected="selected" ';
 8465:                         }
 8466:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8467:                     }
 8468:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
 8469:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
 8470:                                   &mt('delete').'</span></td>'.
 8471:                                   '<td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.&mt('Name displayed:').
 8472:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
 8473:                                   '</span></td></tr>';
 8474:                 }
 8475:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
 8476:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
 8477:                 $datatable .= '<tr '.$css_class.'>'.
 8478:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
 8479:                 for (my $k=0; $k<=$maxnum; $k++) {
 8480:                     my $vpos = $k+1;
 8481:                     my $selstr;
 8482:                     if ($k == $maxnum) {
 8483:                         $selstr = ' selected="selected" ';
 8484:                     }
 8485:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8486:                 }
 8487:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
 8488:                               '<input type="text" size="10" name="addinststatus" value="" />'.
 8489:                               '&nbsp;'.&mt('(new)').
 8490:                               '</span></td><td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.
 8491:                               &mt('Name displayed:').
 8492:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
 8493:                               '</tr>'."\n";
 8494:                 $rownum ++;
 8495:             }
 8496:         }
 8497:     }
 8498:     $$rowtotal += $rownum;
 8499:     return $datatable;
 8500: }
 8501: 
 8502: sub get_languages_hash {
 8503:     my %langchoices;
 8504:     foreach my $id (&Apache::loncommon::languageids()) {
 8505:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 8506:         if ($code ne '') {
 8507:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 8508:         }
 8509:     }
 8510:     return %langchoices;
 8511: }
 8512: 
 8513: sub defaults_titles {
 8514:     my ($dom) = @_;
 8515:     my %titles = &Apache::lonlocal::texthash (
 8516:                    'auth_def'      => 'Default authentication type',
 8517:                    'auth_arg_def'  => 'Default authentication argument',
 8518:                    'lang_def'      => 'Default language',
 8519:                    'timezone_def'  => 'Default timezone',
 8520:                    'datelocale_def' => 'Default locale for dates',
 8521:                    'portal_def'     => 'Portal/Default URL',
 8522:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
 8523:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
 8524:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
 8525:                  );
 8526:     if ($dom) {
 8527:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
 8528:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 8529:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
 8530:         $protocol = 'http' if ($protocol ne 'https');
 8531:         if ($uint_dom) {
 8532:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
 8533:                                          $uint_dom);
 8534:         }
 8535:     }
 8536:     return (\%titles);
 8537: }
 8538: 
 8539: sub print_scantron {
 8540:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
 8541:     if ($position eq 'top') {
 8542:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
 8543:     } else {
 8544:         return &print_scantronconfig($dom,$settings,\$rowtotal);
 8545:     }
 8546: }
 8547: 
 8548: sub scantron_javascript {
 8549:     return <<"ENDSCRIPT";
 8550: 
 8551: <script type="text/javascript">
 8552: // <![CDATA[
 8553: 
 8554: function toggleScantron(form) {
 8555:     var csvfieldset = new Array();
 8556:     if (document.getElementById('scantroncsv_cols')) {
 8557:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
 8558:     }
 8559:     if (document.getElementById('scantroncsv_options')) {
 8560:         csvfieldset.push(document.getElementById('scantroncsv_options'));
 8561:     }
 8562:     if (csvfieldset.length) {
 8563:         if (document.getElementById('scantronconfcsv')) {
 8564:             var scantroncsv = document.getElementById('scantronconfcsv');
 8565:             if (scantroncsv.checked) {
 8566:                 for (var i=0; i<csvfieldset.length; i++) {
 8567:                     csvfieldset[i].style.display = 'block';
 8568:                 }
 8569:             } else {
 8570:                 for (var i=0; i<csvfieldset.length; i++) {
 8571:                     csvfieldset[i].style.display = 'none';
 8572:                 }
 8573:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
 8574:                 if (csvselects.length) {
 8575:                     for (var j=0; j<csvselects.length; j++) {
 8576:                         csvselects[j].selectedIndex = 0;
 8577:                     }
 8578:                 }
 8579:             }
 8580:         }
 8581:     }
 8582:     return;
 8583: }
 8584: // ]]>
 8585: </script>
 8586: 
 8587: ENDSCRIPT
 8588: 
 8589: }
 8590: 
 8591: sub print_scantronformat {
 8592:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
 8593:     my $itemcount = 1;
 8594:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
 8595:         %confhash);
 8596:     my $switchserver = &check_switchserver($dom,$confname);
 8597:     my %lt = &Apache::lonlocal::texthash (
 8598:                 default => 'Default bubblesheet format file error',
 8599:                 custom  => 'Custom bubblesheet format file error',
 8600:              );
 8601:     my %scantronfiles = (
 8602:         default => 'default.tab',
 8603:         custom => 'custom.tab',
 8604:     );
 8605:     foreach my $key (keys(%scantronfiles)) {
 8606:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
 8607:                               .$scantronfiles{$key};
 8608:     }
 8609:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
 8610:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
 8611:         if (!$switchserver) {
 8612:             my $servadm = $r->dir_config('lonAdmEMail');
 8613:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
 8614:             if ($configuserok eq 'ok') {
 8615:                 if ($author_ok eq 'ok') {
 8616:                     my %legacyfile = (
 8617:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
 8618:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
 8619:                     );
 8620:                     my %md5chk;
 8621:                     foreach my $type (keys(%legacyfile)) {
 8622:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
 8623:                         chomp($md5chk{$type});
 8624:                     }
 8625:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
 8626:                         foreach my $type (keys(%legacyfile)) {
 8627:                             ($scantronurls{$type},my $error) =
 8628:                                 &legacy_scantronformat($r,$dom,$confname,
 8629:                                                  $type,$legacyfile{$type},
 8630:                                                  $scantronurls{$type},
 8631:                                                  $scantronfiles{$type});
 8632:                             if ($error ne '') {
 8633:                                 $error{$type} = $error;
 8634:                             }
 8635:                         }
 8636:                         if (keys(%error) == 0) {
 8637:                             $is_custom = 1;
 8638:                             $confhash{'scantron'}{'scantronformat'} =
 8639:                                 $scantronurls{'custom'};
 8640:                             my $putresult =
 8641:                                 &Apache::lonnet::put_dom('configuration',
 8642:                                                          \%confhash,$dom);
 8643:                             if ($putresult ne 'ok') {
 8644:                                 $error{'custom'} =
 8645:                                     '<span class="LC_error">'.
 8646:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 8647:                             }
 8648:                         }
 8649:                     } else {
 8650:                         ($scantronurls{'default'},my $error) =
 8651:                             &legacy_scantronformat($r,$dom,$confname,
 8652:                                           'default',$legacyfile{'default'},
 8653:                                           $scantronurls{'default'},
 8654:                                           $scantronfiles{'default'});
 8655:                         if ($error eq '') {
 8656:                             $confhash{'scantron'}{'scantronformat'} = ''; 
 8657:                             my $putresult =
 8658:                                 &Apache::lonnet::put_dom('configuration',
 8659:                                                          \%confhash,$dom);
 8660:                             if ($putresult ne 'ok') {
 8661:                                 $error{'default'} =
 8662:                                     '<span class="LC_error">'.
 8663:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 8664:                             }
 8665:                         } else {
 8666:                             $error{'default'} = $error;
 8667:                         }
 8668:                     }
 8669:                 }
 8670:             }
 8671:         } else {
 8672:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
 8673:         }
 8674:     }
 8675:     if (ref($settings) eq 'HASH') {
 8676:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
 8677:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
 8678:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
 8679:                 $scantronurl = '';
 8680:             } else {
 8681:                 $scantronurl = $settings->{'scantronformat'};
 8682:             }
 8683:             $is_custom = 1;
 8684:         } else {
 8685:             $scantronurl = $scantronurls{'default'};
 8686:         }
 8687:     } else {
 8688:         if ($is_custom) {
 8689:             $scantronurl = $scantronurls{'custom'};
 8690:         } else {
 8691:             $scantronurl = $scantronurls{'default'};
 8692:         }
 8693:     }
 8694:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8695:     $datatable .= '<tr'.$css_class.'>';
 8696:     if (!$is_custom) {
 8697:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
 8698:                       '<span class="LC_nobreak">';
 8699:         if ($scantronurl) {
 8700:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
 8701:                                                          undef,undef,undef,undef,'background-color:#ffffff');
 8702:         } else {
 8703:             $datatable = &mt('File unavailable for display');
 8704:         }
 8705:         $datatable .= '</span></td>';
 8706:         if (keys(%error) == 0) { 
 8707:             $datatable .= '<td style="vertical-align: bottom">';
 8708:             if (!$switchserver) {
 8709:                 $datatable .= &mt('Upload:').'<br />';
 8710:             }
 8711:         } else {
 8712:             my $errorstr;
 8713:             foreach my $key (sort(keys(%error))) {
 8714:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 8715:             }
 8716:             $datatable .= '<td>'.$errorstr;
 8717:         }
 8718:     } else {
 8719:         if (keys(%error) > 0) {
 8720:             my $errorstr;
 8721:             foreach my $key (sort(keys(%error))) {
 8722:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 8723:             } 
 8724:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
 8725:         } elsif ($scantronurl) {
 8726:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
 8727:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 8728:             $datatable .= '<td><span class="LC_nobreak">'.
 8729:                           $link.
 8730:                           '<label><input type="checkbox" name="scantronformat_del"'.
 8731:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
 8732:                           '<td><span class="LC_nobreak">&nbsp;'.
 8733:                           &mt('Replace:').'</span><br />';
 8734:         }
 8735:     }
 8736:     if (keys(%error) == 0) {
 8737:         if ($switchserver) {
 8738:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 8739:         } else {
 8740:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 8741:                          '<input type="file" name="scantronformat" /></span>';
 8742:         }
 8743:     }
 8744:     $datatable .= '</td></tr>';
 8745:     $$rowtotal ++;
 8746:     return $datatable;
 8747: }
 8748: 
 8749: sub legacy_scantronformat {
 8750:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
 8751:     my ($url,$error);
 8752:     my @statinfo = &Apache::lonnet::stat_file($newurl);
 8753:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
 8754:         (my $result,$url) =
 8755:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
 8756:                          '','',$newfile);
 8757:         if ($result ne 'ok') {
 8758:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
 8759:         }
 8760:     }
 8761:     return ($url,$error);
 8762: }
 8763: 
 8764: sub print_scantronconfig {
 8765:     my ($dom,$settings,$rowtotal) = @_;
 8766:     my $itemcount = 2;
 8767:     my $is_checked = ' checked="checked"';
 8768:     my %optionson = (
 8769:                      hdr => ' checked="checked"',
 8770:                      pad => ' checked="checked"',
 8771:                      rem => ' checked="checked"',
 8772:                     );
 8773:     my %optionsoff = (
 8774:                       hdr => '',
 8775:                       pad => '',
 8776:                       rem => '',
 8777:                      );
 8778:     my $currcsvsty = 'none';
 8779:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
 8780:     my @fields = &scantroncsv_fields();
 8781:     my %titles = &scantronconfig_titles();
 8782:     if (ref($settings) eq 'HASH') {
 8783:         if (ref($settings->{config}) eq 'HASH') {
 8784:             if ($settings->{config}->{dat}) {
 8785:                 $checked{'dat'} = $is_checked;
 8786:             }
 8787:             if (ref($settings->{config}->{csv}) eq 'HASH') {
 8788:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
 8789:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
 8790:                     if (keys(%csvfields) > 0) {
 8791:                         $checked{'csv'} = $is_checked;
 8792:                         $currcsvsty = 'block';
 8793:                     }
 8794:                 }
 8795:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
 8796:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
 8797:                     foreach my $option (keys(%optionson)) {
 8798:                         unless ($csvoptions{$option}) {
 8799:                             $optionsoff{$option} = $optionson{$option};
 8800:                             $optionson{$option} = '';
 8801:                         }
 8802:                     }
 8803:                 }
 8804:             }
 8805:         } else {
 8806:             $checked{'dat'} = $is_checked;
 8807:         }
 8808:     } else {
 8809:         $checked{'dat'} = $is_checked;
 8810:     }
 8811:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
 8812:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 8813:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
 8814:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
 8815:     foreach my $item ('dat','csv') {
 8816:         my $id;
 8817:         if ($item eq 'csv') {
 8818:             $id = 'id="scantronconfcsv" ';
 8819:         }
 8820:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
 8821:                       $titles{$item}.'</label>'.('&nbsp;'x3);
 8822:         if ($item eq 'csv') {
 8823:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
 8824:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
 8825:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
 8826:             foreach my $col (@fields) {
 8827:                 my $selnone;
 8828:                 if ($csvfields{$col} eq '') {
 8829:                     $selnone = ' selected="selected"';
 8830:                 }
 8831:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
 8832:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
 8833:                               '<option value=""'.$selnone.'></option>';
 8834:                 for (my $i=0; $i<20; $i++) {
 8835:                     my $shown = $i+1;
 8836:                     my $sel;
 8837:                     unless ($selnone) {
 8838:                         if (exists($csvfields{$col})) {
 8839:                             if ($csvfields{$col} == $i) {
 8840:                                 $sel = ' selected="selected"';
 8841:                             }
 8842:                         }
 8843:                     }
 8844:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
 8845:                 }
 8846:                 $datatable .= '</select></td></tr>';
 8847:            }
 8848:            $datatable .= '</table></fieldset>'.
 8849:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
 8850:                          '<legend>'.&mt('CSV Options').'</legend>';
 8851:            foreach my $option ('hdr','pad','rem') {
 8852:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
 8853:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
 8854:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
 8855:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
 8856:            }
 8857:            $datatable .= '</fieldset>';
 8858:            $itemcount ++;
 8859:         }
 8860:     }
 8861:     $datatable .= '</td></tr>';
 8862:     $$rowtotal ++;
 8863:     return $datatable;
 8864: }
 8865: 
 8866: sub scantronconfig_titles {
 8867:     return &Apache::lonlocal::texthash(
 8868:                                           dat => 'Standard format (.dat)',
 8869:                                           csv => 'Comma separated values (.csv)',
 8870:                                           hdr => 'Remove first line in file (contains column titles)',
 8871:                                           pad => 'Prepend 0s to PaperID',
 8872:                                           rem => 'Remove leading spaces (except Question Response columns)',
 8873:                                           CODE => 'CODE',
 8874:                                           ID   => 'Student ID',
 8875:                                           PaperID => 'Paper ID',
 8876:                                           FirstName => 'First Name',
 8877:                                           LastName => 'Last Name',
 8878:                                           FirstQuestion => 'First Question Response',
 8879:                                           Section => 'Section',
 8880:     );
 8881: }
 8882: 
 8883: sub scantroncsv_fields {
 8884:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
 8885: }
 8886: 
 8887: sub print_coursecategories {
 8888:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
 8889:     my $datatable;
 8890:     if ($position eq 'top') {
 8891:         my (%checked);
 8892:         my @catitems = ('unauth','auth');
 8893:         my @cattypes = ('std','domonly','codesrch','none');
 8894:         $checked{'unauth'} = 'std';
 8895:         $checked{'auth'} = 'std';
 8896:         if (ref($settings) eq 'HASH') {
 8897:             foreach my $type (@cattypes) {
 8898:                 if ($type eq $settings->{'unauth'}) {
 8899:                     $checked{'unauth'} = $type;
 8900:                 }
 8901:                 if ($type eq $settings->{'auth'}) {
 8902:                     $checked{'auth'} = $type;
 8903:                 }
 8904:             }
 8905:         }
 8906:         my %lt = &Apache::lonlocal::texthash (
 8907:                                                unauth   => 'Catalog type for unauthenticated users',
 8908:                                                auth     => 'Catalog type for authenticated users',
 8909:                                                none     => 'No catalog',
 8910:                                                std      => 'Standard catalog',
 8911:                                                domonly  => 'Domain-only catalog',
 8912:                                                codesrch => "Code search form",
 8913:                                              );
 8914:        my $itemcount = 0;
 8915:        foreach my $item (@catitems) {
 8916:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 8917:            $datatable .= '<tr '.$css_class.'>'.
 8918:                          '<td>'.$lt{$item}.'</td>'.
 8919:                          '<td class="LC_right_item"><span class="LC_nobreak">';
 8920:            foreach my $type (@cattypes) {
 8921:                my $ischecked;
 8922:                if ($checked{$item} eq $type) {
 8923:                    $ischecked=' checked="checked"';
 8924:                }
 8925:                $datatable .= '<label>'.
 8926:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
 8927:                              ' />'.$lt{$type}.'</label>&nbsp;';
 8928:            }
 8929:            $datatable .= '</span></td></tr>';
 8930:            $itemcount ++;
 8931:         }
 8932:         $$rowtotal += $itemcount;
 8933:     } elsif ($position eq 'middle') {
 8934:         my $toggle_cats_crs = ' ';
 8935:         my $toggle_cats_dom = ' checked="checked" ';
 8936:         my $can_cat_crs = ' ';
 8937:         my $can_cat_dom = ' checked="checked" ';
 8938:         my $toggle_catscomm_comm = ' ';
 8939:         my $toggle_catscomm_dom = ' checked="checked" ';
 8940:         my $can_catcomm_comm = ' ';
 8941:         my $can_catcomm_dom = ' checked="checked" ';
 8942:         my $toggle_catsplace_place = ' ';
 8943:         my $toggle_catsplace_dom = ' checked="checked" ';
 8944:         my $can_catplace_place = ' ';
 8945:         my $can_catplace_dom = ' checked="checked" ';
 8946: 
 8947:         if (ref($settings) eq 'HASH') {
 8948:             if ($settings->{'togglecats'} eq 'crs') {
 8949:                 $toggle_cats_crs = $toggle_cats_dom;
 8950:                 $toggle_cats_dom = ' ';
 8951:             }
 8952:             if ($settings->{'categorize'} eq 'crs') {
 8953:                 $can_cat_crs = $can_cat_dom;
 8954:                 $can_cat_dom = ' ';
 8955:             }
 8956:             if ($settings->{'togglecatscomm'} eq 'comm') {
 8957:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
 8958:                 $toggle_catscomm_dom = ' ';
 8959:             }
 8960:             if ($settings->{'categorizecomm'} eq 'comm') {
 8961:                 $can_catcomm_comm = $can_catcomm_dom;
 8962:                 $can_catcomm_dom = ' ';
 8963:             }
 8964:             if ($settings->{'togglecatsplace'} eq 'place') {
 8965:                 $toggle_catsplace_place = $toggle_catsplace_dom;
 8966:                 $toggle_catsplace_dom = ' ';
 8967:             }
 8968:             if ($settings->{'categorizeplace'} eq 'place') {
 8969:                 $can_catplace_place = $can_catplace_dom;
 8970:                 $can_catplace_dom = ' ';
 8971:             }
 8972:         }
 8973:         my %title = &Apache::lonlocal::texthash (
 8974:                      togglecats      => 'Show/Hide a course in catalog',
 8975:                      togglecatscomm  => 'Show/Hide a community in catalog',
 8976:                      togglecatsplace => 'Show/Hide a placement test in catalog',
 8977:                      categorize      => 'Assign a category to a course',
 8978:                      categorizecomm  => 'Assign a category to a community',
 8979:                      categorizeplace => 'Assign a category to a placement test',
 8980:                     );
 8981:         my %level = &Apache::lonlocal::texthash (
 8982:                      dom   => 'Set in Domain',
 8983:                      crs   => 'Set in Course',
 8984:                      comm  => 'Set in Community',
 8985:                      place => 'Set in Placement Test',
 8986:                     );
 8987:         $datatable = '<tr class="LC_odd_row">'.
 8988:                   '<td>'.$title{'togglecats'}.'</td>'.
 8989:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 8990:                   '<input type="radio" name="togglecats"'.
 8991:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 8992:                   '<label><input type="radio" name="togglecats"'.
 8993:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
 8994:                   '</tr><tr>'.
 8995:                   '<td>'.$title{'categorize'}.'</td>'.
 8996:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 8997:                   '<label><input type="radio" name="categorize"'.
 8998:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 8999:                   '<label><input type="radio" name="categorize"'.
 9000:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
 9001:                   '</tr><tr class="LC_odd_row">'.
 9002:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
 9003:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 9004:                   '<input type="radio" name="togglecatscomm"'.
 9005:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9006:                   '<label><input type="radio" name="togglecatscomm"'.
 9007:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
 9008:                   '</tr><tr>'.
 9009:                   '<td>'.$title{'categorizecomm'}.'</td>'.
 9010:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 9011:                   '<label><input type="radio" name="categorizecomm"'.
 9012:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9013:                   '<label><input type="radio" name="categorizecomm"'.
 9014:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
 9015:                   '</tr><tr class="LC_odd_row">'.
 9016:                   '<td>'.$title{'togglecatsplace'}.'</td>'.
 9017:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 9018:                   '<input type="radio" name="togglecatsplace"'.
 9019:                   $toggle_catsplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9020:                   '<label><input type="radio" name="togglecatscomm"'.
 9021:                   $toggle_catsplace_place.' value="comm" />'.$level{'place'}.'</label></span></td>'.
 9022:                   '</tr><tr>'.
 9023:                   '<td>'.$title{'categorizeplace'}.'</td>'.
 9024:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 9025:                   '<label><input type="radio" name="categorizeplace"'.
 9026:                   $can_catplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9027:                   '<label><input type="radio" name="categorizeplace"'.
 9028:                   $can_catplace_place.'value="place" />'.$level{'place'}.'</label></span></td>'.
 9029:                   '</tr>';
 9030:         $$rowtotal += 6;
 9031:     } else {
 9032:         my $css_class;
 9033:         my $itemcount = 1;
 9034:         my $cathash; 
 9035:         if (ref($settings) eq 'HASH') {
 9036:             $cathash = $settings->{'cats'};
 9037:         }
 9038:         if (ref($cathash) eq 'HASH') {
 9039:             my (@cats,@trails,%allitems,%idx,@jsarray);
 9040:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
 9041:                                                    \%allitems,\%idx,\@jsarray);
 9042:             my $maxdepth = scalar(@cats);
 9043:             my $colattrib = '';
 9044:             if ($maxdepth > 2) {
 9045:                 $colattrib = ' colspan="2" ';
 9046:             }
 9047:             my @path;
 9048:             if (@cats > 0) {
 9049:                 if (ref($cats[0]) eq 'ARRAY') {
 9050:                     my $numtop = @{$cats[0]};
 9051:                     my $maxnum = $numtop;
 9052:                     my %default_names = (
 9053:                           instcode    => &mt('Official courses'),
 9054:                           communities => &mt('Communities'),
 9055:                           placement   => &mt('Placement Tests'),
 9056:                     );
 9057: 
 9058:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
 9059:                         ($cathash->{'instcode::0'} eq '') ||
 9060:                         (!grep(/^communities$/,@{$cats[0]})) || 
 9061:                         ($cathash->{'communities::0'} eq '') ||
 9062:                         (!grep(/^placement$/,@{$cats[0]})) ||
 9063:                         ($cathash->{'placement::0'} eq '')) {
 9064:                         $maxnum ++;
 9065:                     }
 9066:                     my $lastidx;
 9067:                     for (my $i=0; $i<$numtop; $i++) {
 9068:                         my $parent = $cats[0][$i];
 9069:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9070:                         my $item = &escape($parent).'::0';
 9071:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
 9072:                         $lastidx = $idx{$item};
 9073:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 9074:                                       .'<select name="'.$item.'"'.$chgstr.'>';
 9075:                         for (my $k=0; $k<=$maxnum; $k++) {
 9076:                             my $vpos = $k+1;
 9077:                             my $selstr;
 9078:                             if ($k == $i) {
 9079:                                 $selstr = ' selected="selected" ';
 9080:                             }
 9081:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9082:                         }
 9083:                         $datatable .= '</select></span></td><td>';
 9084:                         if ($parent eq 'instcode' || $parent eq 'communities' || $parent eq 'placement') {
 9085:                             $datatable .=  '<span class="LC_nobreak">'
 9086:                                            .$default_names{$parent}.'</span>';
 9087:                             if ($parent eq 'instcode') {
 9088:                                 $datatable .= '<br /><span class="LC_nobreak">('
 9089:                                               .&mt('with institutional codes')
 9090:                                               .')</span></td><td'.$colattrib.'>';
 9091:                             } else {
 9092:                                 $datatable .= '<table><tr><td>';
 9093:                             }
 9094:                             $datatable .= '<span class="LC_nobreak">'
 9095:                                           .'<label><input type="radio" name="'
 9096:                                           .$parent.'" value="1" checked="checked" />'
 9097:                                           .&mt('Display').'</label>';
 9098:                             if ($parent eq 'instcode') {
 9099:                                 $datatable .= '&nbsp;';
 9100:                             } else {
 9101:                                 $datatable .= '</span></td></tr><tr><td>'
 9102:                                               .'<span class="LC_nobreak">';
 9103:                             }
 9104:                             $datatable .= '<label><input type="radio" name="'
 9105:                                           .$parent.'" value="0" />'
 9106:                                           .&mt('Do not display').'</label></span>';
 9107:                             if (($parent eq 'communities') || ($parent eq 'placement')) {
 9108:                                 $datatable .= '</td></tr></table>';
 9109:                             }
 9110:                             $datatable .= '</td>';
 9111:                         } else {
 9112:                             $datatable .= $parent
 9113:                                           .'&nbsp;<span class="LC_nobreak"><label>'
 9114:                                           .'<input type="checkbox" name="deletecategory" '
 9115:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
 9116:                         }
 9117:                         my $depth = 1;
 9118:                         push(@path,$parent);
 9119:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
 9120:                         pop(@path);
 9121:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9122:                         $itemcount ++;
 9123:                     }
 9124:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9125:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
 9126:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
 9127:                     for (my $k=0; $k<=$maxnum; $k++) {
 9128:                         my $vpos = $k+1;
 9129:                         my $selstr;
 9130:                         if ($k == $numtop) {
 9131:                             $selstr = ' selected="selected" ';
 9132:                         }
 9133:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9134:                     }
 9135:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
 9136:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
 9137:                                   .'</tr>'."\n";
 9138:                     $itemcount ++;
 9139:                     foreach my $default ('instcode','communities','placement') {
 9140:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
 9141:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9142:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
 9143:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
 9144:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
 9145:                             for (my $k=0; $k<=$maxnum; $k++) {
 9146:                                 my $vpos = $k+1;
 9147:                                 my $selstr;
 9148:                                 if ($k == $maxnum) {
 9149:                                     $selstr = ' selected="selected" ';
 9150:                                 }
 9151:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9152:                             }
 9153:                             $datatable .= '</select></span></td>'.
 9154:                                           '<td><span class="LC_nobreak">'.
 9155:                                           $default_names{$default}.'</span>';
 9156:                             if ($default eq 'instcode') {
 9157:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
 9158:                                               .&mt('with institutional codes').')</span>';
 9159:                             }
 9160:                             $datatable .= '</td>'
 9161:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
 9162:                                           .&mt('Display').'</label>&nbsp;'
 9163:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
 9164:                                           .&mt('Do not display').'</label></span></td></tr>';
 9165:                         }
 9166:                     }
 9167:                 }
 9168:             } else {
 9169:                 $datatable .= &initialize_categories($itemcount);
 9170:             }
 9171:         } else {
 9172:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
 9173:                           .&initialize_categories($itemcount);
 9174:         }
 9175:         $$rowtotal += $itemcount;
 9176:     }
 9177:     return $datatable;
 9178: }
 9179: 
 9180: sub print_serverstatuses {
 9181:     my ($dom,$settings,$rowtotal) = @_;
 9182:     my $datatable;
 9183:     my @pages = &serverstatus_pages();
 9184:     my (%namedaccess,%machineaccess);
 9185:     foreach my $type (@pages) {
 9186:         $namedaccess{$type} = '';
 9187:         $machineaccess{$type}= '';
 9188:     }
 9189:     if (ref($settings) eq 'HASH') {
 9190:         foreach my $type (@pages) {
 9191:             if (exists($settings->{$type})) {
 9192:                 if (ref($settings->{$type}) eq 'HASH') {
 9193:                     foreach my $key (keys(%{$settings->{$type}})) {
 9194:                         if ($key eq 'namedusers') {
 9195:                             $namedaccess{$type} = $settings->{$type}->{$key};
 9196:                         } elsif ($key eq 'machines') {
 9197:                             $machineaccess{$type} = $settings->{$type}->{$key};
 9198:                         }
 9199:                     }
 9200:                 }
 9201:             }
 9202:         }
 9203:     }
 9204:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
 9205:     my $rownum = 0;
 9206:     my $css_class;
 9207:     foreach my $type (@pages) {
 9208:         $rownum ++;
 9209:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 9210:         $datatable .= '<tr'.$css_class.'>'.
 9211:                       '<td><span class="LC_nobreak">'.
 9212:                       $titles->{$type}.'</span></td>'.
 9213:                       '<td class="LC_left_item">'.
 9214:                       '<input type="text" name="'.$type.'_namedusers" '.
 9215:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
 9216:                       '<td class="LC_right_item">'.
 9217:                       '<span class="LC_nobreak">'.
 9218:                       '<input type="text" name="'.$type.'_machines" '.
 9219:                       'value="'.$machineaccess{$type}.'" size="10" />'.
 9220:                       '</span></td></tr>'."\n";
 9221:     }
 9222:     $$rowtotal += $rownum;
 9223:     return $datatable;
 9224: }
 9225: 
 9226: sub serverstatus_pages {
 9227:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
 9228:             'checksums','clusterstatus','certstatus','metadata_keywords',
 9229:             'metadata_harvest','takeoffline','takeonline','showenv','toggledebug',
 9230:             'ping','domconf','uniquecodes','diskusage','coursecatalog');
 9231: }
 9232: 
 9233: sub defaults_javascript {
 9234:     my ($settings) = @_;
 9235:     return unless (ref($settings) eq 'HASH');
 9236:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 9237:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
 9238:         if ($maxnum eq '') {
 9239:             $maxnum = 0;
 9240:         }
 9241:         $maxnum ++;
 9242:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
 9243:         return <<"ENDSCRIPT";
 9244: <script type="text/javascript">
 9245: // <![CDATA[
 9246: function reorderTypes(form,caller) {
 9247:     var changedVal;
 9248: $jstext 
 9249:     var newpos = 'addinststatus_pos';
 9250:     var current = new Array;
 9251:     var maxh = $maxnum;
 9252:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 9253:     var oldVal;
 9254:     if (caller == newpos) {
 9255:         changedVal = newitemVal;
 9256:     } else {
 9257:         var curritem = 'inststatus_pos_'+caller;
 9258:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
 9259:         current[newitemVal] = newpos;
 9260:     }
 9261:     for (var i=0; i<inststatuses.length; i++) {
 9262:         if (inststatuses[i] != caller) {
 9263:             var elementName = 'inststatus_pos_'+inststatuses[i];
 9264:             if (form.elements[elementName]) {
 9265:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 9266:                 current[currVal] = elementName;
 9267:             }
 9268:         }
 9269:     }
 9270:     for (var j=0; j<maxh; j++) {
 9271:         if (current[j] == undefined) {
 9272:             oldVal = j;
 9273:         }
 9274:     }
 9275:     if (oldVal < changedVal) {
 9276:         for (var k=oldVal+1; k<=changedVal ; k++) {
 9277:            var elementName = current[k];
 9278:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 9279:         }
 9280:     } else {
 9281:         for (var k=changedVal; k<oldVal; k++) {
 9282:             var elementName = current[k];
 9283:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 9284:         }
 9285:     }
 9286:     return;
 9287: }
 9288: 
 9289: // ]]>
 9290: </script>
 9291: 
 9292: ENDSCRIPT
 9293:     }
 9294:     return;
 9295: }
 9296: 
 9297: sub passwords_javascript {
 9298:     my $intauthcheck = &mt('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.');
 9299:     my $intauthcost = &mt('Warning: bcrypt encryption cost for internal authentication must be an integer.');
 9300:     &js_escape(\$intauthcheck);
 9301:     &js_escape(\$intauthcost);
 9302:     my $intauthjs = <<"ENDSCRIPT";
 9303: 
 9304: function warnIntAuth(field) {
 9305:     if (field.name == 'intauth_check') {
 9306:         if (field.value == '2') {
 9307:             alert('$intauthcheck');
 9308:         }
 9309:     }
 9310:     if (field.name == 'intauth_cost') {
 9311:         field.value.replace(/\s/g,'');
 9312:         if (field.value != '') {
 9313:             var regexdigit=/^\\d+\$/;
 9314:             if (!regexdigit.test(field.value)) {
 9315:                 alert('$intauthcost');
 9316:             }
 9317:         }
 9318:     }
 9319:     return;
 9320: }
 9321: 
 9322: ENDSCRIPT
 9323:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
 9324: }
 9325: 
 9326: sub coursecategories_javascript {
 9327:     my ($settings) = @_;
 9328:     my ($output,$jstext,$cathash);
 9329:     if (ref($settings) eq 'HASH') {
 9330:         $cathash = $settings->{'cats'};
 9331:     }
 9332:     if (ref($cathash) eq 'HASH') {
 9333:         my (@cats,@jsarray,%idx);
 9334:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
 9335:         if (@jsarray > 0) {
 9336:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
 9337:             for (my $i=0; $i<@jsarray; $i++) {
 9338:                 if (ref($jsarray[$i]) eq 'ARRAY') {
 9339:                     my $catstr = join('","',@{$jsarray[$i]});
 9340:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
 9341:                 }
 9342:             }
 9343:         }
 9344:     } else {
 9345:         $jstext  = '    var categories = Array(1);'."\n".
 9346:                    '    categories[0] = Array("instcode_pos");'."\n"; 
 9347:     }
 9348:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
 9349:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
 9350:     my $placement_reserved = &mt('The name: [_1] is a reserved category.','"placement"');
 9351:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
 9352:     &js_escape(\$instcode_reserved);
 9353:     &js_escape(\$communities_reserved);
 9354:     &js_escape(\$placement_reserved);
 9355:     &js_escape(\$choose_again);
 9356:     $output = <<"ENDSCRIPT";
 9357: <script type="text/javascript">
 9358: // <![CDATA[
 9359: function reorderCats(form,parent,item,idx) {
 9360:     var changedVal;
 9361: $jstext
 9362:     var newpos = 'addcategory_pos';
 9363:     if (parent == '') {
 9364:         var has_instcode = 0;
 9365:         var maxtop = categories[idx].length;
 9366:         for (var j=0; j<maxtop; j++) {
 9367:             if (categories[idx][j] == 'instcode::0') {
 9368:                 has_instcode == 1;
 9369:             }
 9370:         }
 9371:         if (has_instcode == 0) {
 9372:             categories[idx][maxtop] = 'instcode_pos';
 9373:         }
 9374:     } else {
 9375:         newpos += '_'+parent;
 9376:     }
 9377:     var maxh = 1 + categories[idx].length;
 9378:     var current = new Array;
 9379:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 9380:     if (item == newpos) {
 9381:         changedVal = newitemVal;
 9382:     } else {
 9383:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 9384:         current[newitemVal] = newpos;
 9385:     }
 9386:     for (var i=0; i<categories[idx].length; i++) {
 9387:         var elementName = categories[idx][i];
 9388:         if (elementName != item) {
 9389:             if (form.elements[elementName]) {
 9390:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 9391:                 current[currVal] = elementName;
 9392:             }
 9393:         }
 9394:     }
 9395:     var oldVal;
 9396:     for (var j=0; j<maxh; j++) {
 9397:         if (current[j] == undefined) {
 9398:             oldVal = j;
 9399:         }
 9400:     }
 9401:     if (oldVal < changedVal) {
 9402:         for (var k=oldVal+1; k<=changedVal ; k++) {
 9403:            var elementName = current[k];
 9404:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 9405:         }
 9406:     } else {
 9407:         for (var k=changedVal; k<oldVal; k++) {
 9408:             var elementName = current[k];
 9409:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 9410:         }
 9411:     }
 9412:     return;
 9413: }
 9414: 
 9415: function categoryCheck(form) {
 9416:     if (form.elements['addcategory_name'].value == 'instcode') {
 9417:         alert('$instcode_reserved\\n$choose_again');
 9418:         return false;
 9419:     }
 9420:     if (form.elements['addcategory_name'].value == 'communities') {
 9421:         alert('$communities_reserved\\n$choose_again');
 9422:         return false;
 9423:     }
 9424:     if (form.elements['addcategory_name'].value == 'placement') {
 9425:         alert('$placement_reserved\\n$choose_again');
 9426:         return false;
 9427:     }
 9428:     return true;
 9429: }
 9430: 
 9431: // ]]>
 9432: </script>
 9433: 
 9434: ENDSCRIPT
 9435:     return $output;
 9436: }
 9437: 
 9438: sub initialize_categories {
 9439:     my ($itemcount) = @_;
 9440:     my ($datatable,$css_class,$chgstr);
 9441:     my %default_names = (
 9442:                       instcode    => 'Official courses (with institutional codes)',
 9443:                       communities => 'Communities',
 9444:                       placement   => 'Placement Tests',
 9445:                         );
 9446:     my %selnum = (
 9447:                    instcode    => '0',
 9448:                    communities => '1',
 9449:                    placement   => '2',
 9450:                  );
 9451:     my %selected;
 9452:     foreach my $default ('instcode','communities','placement') {
 9453:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9454:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
 9455:         map { $selected{$selnum{$_}} = '' } keys(%selnum);
 9456:         $selected{$selnum{$default}} = ' selected="selected"';
 9457:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 9458:                      .'<select name="'.$default.'_pos"'.$chgstr.'>'
 9459:                      .'<option value="0"'.$selected{'0'}.'>1</option>'
 9460:                      .'<option value="1"'.$selected{'1'}.'>2</option>'
 9461:                      .'<option value="2"'.$selected{'2'}.'>3</option>'
 9462:                      .'<option value="3">4</option></select>&nbsp;'
 9463:                      .$default_names{$default}
 9464:                      .'</span></td><td><span class="LC_nobreak">'
 9465:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
 9466:                      .&mt('Display').'</label>&nbsp;<label>'
 9467:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
 9468:                  .'</label></span></td></tr>';
 9469:         $itemcount ++;
 9470:     }
 9471:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9472:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
 9473:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 9474:                   .'<select name="addcategory_pos"'.$chgstr.'>'
 9475:                   .'<option value="0">1</option>'
 9476:                   .'<option value="1">2</option>'
 9477:                   .'<option value="2">3</option>'
 9478:                   .'<option value="3" selected="selected">4</option></select>&nbsp;'
 9479:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
 9480:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
 9481:                   .'</td></tr>';
 9482:     return $datatable;
 9483: }
 9484: 
 9485: sub build_category_rows {
 9486:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
 9487:     my ($text,$name,$item,$chgstr);
 9488:     if (ref($cats) eq 'ARRAY') {
 9489:         my $maxdepth = scalar(@{$cats});
 9490:         if (ref($cats->[$depth]) eq 'HASH') {
 9491:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9492:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9493:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9494:                 $text .= '<td><table class="LC_data_table">';
 9495:                 my ($idxnum,$parent_name,$parent_item);
 9496:                 my $higher = $depth - 1;
 9497:                 if ($higher == 0) {
 9498:                     $parent_name = &escape($parent).'::'.$higher;
 9499:                 } else {
 9500:                     if (ref($path) eq 'ARRAY') {
 9501:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 9502:                     }
 9503:                 }
 9504:                 $parent_item = 'addcategory_pos_'.$parent_name;
 9505:                 for (my $j=0; $j<=$numchildren; $j++) {
 9506:                     if ($j < $numchildren) {
 9507:                         $name = $cats->[$depth]{$parent}[$j];
 9508:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
 9509:                         $idxnum = $idx->{$item};
 9510:                     } else {
 9511:                         $name = $parent_name;
 9512:                         $item = $parent_item;
 9513:                     }
 9514:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
 9515:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
 9516:                     for (my $i=0; $i<=$numchildren; $i++) {
 9517:                         my $vpos = $i+1;
 9518:                         my $selstr;
 9519:                         if ($j == $i) {
 9520:                             $selstr = ' selected="selected" ';
 9521:                         }
 9522:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
 9523:                     }
 9524:                     $text .= '</select>&nbsp;';
 9525:                     if ($j < $numchildren) {
 9526:                         my $deeper = $depth+1;
 9527:                         $text .= $name.'&nbsp;'
 9528:                                  .'<label><input type="checkbox" name="deletecategory" value="'
 9529:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
 9530:                         if(ref($path) eq 'ARRAY') {
 9531:                             push(@{$path},$name);
 9532:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
 9533:                             pop(@{$path});
 9534:                         }
 9535:                     } else {
 9536:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
 9537:                         if ($j == $numchildren) {
 9538:                             $text .= $name;
 9539:                         } else {
 9540:                             $text .= $item;
 9541:                         }
 9542:                         $text .= '" value="" />';
 9543:                     }
 9544:                     $text .= '</td></tr>';
 9545:                 }
 9546:                 $text .= '</table></td>';
 9547:             } else {
 9548:                 my $higher = $depth-1;
 9549:                 if ($higher == 0) {
 9550:                     $name = &escape($parent).'::'.$higher;
 9551:                 } else {
 9552:                     if (ref($path) eq 'ARRAY') {
 9553:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 9554:                     }
 9555:                 }
 9556:                 my $colspan;
 9557:                 if ($parent ne 'instcode') {
 9558:                     $colspan = $maxdepth - $depth - 1;
 9559:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
 9560:                 }
 9561:             }
 9562:         }
 9563:     }
 9564:     return $text;
 9565: }
 9566: 
 9567: sub modifiable_userdata_row {
 9568:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
 9569:         $rowid,$customcss,$rowstyle,$itemdesc) = @_;
 9570:     my ($role,$rolename,$statustype);
 9571:     $role = $item;
 9572:     if ($context eq 'cancreate') {
 9573:         if ($item =~ /^(emailusername)_(.+)$/) {
 9574:             $role = $1;
 9575:             $statustype = $2;
 9576:             if (ref($usertypes) eq 'HASH') {
 9577:                 if ($usertypes->{$statustype}) {
 9578:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
 9579:                 } else {
 9580:                     $rolename = &mt('Data provided by user');
 9581:                 }
 9582:             }
 9583:         }
 9584:     } elsif ($context eq 'selfcreate') {
 9585:         if (ref($usertypes) eq 'HASH') {
 9586:             $rolename = $usertypes->{$role};
 9587:         } else {
 9588:             $rolename = $role;
 9589:         }
 9590:     } elsif ($context eq 'lti') {
 9591:         $rolename = &mt('Institutional data used (if available)');
 9592:     } elsif ($context eq 'privacy') {
 9593:         $rolename = $itemdesc;
 9594:     } else {
 9595:         if ($role eq 'cr') {
 9596:             $rolename = &mt('Custom role');
 9597:         } else {
 9598:             $rolename = &Apache::lonnet::plaintext($role);
 9599:         }
 9600:     }
 9601:     my (@fields,%fieldtitles);
 9602:     if (ref($fieldsref) eq 'ARRAY') {
 9603:         @fields = @{$fieldsref};
 9604:     } else {
 9605:         @fields = ('lastname','firstname','middlename','generation',
 9606:                    'permanentemail','id');
 9607:     }
 9608:     if ((ref($titlesref) eq 'HASH')) {
 9609:         %fieldtitles = %{$titlesref};
 9610:     } else {
 9611:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 9612:     }
 9613:     my $output;
 9614:     my $css_class;
 9615:     if ($rowcount%2) {
 9616:         $css_class = 'LC_odd_row';
 9617:     }
 9618:     if ($customcss) {
 9619:         $css_class .= " $customcss";
 9620:     }
 9621:     $css_class =~ s/^\s+//;
 9622:     if ($css_class) {
 9623:         $css_class = ' class="'.$css_class.'"';
 9624:     }
 9625:     if ($rowstyle) {
 9626:         $css_class .= ' style="'.$rowstyle.'"';
 9627:     }
 9628:     if ($rowid) {
 9629:         $rowid = ' id="'.$rowid.'"';
 9630:     }
 9631:     $output = '<tr '.$css_class.$rowid.'>'.
 9632:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
 9633:               '<td class="LC_left_item" colspan="2"><table>';
 9634:     my $rem;
 9635:     my %checks;
 9636:     my %current;
 9637:     if (ref($settings) eq 'HASH') {
 9638:         my $hashref;
 9639:         if ($context eq 'lti') {
 9640:             if (ref($settings) eq 'HASH') {
 9641:                 $hashref = $settings->{'instdata'};
 9642:             }
 9643:         } elsif ($context eq 'privacy') {
 9644:             my ($key,$inner) = split(/_/,$role);
 9645:             if (ref($settings) eq 'HASH') {
 9646:                 if (ref($settings->{$key}) eq 'HASH') {
 9647:                     $hashref = $settings->{$key}->{$inner};
 9648:                 }
 9649:             }
 9650:         } elsif (ref($settings->{$context}) eq 'HASH') {
 9651:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
 9652:                 $hashref = $settings->{'lti_instdata'};
 9653:             }
 9654:             if ($role eq 'emailusername') {
 9655:                 if ($statustype) {
 9656:                     if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
 9657:                         $hashref = $settings->{$context}->{$role}->{$statustype};
 9658:                     }
 9659:                 }
 9660:             }
 9661:         }
 9662:         if (ref($hashref) eq 'HASH') { 
 9663:             foreach my $field (@fields) {
 9664:                 if ($hashref->{$field}) {
 9665:                     if ($role eq 'emailusername') {
 9666:                         $checks{$field} = $hashref->{$field};
 9667:                     } else {
 9668:                         $checks{$field} = ' checked="checked" ';
 9669:                     }
 9670:                 }
 9671:             }
 9672:         }
 9673:     }
 9674:  
 9675:     my $total = scalar(@fields);
 9676:     for (my $i=0; $i<$total; $i++) {
 9677:         $rem = $i%($numinrow);
 9678:         if ($rem == 0) {
 9679:             if ($i > 0) {
 9680:                 $output .= '</tr>';
 9681:             }
 9682:             $output .= '<tr>';
 9683:         }
 9684:         my $check = ' ';
 9685:         unless ($role eq 'emailusername') {
 9686:             if (exists($checks{$fields[$i]})) {
 9687:                 $check = $checks{$fields[$i]};
 9688:             } elsif ($context eq 'privacy') {
 9689:                 if ($role =~ /^priv_(domain|course)$/) {
 9690:                     if (ref($settings) ne 'HASH') {
 9691:                         $check = ' checked="checked" ';
 9692:                     }
 9693:                 } elsif ($role =~ /^priv_(author|community)$/) {
 9694:                     if (ref($settings) ne 'HASH') {
 9695:                         unless ($fields[$i] eq 'id') {
 9696:                             $check = ' checked="checked" ';
 9697:                         }
 9698:                     }
 9699:                 } elsif ($role =~ /^(unpriv|othdom)_/) {
 9700:                     if (ref($settings) ne 'HASH') {
 9701:                         if (($fields[$i] eq 'lastname') || ($fields[$i] eq 'firstname')) {
 9702:                             $check = ' checked="checked" ';
 9703:                         }
 9704:                     }
 9705:                 }
 9706:             } elsif ($context ne 'lti') {
 9707:                 if ($role eq 'st') {
 9708:                     if (ref($settings) ne 'HASH') {
 9709:                         $check = ' checked="checked" '; 
 9710:                     }
 9711:                 }
 9712:             }
 9713:         }
 9714:         $output .= '<td class="LC_left_item">'.
 9715:                    '<span class="LC_nobreak">';
 9716:         my $prefix = 'canmodify';
 9717:         if ($role eq 'emailusername') {
 9718:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
 9719:                 $checks{$fields[$i]} = 'omit';
 9720:             }
 9721:             foreach my $option ('required','optional','omit') {
 9722:                 my $checked='';
 9723:                 if ($checks{$fields[$i]} eq $option) {
 9724:                     $checked='checked="checked" ';
 9725:                 }
 9726:                 $output .= '<label>'.
 9727:                            '<input type="radio" name="'.$prefix.'_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
 9728:                            &mt($option).'</label>'.('&nbsp;' x2);
 9729:             }
 9730:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
 9731:         } else {
 9732:             if ($context eq 'lti') {
 9733:                 $prefix = 'lti';
 9734:             } elsif ($context eq 'privacy') {
 9735:                 $prefix = 'privacy';
 9736:             }
 9737:             $output .= '<label>'.
 9738:                        '<input type="checkbox" name="'.$prefix.'_'.$role.'" '.
 9739:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
 9740:                        '</label>';
 9741:         }
 9742:         $output .= '</span></td>';
 9743:     }
 9744:     $rem = $total%$numinrow;
 9745:     my $colsleft;
 9746:     if ($rem) {
 9747:         $colsleft = $numinrow - $rem;
 9748:     }
 9749:     if ($colsleft > 1) {
 9750:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9751:                    '&nbsp;</td>';
 9752:     } elsif ($colsleft == 1) {
 9753:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 9754:     }
 9755:     $output .= '</tr></table></td></tr>';
 9756:     return $output;
 9757: }
 9758: 
 9759: sub insttypes_row {
 9760:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
 9761:         $customcss,$rowstyle) = @_;
 9762:     my %lt = &Apache::lonlocal::texthash (
 9763:                       cansearch => 'Users allowed to search',
 9764:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
 9765:                       lockablenames => 'User preference to lock name',
 9766:                       selfassign    => 'Self-reportable affiliations',
 9767:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
 9768:              );
 9769:     my $showdom;
 9770:     if ($context eq 'cansearch') {
 9771:         $showdom = ' ('.$dom.')';
 9772:     }
 9773:     my $class = 'LC_left_item';
 9774:     if ($context eq 'statustocreate') {
 9775:         $class = 'LC_right_item';
 9776:     }
 9777:     my $css_class;
 9778:     if ($$rowtotal%2) {
 9779:         $css_class = 'LC_odd_row';
 9780:     }
 9781:     if ($customcss) {
 9782:         $css_class .= ' '.$customcss;
 9783:     }
 9784:     $css_class =~ s/^\s+//;
 9785:     if ($css_class) {
 9786:         $css_class = ' class="'.$css_class.'"';
 9787:     }
 9788:     if ($rowstyle) {
 9789:         $css_class .= ' style="'.$rowstyle.'"';
 9790:     }
 9791:     if ($onclick) {
 9792:         $onclick = 'onclick="'.$onclick.'" ';
 9793:     }
 9794:     my $output = '<tr'.$css_class.'>'.
 9795:                  '<td>'.$lt{$context}.$showdom.
 9796:                  '</td><td class="'.$class.'" colspan="2"><table>';
 9797:     my $rem;
 9798:     if (ref($types) eq 'ARRAY') {
 9799:         for (my $i=0; $i<@{$types}; $i++) {
 9800:             if (defined($usertypes->{$types->[$i]})) {
 9801:                 my $rem = $i%($numinrow);
 9802:                 if ($rem == 0) {
 9803:                     if ($i > 0) {
 9804:                         $output .= '</tr>';
 9805:                     }
 9806:                     $output .= '<tr>';
 9807:                 }
 9808:                 my $check = ' ';
 9809:                 if (ref($settings) eq 'HASH') {
 9810:                     if (ref($settings->{$context}) eq 'ARRAY') {
 9811:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
 9812:                             $check = ' checked="checked" ';
 9813:                         }
 9814:                     } elsif (ref($settings->{$context}) eq 'HASH') {
 9815:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
 9816:                             $check = ' checked="checked" ';
 9817:                         }
 9818:                     } elsif ($context eq 'statustocreate') {
 9819:                         $check = ' checked="checked" ';
 9820:                     }
 9821:                 }
 9822:                 $output .= '<td class="LC_left_item">'.
 9823:                            '<span class="LC_nobreak"><label>'.
 9824:                            '<input type="checkbox" name="'.$context.'" '.
 9825:                            'value="'.$types->[$i].'"'.$check.$onclick.' />'.
 9826:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 9827:             }
 9828:         }
 9829:         $rem = @{$types}%($numinrow);
 9830:     }
 9831:     my $colsleft = $numinrow - $rem;
 9832:     if ($context eq 'overrides') {
 9833:         if ($colsleft > 1) {
 9834:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 9835:         } else {
 9836:             $output .= '<td class="LC_left_item">';
 9837:         }
 9838:         $output .= '&nbsp;';  
 9839:     } else {
 9840:         if ($rem == 0) {
 9841:             $output .= '<tr>';
 9842:         }
 9843:         if ($colsleft > 1) {
 9844:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 9845:         } else {
 9846:             $output .= '<td class="LC_left_item">';
 9847:         }
 9848:         my $defcheck = ' ';
 9849:         if (ref($settings) eq 'HASH') {  
 9850:             if (ref($settings->{$context}) eq 'ARRAY') {
 9851:                 if (grep(/^default$/,@{$settings->{$context}})) {
 9852:                     $defcheck = ' checked="checked" ';
 9853:                 }
 9854:             } elsif ($context eq 'statustocreate') {
 9855:                 $defcheck = ' checked="checked" ';
 9856:             }
 9857:         }
 9858:         $output .= '<span class="LC_nobreak"><label>'.
 9859:                    '<input type="checkbox" name="'.$context.'" '.
 9860:                    'value="default"'.$defcheck.$onclick.' />'.
 9861:                    $othertitle.'</label></span>';
 9862:     }
 9863:     $output .= '</td></tr></table></td></tr>';
 9864:     return $output;
 9865: }
 9866: 
 9867: sub sorted_searchtitles {
 9868:     my %searchtitles = &Apache::lonlocal::texthash(
 9869:                          'uname' => 'username',
 9870:                          'lastname' => 'last name',
 9871:                          'lastfirst' => 'last name, first name',
 9872:                      );
 9873:     my @titleorder = ('uname','lastname','lastfirst');
 9874:     return (\%searchtitles,\@titleorder);
 9875: }
 9876: 
 9877: sub sorted_searchtypes {
 9878:     my %srchtypes_desc = (
 9879:                            exact    => 'is exact match',
 9880:                            contains => 'contains ..',
 9881:                            begins   => 'begins with ..',
 9882:                          );
 9883:     my @srchtypeorder = ('exact','begins','contains');
 9884:     return (\%srchtypes_desc,\@srchtypeorder);
 9885: }
 9886: 
 9887: sub usertype_update_row {
 9888:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
 9889:     my $datatable;
 9890:     my $numinrow = 4;
 9891:     foreach my $type (@{$types}) {
 9892:         if (defined($usertypes->{$type})) {
 9893:             $$rownums ++;
 9894:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
 9895:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
 9896:                           '</td><td class="LC_left_item"><table>';
 9897:             for (my $i=0; $i<@{$fields}; $i++) {
 9898:                 my $rem = $i%($numinrow);
 9899:                 if ($rem == 0) {
 9900:                     if ($i > 0) {
 9901:                         $datatable .= '</tr>';
 9902:                     }
 9903:                     $datatable .= '<tr>';
 9904:                 }
 9905:                 my $check = ' ';
 9906:                 if (ref($settings) eq 'HASH') {
 9907:                     if (ref($settings->{'fields'}) eq 'HASH') {
 9908:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
 9909:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
 9910:                                 $check = ' checked="checked" ';
 9911:                             }
 9912:                         }
 9913:                     }
 9914:                 }
 9915: 
 9916:                 if ($i == @{$fields}-1) {
 9917:                     my $colsleft = $numinrow - $rem;
 9918:                     if ($colsleft > 1) {
 9919:                         $datatable .= '<td colspan="'.$colsleft.'">';
 9920:                     } else {
 9921:                         $datatable .= '<td>';
 9922:                     }
 9923:                 } else {
 9924:                     $datatable .= '<td>';
 9925:                 }
 9926:                 $datatable .= '<span class="LC_nobreak"><label>'.
 9927:                               '<input type="checkbox" name="updateable_'.$type.
 9928:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
 9929:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
 9930:             }
 9931:             $datatable .= '</tr></table></td></tr>';
 9932:         }
 9933:     }
 9934:     return $datatable;
 9935: }
 9936: 
 9937: sub modify_login {
 9938:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
 9939:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
 9940:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon);
 9941:     %title = ( coursecatalog => 'Display course catalog',
 9942:                adminmail => 'Display administrator E-mail address',
 9943:                helpdesk  => 'Display "Contact Helpdesk" link',
 9944:                newuser => 'Link for visitors to create a user account',
 9945:                loginheader => 'Log-in box header');
 9946:     @offon = ('off','on');
 9947:     if (ref($domconfig{login}) eq 'HASH') {
 9948:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
 9949:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
 9950:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
 9951:             }
 9952:         }
 9953:     }
 9954:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
 9955:                                            \%domconfig,\%loginhash);
 9956:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 9957:     foreach my $item (@toggles) {
 9958:         $loginhash{login}{$item} = $env{'form.'.$item};
 9959:     }
 9960:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
 9961:     if (ref($colchanges{'login'}) eq 'HASH') {  
 9962:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
 9963:                                          \%loginhash);
 9964:     }
 9965: 
 9966:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 9967:     my %domservers = &Apache::lonnet::get_servers($dom);
 9968:     my @loginvia_attribs = ('serverpath','custompath','exempt');
 9969:     if (keys(%servers) > 1) {
 9970:         foreach my $lonhost (keys(%servers)) {
 9971:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
 9972:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
 9973:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
 9974:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
 9975:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
 9976:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 9977:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 9978:                         $changes{'loginvia'}{$lonhost} = 1;
 9979:                     } else {
 9980:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
 9981:                         $changes{'loginvia'}{$lonhost} = 1;
 9982:                     }
 9983:                 } else {
 9984:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 9985:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 9986:                         $changes{'loginvia'}{$lonhost} = 1;
 9987:                     }
 9988:                 }
 9989:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
 9990:                     foreach my $item (@loginvia_attribs) {
 9991:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
 9992:                     }
 9993:                 } else {
 9994:                     foreach my $item (@loginvia_attribs) {
 9995:                         my $new = $env{'form.'.$lonhost.'_'.$item};
 9996:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
 9997:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
 9998:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
 9999:                                 $new = '/';
10000:                             }
10001:                         }
10002:                         if (($item eq 'custompath') && 
10003:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
10004:                             $new = '';
10005:                         }
10006:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
10007:                             $changes{'loginvia'}{$lonhost} = 1;
10008:                         }
10009:                         if ($item eq 'exempt') {
10010:                             $new = &check_exempt_addresses($new);
10011:                         }
10012:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
10013:                     }
10014:                 }
10015:             } else {
10016:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
10017:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
10018:                     $changes{'loginvia'}{$lonhost} = 1;
10019:                     foreach my $item (@loginvia_attribs) {
10020:                         my $new = $env{'form.'.$lonhost.'_'.$item};
10021:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
10022:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
10023:                                 $new = '/';
10024:                             }
10025:                         }
10026:                         if (($item eq 'custompath') && 
10027:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
10028:                             $new = '';
10029:                         }
10030:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
10031:                     }
10032:                 }
10033:             }
10034:         }
10035:     }
10036: 
10037:     my $servadm = $r->dir_config('lonAdmEMail');
10038:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
10039:     if (ref($domconfig{'login'}) eq 'HASH') {
10040:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
10041:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
10042:                 if ($lang eq 'nolang') {
10043:                     push(@currlangs,$lang);
10044:                 } elsif (defined($langchoices{$lang})) {
10045:                     push(@currlangs,$lang);
10046:                 } else {
10047:                     next;
10048:                 }
10049:             }
10050:         }
10051:     }
10052:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
10053:     if (@currlangs > 0) {
10054:         foreach my $lang (@currlangs) {
10055:             if (grep(/^\Q$lang\E$/,@delurls)) {
10056:                 $changes{'helpurl'}{$lang} = 1;
10057:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
10058:                 $changes{'helpurl'}{$lang} = 1;
10059:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
10060:                 push(@newlangs,$lang);
10061:             } else {
10062:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
10063:             }
10064:         }
10065:     }
10066:     unless (grep(/^nolang$/,@currlangs)) {
10067:         if ($env{'form.loginhelpurl_nolang.filename'}) {
10068:             $changes{'helpurl'}{'nolang'} = 1;
10069:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
10070:             push(@newlangs,'nolang');
10071:         }
10072:     }
10073:     if ($env{'form.loginhelpurl_add_lang'}) {
10074:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
10075:             ($env{'form.loginhelpurl_add_file.filename'})) {
10076:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
10077:             $addedfile = $env{'form.loginhelpurl_add_lang'};
10078:         }
10079:     }
10080:     if ((@newlangs > 0) || ($addedfile)) {
10081:         my $error;
10082:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
10083:         if ($configuserok eq 'ok') {
10084:             if ($switchserver) {
10085:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
10086:             } elsif ($author_ok eq 'ok') {
10087:                 my @allnew = @newlangs;
10088:                 if ($addedfile ne '') {
10089:                     push(@allnew,$addedfile);
10090:                 }
10091:                 foreach my $lang (@allnew) {
10092:                     my $formelem = 'loginhelpurl_'.$lang;
10093:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
10094:                         $formelem = 'loginhelpurl_add_file';
10095:                     }
10096:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
10097:                                                                "help/$lang",'','',$newfile{$lang});
10098:                     if ($result eq 'ok') {
10099:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
10100:                         $changes{'helpurl'}{$lang} = 1;
10101:                     } else {
10102:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
10103:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
10104:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
10105:                             (!grep(/^\Q$lang\E$/,@delurls))) {
10106:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
10107:                         }
10108:                     }
10109:                 }
10110:             } else {
10111:                 $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);
10112:             }
10113:         } else {
10114:             $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);
10115:         }
10116:         if ($error) {
10117:             &Apache::lonnet::logthis($error);
10118:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10119:         }
10120:     }
10121: 
10122:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
10123:     if (ref($domconfig{'login'}) eq 'HASH') {
10124:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
10125:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
10126:                 if ($domservers{$lonhost}) {
10127:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
10128:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
10129:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
10130:                     }
10131:                 }
10132:             }
10133:         }
10134:     }
10135:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
10136:     foreach my $lonhost (sort(keys(%domservers))) {
10137:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
10138:             $changes{'headtag'}{$lonhost} = 1;
10139:         } else {
10140:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
10141:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
10142:             }
10143:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
10144:                 push(@newhosts,$lonhost);
10145:             } elsif ($currheadtagurls{$lonhost}) {
10146:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
10147:                 if ($currexempt{$lonhost}) {
10148:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
10149:                         $changes{'headtag'}{$lonhost} = 1;
10150:                     }
10151:                 } elsif ($possexempt{$lonhost}) {
10152:                     $changes{'headtag'}{$lonhost} = 1;
10153:                 }
10154:                 if ($possexempt{$lonhost}) {
10155:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
10156:                 }
10157:             }
10158:         }
10159:     }
10160:     if (@newhosts) {
10161:         my $error;
10162:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
10163:         if ($configuserok eq 'ok') {
10164:             if ($switchserver) {
10165:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
10166:             } elsif ($author_ok eq 'ok') {
10167:                 foreach my $lonhost (@newhosts) {
10168:                     my $formelem = 'loginheadtag_'.$lonhost;
10169:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
10170:                                                                           "login/headtag/$lonhost",'','',
10171:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
10172:                     if ($result eq 'ok') {
10173:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
10174:                         $changes{'headtag'}{$lonhost} = 1;
10175:                         if ($possexempt{$lonhost}) {
10176:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
10177:                         }
10178:                     } else {
10179:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
10180:                                            $newheadtagurls{$lonhost},$result);
10181:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
10182:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
10183:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
10184:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
10185:                         }
10186:                     }
10187:                 }
10188:             } else {
10189:                 $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);
10190:             }
10191:         } else {
10192:             $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);
10193:         }
10194:         if ($error) {
10195:             &Apache::lonnet::logthis($error);
10196:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10197:         }
10198:     }
10199:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
10200: 
10201:     my $defaulthelpfile = '/adm/loginproblems.html';
10202:     my $defaulttext = &mt('Default in use');
10203: 
10204:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
10205:                                              $dom);
10206:     if ($putresult eq 'ok') {
10207:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
10208:         my %defaultchecked = (
10209:                     'coursecatalog' => 'on',
10210:                     'helpdesk'      => 'on',
10211:                     'adminmail'     => 'off',
10212:                     'newuser'       => 'off',
10213:         );
10214:         if (ref($domconfig{'login'}) eq 'HASH') {
10215:             foreach my $item (@toggles) {
10216:                 if ($defaultchecked{$item} eq 'on') { 
10217:                     if (($domconfig{'login'}{$item} eq '0') &&
10218:                         ($env{'form.'.$item} eq '1')) {
10219:                         $changes{$item} = 1;
10220:                     } elsif (($domconfig{'login'}{$item} eq '' ||
10221:                               $domconfig{'login'}{$item} eq '1') &&
10222:                              ($env{'form.'.$item} eq '0')) {
10223:                         $changes{$item} = 1;
10224:                     }
10225:                 } elsif ($defaultchecked{$item} eq 'off') {
10226:                     if (($domconfig{'login'}{$item} eq '1') &&
10227:                         ($env{'form.'.$item} eq '0')) {
10228:                         $changes{$item} = 1;
10229:                     } elsif (($domconfig{'login'}{$item} eq '' ||
10230:                               $domconfig{'login'}{$item} eq '0') &&
10231:                              ($env{'form.'.$item} eq '1')) {
10232:                         $changes{$item} = 1;
10233:                     }
10234:                 }
10235:             }
10236:         }
10237:         if (keys(%changes) > 0 || $colchgtext) {
10238:             &Apache::loncommon::devalidate_domconfig_cache($dom);
10239:             if (ref($lastactref) eq 'HASH') {
10240:                 $lastactref->{'domainconfig'} = 1;
10241:             }
10242:             $resulttext = &mt('Changes made:').'<ul>';
10243:             foreach my $item (sort(keys(%changes))) {
10244:                 if ($item eq 'loginvia') {
10245:                     if (ref($changes{$item}) eq 'HASH') {
10246:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
10247:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
10248:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
10249:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
10250:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
10251:                                     $protocol = 'http' if ($protocol ne 'https');
10252:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
10253: 
10254:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
10255:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
10256:                                     } else {
10257:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
10258:                                     }
10259:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
10260:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
10261:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
10262:                                     }
10263:                                     $resulttext .= '</li>';
10264:                                 } else {
10265:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
10266:                                 }
10267:                             } else {
10268:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
10269:                             }
10270:                         }
10271:                         $resulttext .= '</ul></li>';
10272:                     }
10273:                 } elsif ($item eq 'helpurl') {
10274:                     if (ref($changes{$item}) eq 'HASH') {
10275:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
10276:                             if (grep(/^\Q$lang\E$/,@delurls)) {
10277:                                 my ($chg,$link);
10278:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
10279:                                 if ($lang eq 'nolang') {
10280:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
10281:                                 } else {
10282:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
10283:                                 }
10284:                                 $resulttext .= '<li>'.$chg.'</li>';
10285:                             } else {
10286:                                 my $chg;
10287:                                 if ($lang eq 'nolang') {
10288:                                     $chg = &mt('custom log-in help file for no preferred language');
10289:                                 } else {
10290:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
10291:                                 }
10292:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
10293:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
10294:                                                       '?inhibitmenu=yes',$chg,600,500).
10295:                                                '</li>';
10296:                             }
10297:                         }
10298:                     }
10299:                 } elsif ($item eq 'headtag') {
10300:                     if (ref($changes{$item}) eq 'HASH') {
10301:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
10302:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
10303:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
10304:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
10305:                                 $resulttext .= '<li><a href="'.
10306:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
10307:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
10308:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
10309:                                 if ($possexempt{$lonhost}) {
10310:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
10311:                                 } else {
10312:                                     $resulttext .= &mt('included for any client IP');
10313:                                 }
10314:                                 $resulttext .= '</li>';
10315:                             }
10316:                         }
10317:                     }
10318:                 } elsif ($item eq 'captcha') {
10319:                     if (ref($loginhash{'login'}) eq 'HASH') {
10320:                         my $chgtxt;
10321:                         if ($loginhash{'login'}{$item} eq 'notused') {
10322:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
10323:                         } else {
10324:                             my %captchas = &captcha_phrases();
10325:                             if ($captchas{$loginhash{'login'}{$item}}) {
10326:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
10327:                             } else {
10328:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
10329:                             }
10330:                         }
10331:                         $resulttext .= '<li>'.$chgtxt.'</li>';
10332:                     }
10333:                 } elsif ($item eq 'recaptchakeys') {
10334:                     if (ref($loginhash{'login'}) eq 'HASH') {
10335:                         my ($privkey,$pubkey);
10336:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
10337:                             $pubkey = $loginhash{'login'}{$item}{'public'};
10338:                             $privkey = $loginhash{'login'}{$item}{'private'};
10339:                         }
10340:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
10341:                         if (!$pubkey) {
10342:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
10343:                         } else {
10344:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
10345:                         }
10346:                         if (!$privkey) {
10347:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
10348:                         } else {
10349:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
10350:                         }
10351:                         $chgtxt .= '</ul>';
10352:                         $resulttext .= '<li>'.$chgtxt.'</li>';
10353:                     }
10354:                 } elsif ($item eq 'recaptchaversion') {
10355:                     if (ref($loginhash{'login'}) eq 'HASH') {
10356:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
10357:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
10358:                                            '</li>';
10359:                         }
10360:                     }
10361:                 } else {
10362:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
10363:                 }
10364:             }
10365:             $resulttext .= $colchgtext.'</ul>';
10366:         } else {
10367:             $resulttext = &mt('No changes made to log-in page settings');
10368:         }
10369:     } else {
10370:         $resulttext = '<span class="LC_error">'.
10371: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
10372:     }
10373:     if ($errors) {
10374:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
10375:                        $errors.'</ul>';
10376:     }
10377:     return $resulttext;
10378: }
10379: 
10380: sub check_exempt_addresses {
10381:     my ($iplist) = @_;
10382:     $iplist =~ s/^\s+//;
10383:     $iplist =~ s/\s+$//;
10384:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
10385:     my (@okips,$new);
10386:     foreach my $ip (@poss_ips) {
10387:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
10388:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
10389:                 push(@okips,$ip);
10390:             }
10391:         }
10392:     }
10393:     if (@okips > 0) {
10394:         $new = join(',',@okips);
10395:     } else {
10396:         $new = '';
10397:     }
10398:     return $new;
10399: }
10400: 
10401: sub color_font_choices {
10402:     my %choices =
10403:         &Apache::lonlocal::texthash (
10404:             img => "Header",
10405:             bgs => "Background colors",
10406:             links => "Link colors",
10407:             images => "Images",
10408:             font => "Font color",
10409:             fontmenu => "Font menu",
10410:             pgbg => "Page",
10411:             tabbg => "Header",
10412:             sidebg => "Border",
10413:             link => "Link",
10414:             alink => "Active link",
10415:             vlink => "Visited link",
10416:         );
10417:     return %choices;
10418: }
10419: 
10420: sub modify_rolecolors {
10421:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
10422:     my ($resulttext,%rolehash);
10423:     $rolehash{'rolecolors'} = {};
10424:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
10425:         if ($domconfig{'rolecolors'} eq '') {
10426:             $domconfig{'rolecolors'} = {};
10427:         }
10428:     }
10429:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
10430:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
10431:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
10432:                                              $dom);
10433:     if ($putresult eq 'ok') {
10434:         if (keys(%changes) > 0) {
10435:             &Apache::loncommon::devalidate_domconfig_cache($dom);
10436:             if (ref($lastactref) eq 'HASH') {
10437:                 $lastactref->{'domainconfig'} = 1;
10438:             }
10439:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
10440:                                              $rolehash{'rolecolors'});
10441:         } else {
10442:             $resulttext = &mt('No changes made to default color schemes');
10443:         }
10444:     } else {
10445:         $resulttext = '<span class="LC_error">'.
10446: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
10447:     }
10448:     if ($errors) {
10449:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
10450:                        $errors.'</ul>';
10451:     }
10452:     return $resulttext;
10453: }
10454: 
10455: sub modify_colors {
10456:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
10457:     my (%changes,%choices);
10458:     my @bgs;
10459:     my @links = ('link','alink','vlink');
10460:     my @logintext;
10461:     my @images;
10462:     my $servadm = $r->dir_config('lonAdmEMail');
10463:     my $errors;
10464:     my %defaults;
10465:     foreach my $role (@{$roles}) {
10466:         if ($role eq 'login') {
10467:             %choices = &login_choices();
10468:             @logintext = ('textcol','bgcol');
10469:         } else {
10470:             %choices = &color_font_choices();
10471:         }
10472:         if ($role eq 'login') {
10473:             @images = ('img','logo','domlogo','login');
10474:             @bgs = ('pgbg','mainbg','sidebg');
10475:         } else {
10476:             @images = ('img');
10477:             @bgs = ('pgbg','tabbg','sidebg');
10478:         }
10479:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
10480:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
10481:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
10482:         }
10483:         if ($role eq 'login') {
10484:             foreach my $item (@logintext) {
10485:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10486:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10487:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10488:                 }
10489:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
10490:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10491:                 }
10492:             }
10493:         } else {
10494:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
10495:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
10496:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
10497:             }
10498:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
10499:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
10500:             }
10501:         }
10502:         foreach my $item (@bgs) {
10503:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10504:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10505:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10506:             }
10507:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
10508:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10509:             }
10510:         }
10511:         foreach my $item (@links) {
10512:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10513:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10514:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10515:             }
10516:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
10517:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10518:             }
10519:         }
10520:         my ($configuserok,$author_ok,$switchserver) = 
10521:             &config_check($dom,$confname,$servadm);
10522:         my ($width,$height) = &thumb_dimensions();
10523:         if (ref($domconfig->{$role}) ne 'HASH') {
10524:             $domconfig->{$role} = {};
10525:         }
10526:         foreach my $img (@images) {
10527:             if (($role eq 'login') && (($img eq 'img') || ($img eq 'logo'))) {  
10528:                 if (defined($env{'form.login_showlogo_'.$img})) {
10529:                     $confhash->{$role}{'showlogo'}{$img} = 1;
10530:                 } else { 
10531:                     $confhash->{$role}{'showlogo'}{$img} = 0;
10532:                 }
10533:             } 
10534: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
10535: 		 && !defined($domconfig->{$role}{$img})
10536: 		 && !$env{'form.'.$role.'_del_'.$img}
10537: 		 && $env{'form.'.$role.'_import_'.$img}) {
10538: 		# import the old configured image from the .tab setting
10539: 		# if they haven't provided a new one 
10540: 		$domconfig->{$role}{$img} = 
10541: 		    $env{'form.'.$role.'_import_'.$img};
10542: 	    }
10543:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
10544:                 my $error;
10545:                 if ($configuserok eq 'ok') {
10546:                     if ($switchserver) {
10547:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
10548:                     } else {
10549:                         if ($author_ok eq 'ok') {
10550:                             my ($result,$logourl) = 
10551:                                 &publishlogo($r,'upload',$role.'_'.$img,
10552:                                            $dom,$confname,$img,$width,$height);
10553:                             if ($result eq 'ok') {
10554:                                 $confhash->{$role}{$img} = $logourl;
10555:                                 $changes{$role}{'images'}{$img} = 1;
10556:                             } else {
10557:                                 $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);
10558:                             }
10559:                         } else {
10560:                             $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);
10561:                         }
10562:                     }
10563:                 } else {
10564:                     $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);
10565:                 }
10566:                 if ($error) {
10567:                     &Apache::lonnet::logthis($error);
10568:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10569:                 }
10570:             } elsif ($domconfig->{$role}{$img} ne '') {
10571:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
10572:                     my $error;
10573:                     if ($configuserok eq 'ok') {
10574: # is confname an author?
10575:                         if ($switchserver eq '') {
10576:                             if ($author_ok eq 'ok') {
10577:                                 my ($result,$logourl) = 
10578:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
10579:                                             $dom,$confname,$img,$width,$height);
10580:                                 if ($result eq 'ok') {
10581:                                     $confhash->{$role}{$img} = $logourl;
10582: 				    $changes{$role}{'images'}{$img} = 1;
10583:                                 }
10584:                             }
10585:                         }
10586:                     }
10587:                 }
10588:             }
10589:         }
10590:         if (ref($domconfig) eq 'HASH') {
10591:             if (ref($domconfig->{$role}) eq 'HASH') {
10592:                 foreach my $img (@images) {
10593:                     if ($domconfig->{$role}{$img} ne '') {
10594:                         if ($env{'form.'.$role.'_del_'.$img}) {
10595:                             $confhash->{$role}{$img} = '';
10596:                             $changes{$role}{'images'}{$img} = 1;
10597:                         } else {
10598:                             if ($confhash->{$role}{$img} eq '') {
10599:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
10600:                             }
10601:                         }
10602:                     } else {
10603:                         if ($env{'form.'.$role.'_del_'.$img}) {
10604:                             $confhash->{$role}{$img} = '';
10605:                             $changes{$role}{'images'}{$img} = 1;
10606:                         } 
10607:                     }
10608:                     if (($role eq 'login') && (($img eq 'logo') || ($img eq 'img'))) {
10609:                         if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
10610:                             if ($confhash->{$role}{'showlogo'}{$img} ne 
10611:                                 $domconfig->{$role}{'showlogo'}{$img}) {
10612:                                 $changes{$role}{'showlogo'}{$img} = 1; 
10613:                             }
10614:                         } else {
10615:                             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
10616:                                 $changes{$role}{'showlogo'}{$img} = 1;
10617:                             }
10618:                         }
10619:                     }
10620:                 }
10621:                 if ($domconfig->{$role}{'font'} ne '') {
10622:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
10623:                         $changes{$role}{'font'} = 1;
10624:                     }
10625:                 } else {
10626:                     if ($confhash->{$role}{'font'}) {
10627:                         $changes{$role}{'font'} = 1;
10628:                     }
10629:                 }
10630:                 if ($role ne 'login') {
10631:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
10632:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
10633:                             $changes{$role}{'fontmenu'} = 1;
10634:                         }
10635:                     } else {
10636:                         if ($confhash->{$role}{'fontmenu'}) {
10637:                             $changes{$role}{'fontmenu'} = 1;
10638:                         }
10639:                     }
10640:                 }
10641:                 foreach my $item (@bgs) {
10642:                     if ($domconfig->{$role}{$item} ne '') {
10643:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
10644:                             $changes{$role}{'bgs'}{$item} = 1;
10645:                         } 
10646:                     } else {
10647:                         if ($confhash->{$role}{$item}) {
10648:                             $changes{$role}{'bgs'}{$item} = 1;
10649:                         }
10650:                     }
10651:                 }
10652:                 foreach my $item (@links) {
10653:                     if ($domconfig->{$role}{$item} ne '') {
10654:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
10655:                             $changes{$role}{'links'}{$item} = 1;
10656:                         }
10657:                     } else {
10658:                         if ($confhash->{$role}{$item}) {
10659:                             $changes{$role}{'links'}{$item} = 1;
10660:                         }
10661:                     }
10662:                 }
10663:                 foreach my $item (@logintext) {
10664:                     if ($domconfig->{$role}{$item} ne '') {
10665:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
10666:                             $changes{$role}{'logintext'}{$item} = 1;
10667:                         }
10668:                     } else {
10669:                         if ($confhash->{$role}{$item}) {
10670:                             $changes{$role}{'logintext'}{$item} = 1;
10671:                         }
10672:                     }
10673:                 }
10674:             } else {
10675:                 &default_change_checker($role,\@images,\@links,\@bgs,
10676:                                         \@logintext,$confhash,\%changes); 
10677:             }
10678:         } else {
10679:             &default_change_checker($role,\@images,\@links,\@bgs,
10680:                                     \@logintext,$confhash,\%changes); 
10681:         }
10682:     }
10683:     return ($errors,%changes);
10684: }
10685: 
10686: sub config_check {
10687:     my ($dom,$confname,$servadm) = @_;
10688:     my ($configuserok,$author_ok,$switchserver,%currroles);
10689:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
10690:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
10691:                                                    $confname,$servadm);
10692:     if ($configuserok eq 'ok') {
10693:         $switchserver = &check_switchserver($dom,$confname);
10694:         if ($switchserver eq '') {
10695:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
10696:         }
10697:     }
10698:     return ($configuserok,$author_ok,$switchserver);
10699: }
10700: 
10701: sub default_change_checker {
10702:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
10703:     foreach my $item (@{$links}) {
10704:         if ($confhash->{$role}{$item}) {
10705:             $changes->{$role}{'links'}{$item} = 1;
10706:         }
10707:     }
10708:     foreach my $item (@{$bgs}) {
10709:         if ($confhash->{$role}{$item}) {
10710:             $changes->{$role}{'bgs'}{$item} = 1;
10711:         }
10712:     }
10713:     foreach my $item (@{$logintext}) {
10714:         if ($confhash->{$role}{$item}) {
10715:             $changes->{$role}{'logintext'}{$item} = 1;
10716:         }
10717:     }
10718:     foreach my $img (@{$images}) {
10719:         if ($env{'form.'.$role.'_del_'.$img}) {
10720:             $confhash->{$role}{$img} = '';
10721:             $changes->{$role}{'images'}{$img} = 1;
10722:         }
10723:         if ($role eq 'login') {
10724:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
10725:                 $changes->{$role}{'showlogo'}{$img} = 1;
10726:             }
10727:         }
10728:     }
10729:     if ($confhash->{$role}{'font'}) {
10730:         $changes->{$role}{'font'} = 1;
10731:     }
10732: }
10733: 
10734: sub display_colorchgs {
10735:     my ($dom,$changes,$roles,$confhash) = @_;
10736:     my (%choices,$resulttext);
10737:     if (!grep(/^login$/,@{$roles})) {
10738:         $resulttext = &mt('Changes made:').'<br />';
10739:     }
10740:     foreach my $role (@{$roles}) {
10741:         if ($role eq 'login') {
10742:             %choices = &login_choices();
10743:         } else {
10744:             %choices = &color_font_choices();
10745:         }
10746:         if (ref($changes->{$role}) eq 'HASH') {
10747:             if ($role ne 'login') {
10748:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
10749:             }
10750:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
10751:                 if ($role ne 'login') {
10752:                     $resulttext .= '<ul>';
10753:                 }
10754:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
10755:                     if ($role ne 'login') {
10756:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
10757:                     }
10758:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
10759:                         if (($role eq 'login') && ($key eq 'showlogo')) {
10760:                             if ($confhash->{$role}{$key}{$item}) {
10761:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
10762:                             } else {
10763:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
10764:                             }
10765:                         } elsif ($confhash->{$role}{$item} eq '') {
10766:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
10767:                         } else {
10768:                             my $newitem = $confhash->{$role}{$item};
10769:                             if ($key eq 'images') {
10770:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" style="vertical-align: bottom" />';
10771:                             }
10772:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
10773:                         }
10774:                     }
10775:                     if ($role ne 'login') {
10776:                         $resulttext .= '</ul></li>';
10777:                     }
10778:                 } else {
10779:                     if ($confhash->{$role}{$key} eq '') {
10780:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
10781:                     } else {
10782:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
10783:                     }
10784:                 }
10785:                 if ($role ne 'login') {
10786:                     $resulttext .= '</ul>';
10787:                 }
10788:             }
10789:         }
10790:     }
10791:     return $resulttext;
10792: }
10793: 
10794: sub thumb_dimensions {
10795:     return ('200','50');
10796: }
10797: 
10798: sub check_dimensions {
10799:     my ($inputfile) = @_;
10800:     my ($fullwidth,$fullheight);
10801:     if ($inputfile =~ m|^[/\w.\-]+$|) {
10802:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
10803:             my $imageinfo = <PIPE>;
10804:             if (!close(PIPE)) {
10805:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
10806:             }
10807:             chomp($imageinfo);
10808:             my ($fullsize) = 
10809:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
10810:             if ($fullsize) {
10811:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
10812:             }
10813:         }
10814:     }
10815:     return ($fullwidth,$fullheight);
10816: }
10817: 
10818: sub check_configuser {
10819:     my ($uhome,$dom,$confname,$servadm) = @_;
10820:     my ($configuserok,%currroles);
10821:     if ($uhome eq 'no_host') {
10822:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
10823:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
10824:         $configuserok = 
10825:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
10826:                              $configpass,'','','','','',undef,$servadm);
10827:     } else {
10828:         $configuserok = 'ok';
10829:         %currroles = 
10830:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
10831:     }
10832:     return ($configuserok,%currroles);
10833: }
10834: 
10835: sub check_authorstatus {
10836:     my ($dom,$confname,%currroles) = @_;
10837:     my $author_ok;
10838:     if (!$currroles{':'.$dom.':au'}) {
10839:         my $start = time;
10840:         my $end = 0;
10841:         $author_ok = 
10842:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
10843:                                         'au',$end,$start,'','','domconfig');
10844:     } else {
10845:         $author_ok = 'ok';
10846:     }
10847:     return $author_ok;
10848: }
10849: 
10850: sub publishlogo {
10851:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
10852:     my ($output,$fname,$logourl,$madethumb);
10853:     if ($action eq 'upload') {
10854:         $fname=$env{'form.'.$formname.'.filename'};
10855:         chop($env{'form.'.$formname});
10856:     } else {
10857:         ($fname) = ($formname =~ /([^\/]+)$/);
10858:     }
10859:     if ($savefileas ne '') {
10860:         $fname = $savefileas;
10861:     }
10862:     $fname=&Apache::lonnet::clean_filename($fname);
10863: # See if there is anything left
10864:     unless ($fname) { return ('error: no uploaded file'); }
10865:     $fname="$subdir/$fname";
10866:     my $docroot=$r->dir_config('lonDocRoot');
10867:     my $filepath="$docroot/priv";
10868:     my $relpath = "$dom/$confname";
10869:     my ($fnamepath,$file,$fetchthumb);
10870:     $file=$fname;
10871:     if ($fname=~m|/|) {
10872:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
10873:     }
10874:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
10875:     my $count;
10876:     for ($count=5;$count<=$#parts;$count++) {
10877:         $filepath.="/$parts[$count]";
10878:         if ((-e $filepath)!=1) {
10879:             mkdir($filepath,02770);
10880:         }
10881:     }
10882:     # Check for bad extension and disallow upload
10883:     if ($file=~/\.(\w+)$/ &&
10884:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10885:         $output = 
10886:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
10887:     } elsif ($file=~/\.(\w+)$/ &&
10888:         !defined(&Apache::loncommon::fileembstyle($1))) {
10889:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
10890:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
10891:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
10892:     } elsif (-d "$filepath/$file") {
10893:         $output = &mt('Filename is a directory name - rename the file and re-upload');
10894:     } else {
10895:         my $source = $filepath.'/'.$file;
10896:         my $logfile;
10897:         if (!open($logfile,">>",$source.'.log')) {
10898:             return (&mt('No write permission to Authoring Space'));
10899:         }
10900:         print $logfile
10901: "\n================= Publish ".localtime()." ================\n".
10902: $env{'user.name'}.':'.$env{'user.domain'}."\n";
10903: # Save the file
10904:         if (!open(FH,">",$source)) {
10905:             &Apache::lonnet::logthis('Failed to create '.$source);
10906:             return (&mt('Failed to create file'));
10907:         }
10908:         if ($action eq 'upload') {
10909:             if (!print FH ($env{'form.'.$formname})) {
10910:                 &Apache::lonnet::logthis('Failed to write to '.$source);
10911:                 return (&mt('Failed to write file'));
10912:             }
10913:         } else {
10914:             my $original = &Apache::lonnet::filelocation('',$formname);
10915:             if(!copy($original,$source)) {
10916:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
10917:                 return (&mt('Failed to write file'));
10918:             }
10919:         }
10920:         close(FH);
10921:         chmod(0660, $source); # Permissions to rw-rw---.
10922: 
10923:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
10924:         my $copyfile=$targetdir.'/'.$file;
10925: 
10926:         my @parts=split(/\//,$targetdir);
10927:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
10928:         for (my $count=5;$count<=$#parts;$count++) {
10929:             $path.="/$parts[$count]";
10930:             if (!-e $path) {
10931:                 print $logfile "\nCreating directory ".$path;
10932:                 mkdir($path,02770);
10933:             }
10934:         }
10935:         my $versionresult;
10936:         if (-e $copyfile) {
10937:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
10938:         } else {
10939:             $versionresult = 'ok';
10940:         }
10941:         if ($versionresult eq 'ok') {
10942:             if (copy($source,$copyfile)) {
10943:                 print $logfile "\nCopied original source to ".$copyfile."\n";
10944:                 $output = 'ok';
10945:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
10946:                 push(@{$modified_urls},[$copyfile,$source]);
10947:                 my $metaoutput = 
10948:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
10949:                 unless ($registered_cleanup) {
10950:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
10951:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
10952:                     $registered_cleanup=1;
10953:                 }
10954:             } else {
10955:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
10956:                 $output = &mt('Failed to copy file to RES space').", $!";
10957:             }
10958:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
10959:                 my $inputfile = $filepath.'/'.$file;
10960:                 my $outfile = $filepath.'/'.'tn-'.$file;
10961:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
10962:                 if ($fullwidth ne '' && $fullheight ne '') { 
10963:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
10964:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
10965:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
10966:                         system({$args[0]} @args);
10967:                         chmod(0660, $filepath.'/tn-'.$file);
10968:                         if (-e $outfile) {
10969:                             my $copyfile=$targetdir.'/tn-'.$file;
10970:                             if (copy($outfile,$copyfile)) {
10971:                                 print $logfile "\nCopied source to ".$copyfile."\n";
10972:                                 my $thumb_metaoutput = 
10973:                                     &write_metadata($dom,$confname,$formname,
10974:                                                     $targetdir,'tn-'.$file,$logfile);
10975:                                 push(@{$modified_urls},[$copyfile,$outfile]);
10976:                                 unless ($registered_cleanup) {
10977:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
10978:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
10979:                                     $registered_cleanup=1;
10980:                                 }
10981:                                 $madethumb = 1;
10982:                             } else {
10983:                                 print $logfile "\nUnable to write ".$copyfile.
10984:                                                ':'.$!."\n";
10985:                             }
10986:                         }
10987:                     }
10988:                 }
10989:             }
10990:         } else {
10991:             $output = $versionresult;
10992:         }
10993:     }
10994:     return ($output,$logourl,$madethumb);
10995: }
10996: 
10997: sub logo_versioning {
10998:     my ($targetdir,$file,$logfile) = @_;
10999:     my $target = $targetdir.'/'.$file;
11000:     my ($maxversion,$fn,$extn,$output);
11001:     $maxversion = 0;
11002:     if ($file =~ /^(.+)\.(\w+)$/) {
11003:         $fn=$1;
11004:         $extn=$2;
11005:     }
11006:     opendir(DIR,$targetdir);
11007:     while (my $filename=readdir(DIR)) {
11008:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
11009:             $maxversion=($1>$maxversion)?$1:$maxversion;
11010:         }
11011:     }
11012:     $maxversion++;
11013:     print $logfile "\nCreating old version ".$maxversion."\n";
11014:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
11015:     if (copy($target,$copyfile)) {
11016:         print $logfile "Copied old target to ".$copyfile."\n";
11017:         $copyfile=$copyfile.'.meta';
11018:         if (copy($target.'.meta',$copyfile)) {
11019:             print $logfile "Copied old target metadata to ".$copyfile."\n";
11020:             $output = 'ok';
11021:         } else {
11022:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
11023:             $output = &mt('Failed to copy old meta').", $!, ";
11024:         }
11025:     } else {
11026:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
11027:         $output = &mt('Failed to copy old target').", $!, ";
11028:     }
11029:     return $output;
11030: }
11031: 
11032: sub write_metadata {
11033:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
11034:     my (%metadatafields,%metadatakeys,$output);
11035:     $metadatafields{'title'}=$formname;
11036:     $metadatafields{'creationdate'}=time;
11037:     $metadatafields{'lastrevisiondate'}=time;
11038:     $metadatafields{'copyright'}='public';
11039:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
11040:                                          $env{'user.domain'};
11041:     $metadatafields{'authorspace'}=$confname.':'.$dom;
11042:     $metadatafields{'domain'}=$dom;
11043:     {
11044:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
11045:         my $mfh;
11046:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
11047:             foreach (sort(keys(%metadatafields))) {
11048:                 unless ($_=~/\./) {
11049:                     my $unikey=$_;
11050:                     $unikey=~/^([A-Za-z]+)/;
11051:                     my $tag=$1;
11052:                     $tag=~tr/A-Z/a-z/;
11053:                     print $mfh "\n\<$tag";
11054:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
11055:                         my $value=$metadatafields{$unikey.'.'.$_};
11056:                         $value=~s/\"/\'\'/g;
11057:                         print $mfh ' '.$_.'="'.$value.'"';
11058:                     }
11059:                     print $mfh '>'.
11060:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
11061:                             .'</'.$tag.'>';
11062:                 }
11063:             }
11064:             $output = 'ok';
11065:             print $logfile "\nWrote metadata";
11066:             close($mfh);
11067:         } else {
11068:             print $logfile "\nFailed to open metadata file";
11069:             $output = &mt('Could not write metadata');
11070:         }
11071:     }
11072:     return $output;
11073: }
11074: 
11075: sub notifysubscribed {
11076:     foreach my $targetsource (@{$modified_urls}){
11077:         next unless (ref($targetsource) eq 'ARRAY');
11078:         my ($target,$source)=@{$targetsource};
11079:         if ($source ne '') {
11080:             if (open(my $logfh,">>",$source.'.log')) {
11081:                 print $logfh "\nCleanup phase: Notifications\n";
11082:                 my @subscribed=&subscribed_hosts($target);
11083:                 foreach my $subhost (@subscribed) {
11084:                     print $logfh "\nNotifying host ".$subhost.':';
11085:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
11086:                     print $logfh $reply;
11087:                 }
11088:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
11089:                 foreach my $subhost (@subscribedmeta) {
11090:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
11091:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
11092:                                                         $subhost);
11093:                     print $logfh $reply;
11094:                 }
11095:                 print $logfh "\n============ Done ============\n";
11096:                 close($logfh);
11097:             }
11098:         }
11099:     }
11100:     return OK;
11101: }
11102: 
11103: sub subscribed_hosts {
11104:     my ($target) = @_;
11105:     my @subscribed;
11106:     if (open(my $fh,"<","$target.subscription")) {
11107:         while (my $subline=<$fh>) {
11108:             if ($subline =~ /^($match_lonid):/) {
11109:                 my $host = $1;
11110:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
11111:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
11112:                         push(@subscribed,$host);
11113:                     }
11114:                 }
11115:             }
11116:         }
11117:     }
11118:     return @subscribed;
11119: }
11120: 
11121: sub check_switchserver {
11122:     my ($dom,$confname) = @_;
11123:     my ($allowed,$switchserver);
11124:     my $home = &Apache::lonnet::homeserver($confname,$dom);
11125:     if ($home eq 'no_host') {
11126:         $home = &Apache::lonnet::domain($dom,'primary');
11127:     }
11128:     my @ids=&Apache::lonnet::current_machine_ids();
11129:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
11130:     if (!$allowed) {
11131: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
11132:     }
11133:     return $switchserver;
11134: }
11135: 
11136: sub modify_quotas {
11137:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
11138:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
11139:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
11140:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
11141:         $validationfieldsref);
11142:     if ($action eq 'quotas') {
11143:         $context = 'tools'; 
11144:     } else {
11145:         $context = $action;
11146:     }
11147:     if ($context eq 'requestcourses') {
11148:         @usertools = ('official','unofficial','community','textbook','placement','lti');
11149:         @options =('norequest','approval','validate','autolimit');
11150:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
11151:         %titles = &courserequest_titles();
11152:         $toolregexp = join('|',@usertools);
11153:         %conditions = &courserequest_conditions();
11154:         $confname = $dom.'-domainconfig';
11155:         my $servadm = $r->dir_config('lonAdmEMail');
11156:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11157:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
11158:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
11159:     } elsif ($context eq 'requestauthor') {
11160:         @usertools = ('author');
11161:         %titles = &authorrequest_titles();
11162:     } else {
11163:         @usertools = ('aboutme','blog','webdav','portfolio');
11164:         %titles = &tool_titles();
11165:     }
11166:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
11167:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
11168:     foreach my $key (keys(%env)) {
11169:         if ($context eq 'requestcourses') {
11170:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
11171:                 my $item = $1;
11172:                 my $type = $2;
11173:                 if ($type =~ /^limit_(.+)/) {
11174:                     $limithash{$item}{$1} = $env{$key};
11175:                 } else {
11176:                     $confhash{$item}{$type} = $env{$key};
11177:                 }
11178:             }
11179:         } elsif ($context eq 'requestauthor') {
11180:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
11181:                 $confhash{$1} = $env{$key};
11182:             }
11183:         } else {
11184:             if ($key =~ /^form\.quota_(.+)$/) {
11185:                 $confhash{'defaultquota'}{$1} = $env{$key};
11186:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
11187:                 $confhash{'authorquota'}{$1} = $env{$key};
11188:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
11189:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
11190:             }
11191:         }
11192:     }
11193:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
11194:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
11195:         @approvalnotify = sort(@approvalnotify);
11196:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
11197:         my @crstypes = ('official','unofficial','community','textbook','placement','lti');
11198:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
11199:         foreach my $type (@hasuniquecode) {
11200:             if (grep(/^\Q$type\E$/,@crstypes)) {
11201:                 $confhash{'uniquecode'}{$type} = 1;
11202:             }
11203:         }
11204:         my (%newbook,%allpos);
11205:         if ($context eq 'requestcourses') {
11206:             foreach my $type ('textbooks','templates') {
11207:                 @{$allpos{$type}} = (); 
11208:                 my $invalid;
11209:                 if ($type eq 'textbooks') {
11210:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
11211:                 } else {
11212:                     $invalid = &mt('Invalid LON-CAPA course for template');
11213:                 }
11214:                 if ($env{'form.'.$type.'_addbook'}) {
11215:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
11216:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
11217:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
11218:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
11219:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
11220:                         } else {
11221:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
11222:                             my $position = $env{'form.'.$type.'_addbook_pos'};
11223:                             $position =~ s/\D+//g;
11224:                             if ($position ne '') {
11225:                                 $allpos{$type}[$position] = $newbook{$type};
11226:                             }
11227:                         }
11228:                     } else {
11229:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
11230:                     }
11231:                 }
11232:             } 
11233:         }
11234:         if (ref($domconfig{$action}) eq 'HASH') {
11235:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
11236:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
11237:                     $changes{'notify'}{'approval'} = 1;
11238:                 }
11239:             } else {
11240:                 if ($confhash{'notify'}{'approval'}) {
11241:                     $changes{'notify'}{'approval'} = 1;
11242:                 }
11243:             }
11244:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
11245:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
11246:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
11247:                         unless ($confhash{'uniquecode'}{$crstype}) {
11248:                             $changes{'uniquecode'} = 1;
11249:                         }
11250:                     }
11251:                     unless ($changes{'uniquecode'}) {
11252:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
11253:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
11254:                                 $changes{'uniquecode'} = 1;
11255:                             }
11256:                         }
11257:                     }
11258:                } else {
11259:                    $changes{'uniquecode'} = 1;
11260:                }
11261:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
11262:                 $changes{'uniquecode'} = 1;
11263:             }
11264:             if ($context eq 'requestcourses') {
11265:                 foreach my $type ('textbooks','templates') {
11266:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
11267:                         my %deletions;
11268:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
11269:                         if (@todelete) {
11270:                             map { $deletions{$_} = 1; } @todelete;
11271:                         }
11272:                         my %imgdeletions;
11273:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
11274:                         if (@todeleteimages) {
11275:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
11276:                         }
11277:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
11278:                         for (my $i=0; $i<=$maxnum; $i++) {
11279:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
11280:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
11281:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
11282:                                 if ($deletions{$key}) {
11283:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
11284:                                         #FIXME need to obsolete item in RES space
11285:                                     }
11286:                                     next;
11287:                                 } else {
11288:                                     my $newpos = $env{'form.'.$itemid};
11289:                                     $newpos =~ s/\D+//g;
11290:                                     foreach my $item ('subject','title','publisher','author') {
11291:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
11292:                                                  ($type eq 'templates'));
11293:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
11294:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
11295:                                             $changes{$type}{$key} = 1;
11296:                                         }
11297:                                     }
11298:                                     $allpos{$type}[$newpos] = $key;
11299:                                 }
11300:                                 if ($imgdeletions{$key}) {
11301:                                     $changes{$type}{$key} = 1;
11302:                                     #FIXME need to obsolete item in RES space
11303:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
11304:                                     my ($cdom,$cnum) = split(/_/,$key);
11305:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
11306:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
11307:                                     } else {
11308:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
11309:                                                                                       $cdom,$cnum,$type,$configuserok,
11310:                                                                                       $switchserver,$author_ok);
11311:                                         if ($imgurl) {
11312:                                             $confhash{$type}{$key}{'image'} = $imgurl;
11313:                                             $changes{$type}{$key} = 1; 
11314:                                         }
11315:                                         if ($error) {
11316:                                             &Apache::lonnet::logthis($error);
11317:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11318:                                         }
11319:                                     }
11320:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
11321:                                     $confhash{$type}{$key}{'image'} = 
11322:                                         $domconfig{$action}{$type}{$key}{'image'};
11323:                                 }
11324:                             }
11325:                         }
11326:                     }
11327:                 }
11328:             }
11329:         } else {
11330:             if ($confhash{'notify'}{'approval'}) {
11331:                 $changes{'notify'}{'approval'} = 1;
11332:             }
11333:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
11334:                 $changes{'uniquecode'} = 1;
11335:             }
11336:         }
11337:         if ($context eq 'requestcourses') {
11338:             foreach my $type ('textbooks','templates') {
11339:                 if ($newbook{$type}) {
11340:                     $changes{$type}{$newbook{$type}} = 1;
11341:                     foreach my $item ('subject','title','publisher','author') {
11342:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
11343:                                  ($type eq 'template'));
11344:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
11345:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
11346:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
11347:                         }
11348:                     }
11349:                     if ($type eq 'textbooks') {
11350:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
11351:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
11352:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
11353:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
11354:                             } else {
11355:                                 my ($imageurl,$error) =
11356:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
11357:                                                             $configuserok,$switchserver,$author_ok);
11358:                                 if ($imageurl) {
11359:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
11360:                                 }
11361:                                 if ($error) {
11362:                                     &Apache::lonnet::logthis($error);
11363:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11364:                                 }
11365:                             }
11366:                         }
11367:                     }
11368:                 }
11369:                 if (@{$allpos{$type}} > 0) {
11370:                     my $idx = 0;
11371:                     foreach my $item (@{$allpos{$type}}) {
11372:                         if ($item ne '') {
11373:                             $confhash{$type}{$item}{'order'} = $idx;
11374:                             if (ref($domconfig{$action}) eq 'HASH') {
11375:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
11376:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
11377:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
11378:                                             $changes{$type}{$item} = 1;
11379:                                         }
11380:                                     }
11381:                                 }
11382:                             }
11383:                             $idx ++;
11384:                         }
11385:                     }
11386:                 }
11387:             }
11388:             if (ref($validationitemsref) eq 'ARRAY') {
11389:                 foreach my $item (@{$validationitemsref}) {
11390:                     if ($item eq 'fields') {
11391:                         my @changed;
11392:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
11393:                         if (@{$confhash{'validation'}{$item}} > 0) {
11394:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
11395:                         }
11396:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11397:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11398:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
11399:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
11400:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
11401:                                 } else {
11402:                                     @changed = @{$confhash{'validation'}{$item}};
11403:                                 }
11404:                             } else {
11405:                                 @changed = @{$confhash{'validation'}{$item}};
11406:                             }
11407:                         } else {
11408:                             @changed = @{$confhash{'validation'}{$item}};
11409:                         }
11410:                         if (@changed) {
11411:                             if ($confhash{'validation'}{$item}) {
11412:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
11413:                             } else {
11414:                                 $changes{'validation'}{$item} = &mt('None');
11415:                             }
11416:                         }
11417:                     } else {
11418:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
11419:                         if ($item eq 'markup') {
11420:                             if ($env{'form.requestcourses_validation_'.$item}) {
11421:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
11422:                             }
11423:                         }
11424:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11425:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11426:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
11427:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11428:                                 }
11429:                             } else {
11430:                                 if ($confhash{'validation'}{$item} ne '') {
11431:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11432:                                 }
11433:                             }
11434:                         } else {
11435:                             if ($confhash{'validation'}{$item} ne '') {
11436:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11437:                             }
11438:                         }
11439:                     }
11440:                 }
11441:             }
11442:             if ($env{'form.validationdc'}) {
11443:                 my $newval = $env{'form.validationdc'};
11444:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
11445:                 if (exists($domcoords{$newval})) {
11446:                     $confhash{'validation'}{'dc'} = $newval;
11447:                 }
11448:             }
11449:             if (ref($confhash{'validation'}) eq 'HASH') {
11450:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11451:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11452:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
11453:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
11454:                                 if ($confhash{'validation'}{'dc'} eq '') {
11455:                                     $changes{'validation'}{'dc'} = &mt('None');
11456:                                 } else {
11457:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11458:                                 }
11459:                             }
11460:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
11461:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11462:                         }
11463:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
11464:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11465:                     }
11466:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
11467:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11468:                 }
11469:             } else {
11470:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11471:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11472:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
11473:                             $changes{'validation'}{'dc'} = &mt('None');
11474:                         }
11475:                     }
11476:                 }
11477:             }
11478:         }
11479:     } else {
11480:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
11481:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
11482:     }
11483:     foreach my $item (@usertools) {
11484:         foreach my $type (@{$types},'default','_LC_adv') {
11485:             my $unset; 
11486:             if ($context eq 'requestcourses') {
11487:                 $unset = '0';
11488:                 if ($type eq '_LC_adv') {
11489:                     $unset = '';
11490:                 }
11491:                 if ($confhash{$item}{$type} eq 'autolimit') {
11492:                     $confhash{$item}{$type} .= '=';
11493:                     unless ($limithash{$item}{$type} =~ /\D/) {
11494:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
11495:                     }
11496:                 }
11497:             } elsif ($context eq 'requestauthor') {
11498:                 $unset = '0';
11499:                 if ($type eq '_LC_adv') {
11500:                     $unset = '';
11501:                 }
11502:             } else {
11503:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
11504:                     $confhash{$item}{$type} = 1;
11505:                 } else {
11506:                     $confhash{$item}{$type} = 0;
11507:                 }
11508:             }
11509:             if (ref($domconfig{$action}) eq 'HASH') {
11510:                 if ($action eq 'requestauthor') {
11511:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
11512:                         $changes{$type} = 1;
11513:                     }
11514:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
11515:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
11516:                         $changes{$item}{$type} = 1;
11517:                     }
11518:                 } else {
11519:                     if ($context eq 'requestcourses') {
11520:                         if ($confhash{$item}{$type} ne $unset) {
11521:                             $changes{$item}{$type} = 1;
11522:                         }
11523:                     } else {
11524:                         if (!$confhash{$item}{$type}) {
11525:                             $changes{$item}{$type} = 1;
11526:                         }
11527:                     }
11528:                 }
11529:             } else {
11530:                 if ($context eq 'requestcourses') {
11531:                     if ($confhash{$item}{$type} ne $unset) {
11532:                         $changes{$item}{$type} = 1;
11533:                     }
11534:                 } elsif ($context eq 'requestauthor') {
11535:                     if ($confhash{$type} ne $unset) {
11536:                         $changes{$type} = 1;
11537:                     }
11538:                 } else {
11539:                     if (!$confhash{$item}{$type}) {
11540:                         $changes{$item}{$type} = 1;
11541:                     }
11542:                 }
11543:             }
11544:         }
11545:     }
11546:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
11547:         if (ref($domconfig{'quotas'}) eq 'HASH') {
11548:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
11549:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
11550:                     if (exists($confhash{'defaultquota'}{$key})) {
11551:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
11552:                             $changes{'defaultquota'}{$key} = 1;
11553:                         }
11554:                     } else {
11555:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
11556:                     }
11557:                 }
11558:             } else {
11559:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
11560:                     if (exists($confhash{'defaultquota'}{$key})) {
11561:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
11562:                             $changes{'defaultquota'}{$key} = 1;
11563:                         }
11564:                     } else {
11565:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
11566:                     }
11567:                 }
11568:             }
11569:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
11570:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
11571:                     if (exists($confhash{'authorquota'}{$key})) {
11572:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
11573:                             $changes{'authorquota'}{$key} = 1;
11574:                         }
11575:                     } else {
11576:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
11577:                     }
11578:                 }
11579:             }
11580:         }
11581:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
11582:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
11583:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
11584:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
11585:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
11586:                             $changes{'defaultquota'}{$key} = 1;
11587:                         }
11588:                     } else {
11589:                         if (!exists($domconfig{'quotas'}{$key})) {
11590:                             $changes{'defaultquota'}{$key} = 1;
11591:                         }
11592:                     }
11593:                 } else {
11594:                     $changes{'defaultquota'}{$key} = 1;
11595:                 }
11596:             }
11597:         }
11598:         if (ref($confhash{'authorquota'}) eq 'HASH') {
11599:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
11600:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
11601:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
11602:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
11603:                             $changes{'authorquota'}{$key} = 1;
11604:                         }
11605:                     } else {
11606:                         $changes{'authorquota'}{$key} = 1;
11607:                     }
11608:                 } else {
11609:                     $changes{'authorquota'}{$key} = 1;
11610:                 }
11611:             }
11612:         }
11613:     }
11614: 
11615:     if ($context eq 'requestauthor') {
11616:         $domdefaults{'requestauthor'} = \%confhash;
11617:     } else {
11618:         foreach my $key (keys(%confhash)) {
11619:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
11620:                 $domdefaults{$key} = $confhash{$key};
11621:             }
11622:         }
11623:     }
11624: 
11625:     my %quotahash = (
11626:                       $action => { %confhash }
11627:                     );
11628:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
11629:                                              $dom);
11630:     if ($putresult eq 'ok') {
11631:         if (keys(%changes) > 0) {
11632:             my $cachetime = 24*60*60;
11633:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
11634:             if (ref($lastactref) eq 'HASH') {
11635:                 $lastactref->{'domdefaults'} = 1;
11636:             }
11637:             $resulttext = &mt('Changes made:').'<ul>';
11638:             unless (($context eq 'requestcourses') ||
11639:                     ($context eq 'requestauthor')) {
11640:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
11641:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
11642:                     foreach my $type (@{$types},'default') {
11643:                         if (defined($changes{'defaultquota'}{$type})) {
11644:                             my $typetitle = $usertypes->{$type};
11645:                             if ($type eq 'default') {
11646:                                 $typetitle = $othertitle;
11647:                             }
11648:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
11649:                         }
11650:                     }
11651:                     $resulttext .= '</ul></li>';
11652:                 }
11653:                 if (ref($changes{'authorquota'}) eq 'HASH') {
11654:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
11655:                     foreach my $type (@{$types},'default') {
11656:                         if (defined($changes{'authorquota'}{$type})) {
11657:                             my $typetitle = $usertypes->{$type};
11658:                             if ($type eq 'default') {
11659:                                 $typetitle = $othertitle;
11660:                             }
11661:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
11662:                         }
11663:                     }
11664:                     $resulttext .= '</ul></li>';
11665:                 }
11666:             }
11667:             my %newenv;
11668:             foreach my $item (@usertools) {
11669:                 my (%haschgs,%inconf);
11670:                 if ($context eq 'requestauthor') {
11671:                     %haschgs = %changes;
11672:                     %inconf = %confhash;
11673:                 } else {
11674:                     if (ref($changes{$item}) eq 'HASH') {
11675:                         %haschgs = %{$changes{$item}};
11676:                     }
11677:                     if (ref($confhash{$item}) eq 'HASH') {
11678:                         %inconf = %{$confhash{$item}};
11679:                     }
11680:                 }
11681:                 if (keys(%haschgs) > 0) {
11682:                     my $newacc = 
11683:                         &Apache::lonnet::usertools_access($env{'user.name'},
11684:                                                           $env{'user.domain'},
11685:                                                           $item,'reload',$context);
11686:                     if (($context eq 'requestcourses') ||
11687:                         ($context eq 'requestauthor')) {
11688:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
11689:                             $newenv{'environment.canrequest.'.$item} = $newacc;
11690:                         }
11691:                     } else {
11692:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
11693:                             $newenv{'environment.availabletools.'.$item} = $newacc;
11694:                         }
11695:                     }
11696:                     unless ($context eq 'requestauthor') {
11697:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
11698:                     }
11699:                     foreach my $type (@{$types},'default','_LC_adv') {
11700:                         if ($haschgs{$type}) {
11701:                             my $typetitle = $usertypes->{$type};
11702:                             if ($type eq 'default') {
11703:                                 $typetitle = $othertitle;
11704:                             } elsif ($type eq '_LC_adv') {
11705:                                 $typetitle = 'LON-CAPA Advanced Users'; 
11706:                             }
11707:                             if ($inconf{$type}) {
11708:                                 if ($context eq 'requestcourses') {
11709:                                     my $cond;
11710:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
11711:                                         if ($1 eq '') {
11712:                                             $cond = &mt('(Automatic processing of any request).');
11713:                                         } else {
11714:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
11715:                                         }
11716:                                     } else { 
11717:                                         $cond = $conditions{$inconf{$type}};
11718:                                     }
11719:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
11720:                                 } elsif ($context eq 'requestauthor') {
11721:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
11722:                                                              $titles{$inconf{$type}},$typetitle);
11723: 
11724:                                 } else {
11725:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
11726:                                 }
11727:                             } else {
11728:                                 if ($type eq '_LC_adv') {
11729:                                     if ($inconf{$type} eq '0') {
11730:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
11731:                                     } else { 
11732:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
11733:                                     }
11734:                                 } else {
11735:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
11736:                                 }
11737:                             }
11738:                         }
11739:                     }
11740:                     unless ($context eq 'requestauthor') {
11741:                         $resulttext .= '</ul></li>';
11742:                     }
11743:                 }
11744:             }
11745:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
11746:                 if (ref($changes{'notify'}) eq 'HASH') {
11747:                     if ($changes{'notify'}{'approval'}) {
11748:                         if (ref($confhash{'notify'}) eq 'HASH') {
11749:                             if ($confhash{'notify'}{'approval'}) {
11750:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
11751:                             } else {
11752:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
11753:                             }
11754:                         }
11755:                     }
11756:                 }
11757:             }
11758:             if ($action eq 'requestcourses') {
11759:                 my @offon = ('off','on');
11760:                 if ($changes{'uniquecode'}) {
11761:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
11762:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
11763:                         $resulttext .= '<li>'.
11764:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
11765:                                        '</li>';
11766:                     } else {
11767:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
11768:                                        '</li>';
11769:                     }
11770:                 }
11771:                 foreach my $type ('textbooks','templates') {
11772:                     if (ref($changes{$type}) eq 'HASH') {
11773:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
11774:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
11775:                             my %coursehash = &Apache::lonnet::coursedescription($key);
11776:                             my $coursetitle = $coursehash{'description'};
11777:                             my $position = $confhash{$type}{$key}{'order'} + 1;
11778:                             $resulttext .= '<li>';
11779:                             foreach my $item ('subject','title','publisher','author') {
11780:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
11781:                                          ($type eq 'templates'));
11782:                                 my $name = $item.':';
11783:                                 $name =~ s/^(\w)/\U$1/;
11784:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
11785:                             }
11786:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
11787:                             if ($type eq 'textbooks') {
11788:                                 if ($confhash{$type}{$key}{'image'}) {
11789:                                     $resulttext .= ' '.&mt('Image: [_1]',
11790:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
11791:                                                    ' alt="Textbook cover" />').'<br />';
11792:                                 }
11793:                             }
11794:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
11795:                         }
11796:                         $resulttext .= '</ul></li>';
11797:                     }
11798:                 }
11799:                 if (ref($changes{'validation'}) eq 'HASH') {
11800:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
11801:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
11802:                         foreach my $item (@{$validationitemsref}) {
11803:                             if (exists($changes{'validation'}{$item})) {
11804:                                 if ($item eq 'markup') {
11805:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
11806:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
11807:                                 } else {
11808:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
11809:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
11810:                                 }
11811:                             }
11812:                         }
11813:                         if (exists($changes{'validation'}{'dc'})) {
11814:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
11815:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
11816:                         }
11817:                     }
11818:                 }
11819:             }
11820:             $resulttext .= '</ul>';
11821:             if (keys(%newenv)) {
11822:                 &Apache::lonnet::appenv(\%newenv);
11823:             }
11824:         } else {
11825:             if ($context eq 'requestcourses') {
11826:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
11827:             } elsif ($context eq 'requestauthor') {
11828:                 $resulttext = &mt('No changes made to rights to request author space.');
11829:             } else {
11830:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
11831:             }
11832:         }
11833:     } else {
11834:         $resulttext = '<span class="LC_error">'.
11835: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11836:     }
11837:     if ($errors) {
11838:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
11839:                        '<ul>'.$errors.'</ul></p>';
11840:     }
11841:     return $resulttext;
11842: }
11843: 
11844: sub process_textbook_image {
11845:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
11846:     my $filename = $env{'form.'.$caller.'.filename'};
11847:     my ($error,$url);
11848:     my ($width,$height) = (50,50);
11849:     if ($configuserok eq 'ok') {
11850:         if ($switchserver) {
11851:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
11852:                          $switchserver);
11853:         } elsif ($author_ok eq 'ok') {
11854:             my ($result,$imageurl) =
11855:                 &publishlogo($r,'upload',$caller,$dom,$confname,
11856:                              "$type/$cdom/$cnum/cover",$width,$height);
11857:             if ($result eq 'ok') {
11858:                 $url = $imageurl;
11859:             } else {
11860:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
11861:             }
11862:         } else {
11863:             $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);
11864:         }
11865:     } else {
11866:         $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);
11867:     }
11868:     return ($url,$error);
11869: }
11870: 
11871: sub modify_ltitools {
11872:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
11873:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
11874:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
11875:     my $confname = $dom.'-domainconfig';
11876:     my $servadm = $r->dir_config('lonAdmEMail');
11877:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11878:     my (%posslti,%possfield);
11879:     my @courseroles = ('cc','in','ta','ep','st');
11880:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
11881:     map { $posslti{$_} = 1; } @ltiroles;
11882:     my @allfields = ('fullname','firstname','lastname','email','user','roles');
11883:     map { $possfield{$_} = 1; } @allfields;
11884:     my %lt = &ltitools_names(); 
11885:     if ($env{'form.ltitools_add'}) {
11886:         my $title = $env{'form.ltitools_add_title'};
11887:         $title =~ s/(`)/'/g;
11888:         ($newid,my $error) = &get_ltitools_id($dom,$title);
11889:         if ($newid) {
11890:             my $position = $env{'form.ltitools_add_pos'};
11891:             $position =~ s/\D+//g;
11892:             if ($position ne '') {
11893:                 $allpos[$position] = $newid;
11894:             }
11895:             $changes{$newid} = 1;
11896:             foreach my $item ('title','url','key','secret','lifetime') {
11897:                 $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
11898:                 if ($item eq 'lifetime') {
11899:                     $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
11900:                 }
11901:                 if ($env{'form.ltitools_add_'.$item}) {
11902:                     if (($item eq 'key') || ($item eq 'secret')) {
11903:                         $encconfig{$newid}{$item} = $env{'form.ltitools_add_'.$item};
11904:                     } else {
11905:                         $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
11906:                     }
11907:                 }
11908:             }
11909:             if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
11910:                 $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
11911:             }
11912:             if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
11913:                 $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
11914:             }
11915:             if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
11916:                 $confhash{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
11917:             } else {
11918:                 $confhash{$newid}{'sigmethod'} = 'HMAC-SHA1';
11919:             }
11920:             foreach my $item ('width','height','linktext','explanation') {
11921:                 $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
11922:                 $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
11923:                 if (($item eq 'width') || ($item eq 'height')) {
11924:                     if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
11925:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
11926:                     }
11927:                 } else {
11928:                     if ($env{'form.ltitools_add_'.$item} ne '') {
11929:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item}; 
11930:                     }
11931:                 }
11932:             }
11933:             if ($env{'form.ltitools_add_target'} eq 'window') {
11934:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
11935:             } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
11936:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
11937:             } else {
11938:                 $confhash{$newid}{'display'}{'target'} = 'iframe';
11939:             }
11940:             foreach my $item ('passback','roster') {
11941:                 if ($env{'form.ltitools_'.$item.'_add'}) {
11942:                     $confhash{$newid}{$item} = 1;
11943:                     if ($env{'form.ltitools_'.$item.'valid_add'} ne '') {
11944:                         my $lifetime = $env{'form.ltitools_'.$item.'valid_add'};
11945:                         $lifetime =~ s/^\s+|\s+$//g;
11946:                         if ($lifetime =~ /^\d+\.?\d*$/) {
11947:                             $confhash{$newid}{$item.'valid'} = $lifetime;
11948:                         }
11949:                     }
11950:                 }
11951:             }
11952:             if ($env{'form.ltitools_add_image.filename'} ne '') {
11953:                 my ($imageurl,$error) =
11954:                     &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$newid,
11955:                                             $configuserok,$switchserver,$author_ok);
11956:                 if ($imageurl) {
11957:                     $confhash{$newid}{'image'} = $imageurl;
11958:                 }
11959:                 if ($error) {
11960:                     &Apache::lonnet::logthis($error);
11961:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11962:                 }
11963:             }
11964:             my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
11965:             foreach my $field (@fields) {
11966:                 if ($possfield{$field}) {
11967:                     if ($field eq 'roles') {
11968:                         foreach my $role (@courseroles) {
11969:                             my $choice = $env{'form.ltitools_add_roles_'.$role};
11970:                             if (($choice ne '') && ($posslti{$choice})) {
11971:                                 $confhash{$newid}{'roles'}{$role} = $choice;
11972:                                 if ($role eq 'cc') {
11973:                                     $confhash{$newid}{'roles'}{'co'} = $choice; 
11974:                                 }
11975:                             }
11976:                         }
11977:                     } else {
11978:                         $confhash{$newid}{'fields'}{$field} = 1;
11979:                     }
11980:                 }
11981:             }
11982:             if (ref($confhash{$newid}{'fields'}) eq 'HASH') {
11983:                 if ($confhash{$newid}{'fields'}{'user'}) {
11984:                     if ($env{'form.ltitools_userincdom_add'}) {
11985:                         $confhash{$newid}{'incdom'} = 1;
11986:                     }
11987:                 }
11988:             }
11989:             my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
11990:             foreach my $item (@courseconfig) {
11991:                 $confhash{$newid}{'crsconf'}{$item} = 1;
11992:             }
11993:             if ($env{'form.ltitools_add_custom'}) {
11994:                 my $name = $env{'form.ltitools_add_custom_name'};
11995:                 my $value = $env{'form.ltitools_add_custom_value'};
11996:                 $value =~ s/(`)/'/g;
11997:                 $name =~ s/(`)/'/g;
11998:                 $confhash{$newid}{'custom'}{$name} = $value;
11999:             }
12000:         } else {
12001:             my $error = &mt('Failed to acquire unique ID for new external tool');   
12002:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12003:         }
12004:     }
12005:     if (ref($domconfig{$action}) eq 'HASH') {
12006:         my %deletions;
12007:         my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
12008:         if (@todelete) {
12009:             map { $deletions{$_} = 1; } @todelete;
12010:         }
12011:         my %customadds;
12012:         my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
12013:         if (@newcustom) {
12014:             map { $customadds{$_} = 1; } @newcustom;
12015:         } 
12016:         my %imgdeletions;
12017:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
12018:         if (@todeleteimages) {
12019:             map { $imgdeletions{$_} = 1; } @todeleteimages;
12020:         }
12021:         my $maxnum = $env{'form.ltitools_maxnum'};
12022:         for (my $i=0; $i<=$maxnum; $i++) {
12023:             my $itemid = $env{'form.ltitools_id_'.$i};
12024:             $itemid =~ s/\D+//g;
12025:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
12026:                 if ($deletions{$itemid}) {
12027:                     if ($domconfig{$action}{$itemid}{'image'}) {
12028:                         #FIXME need to obsolete item in RES space
12029:                     }
12030:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
12031:                     next;
12032:                 } else {
12033:                     my $newpos = $env{'form.ltitools_'.$itemid};
12034:                     $newpos =~ s/\D+//g;
12035:                     foreach my $item ('title','url','lifetime') {
12036:                         $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
12037:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
12038:                             $changes{$itemid} = 1;
12039:                         }
12040:                     }
12041:                     foreach my $item ('key','secret') {
12042:                         $encconfig{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
12043:                         if ($domconfig{$action}{$itemid}{$item} ne $encconfig{$itemid}{$item}) {
12044:                             $changes{$itemid} = 1;
12045:                         }
12046:                     }
12047:                     if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
12048:                         $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
12049:                     }
12050:                     if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
12051:                         $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
12052:                     }
12053:                     if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
12054:                         $confhash{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
12055:                     } else {
12056:                         $confhash{$itemid}{'sigmethod'} = 'HMAC-SHA1'; 
12057:                     }
12058:                     if ($domconfig{$action}{$itemid}{'sigmethod'} eq '') {
12059:                         if ($confhash{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
12060:                             $changes{$itemid} = 1;
12061:                         }
12062:                     } elsif ($domconfig{$action}{$itemid}{'sigmethod'} ne $confhash{$itemid}{'sigmethod'}) {
12063:                         $changes{$itemid} = 1;
12064:                     }
12065:                     foreach my $size ('width','height') {
12066:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
12067:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
12068:                         if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
12069:                             $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
12070:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12071:                                 if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
12072:                                     $changes{$itemid} = 1;
12073:                                 }
12074:                             } else {
12075:                                 $changes{$itemid} = 1;
12076:                             }
12077:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12078:                             if ($domconfig{$action}{$itemid}{'display'}{$size} ne '') {
12079:                                 $changes{$itemid} = 1;
12080:                             }
12081:                         }
12082:                     }
12083:                     foreach my $item ('linktext','explanation') {
12084:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
12085:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
12086:                         if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
12087:                             $confhash{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
12088:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12089:                                 if ($domconfig{$action}{$itemid}{'display'}{$item} ne $confhash{$itemid}{'display'}{$item}) {
12090:                                     $changes{$itemid} = 1;
12091:                                 }
12092:                             } else {
12093:                                 $changes{$itemid} = 1;
12094:                             }
12095:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12096:                             if ($domconfig{$action}{$itemid}{'display'}{$item} ne '') {
12097:                                 $changes{$itemid} = 1;
12098:                             }
12099:                         }
12100:                     }
12101:                     if ($env{'form.ltitools_target_'.$i} eq 'window') {
12102:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
12103:                     } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
12104:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
12105:                     } else {
12106:                         $confhash{$itemid}{'display'}{'target'} = 'iframe';
12107:                     }
12108:                     if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12109:                         if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
12110:                             $changes{$itemid} = 1;
12111:                         }
12112:                     } else {
12113:                         $changes{$itemid} = 1;
12114:                     }
12115:                     foreach my $extra ('passback','roster') {
12116:                         if ($env{'form.ltitools_'.$extra.'_'.$i}) {
12117:                             $confhash{$itemid}{$extra} = 1;
12118:                             if ($env{'form.ltitools_'.$extra.'valid_'.$i} ne '') {
12119:                                 my $lifetime = $env{'form.ltitools_'.$extra.'valid_'.$i};
12120:                                 $lifetime =~ s/^\s+|\s+$//g;
12121:                                 if ($lifetime =~ /^\d+\.?\d*$/) {
12122:                                     $confhash{$itemid}{$extra.'valid'} = $lifetime;
12123:                                 }
12124:                             }
12125:                         }
12126:                         if ($domconfig{$action}{$itemid}{$extra} ne $confhash{$itemid}{$extra}) {
12127:                             $changes{$itemid} = 1;
12128:                         }
12129:                         if ($domconfig{$action}{$itemid}{$extra.'valid'} ne $confhash{$itemid}{$extra.'valid'}) {
12130:                             $changes{$itemid} = 1;
12131:                         }
12132:                     }
12133:                     my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
12134:                     foreach my $item ('label','title','target','linktext','explanation','append') {
12135:                         if (grep(/^\Q$item\E$/,@courseconfig)) {
12136:                             $confhash{$itemid}{'crsconf'}{$item} = 1;
12137:                             if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
12138:                                 if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
12139:                                     $changes{$itemid} = 1;
12140:                                 }
12141:                             } else {
12142:                                 $changes{$itemid} = 1;
12143:                             }
12144:                         }
12145:                     }
12146:                     my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
12147:                     foreach my $field (@fields) {
12148:                         if ($possfield{$field}) {
12149:                             if ($field eq 'roles') {
12150:                                 foreach my $role (@courseroles) {
12151:                                     my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
12152:                                     if (($choice ne '') && ($posslti{$choice})) {
12153:                                         $confhash{$itemid}{'roles'}{$role} = $choice;
12154:                                         if ($role eq 'cc') {
12155:                                             $confhash{$itemid}{'roles'}{'co'} = $choice;
12156:                                         }
12157:                                     }
12158:                                     if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
12159:                                         if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
12160:                                             $changes{$itemid} = 1;
12161:                                         }
12162:                                     } elsif ($confhash{$itemid}{'roles'}{$role}) {
12163:                                         $changes{$itemid} = 1;
12164:                                     }
12165:                                 }
12166:                             } else {
12167:                                 $confhash{$itemid}{'fields'}{$field} = 1;
12168:                                 if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
12169:                                     if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
12170:                                         $changes{$itemid} = 1;
12171:                                     }
12172:                                 } else {
12173:                                     $changes{$itemid} = 1;
12174:                                 }
12175:                             }
12176:                         }
12177:                     }
12178:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
12179:                         if ($confhash{$itemid}{'fields'}{'user'}) {
12180:                             if ($env{'form.ltitools_userincdom_'.$i}) {
12181:                                 $confhash{$itemid}{'incdom'} = 1;
12182:                             }
12183:                             if ($domconfig{$action}{$itemid}{'incdom'} ne $confhash{$itemid}{'incdom'}) {
12184:                                 $changes{$itemid} = 1;
12185:                             }
12186:                         }
12187:                     }
12188:                     $allpos[$newpos] = $itemid;
12189:                 }
12190:                 if ($imgdeletions{$itemid}) {
12191:                     $changes{$itemid} = 1;
12192:                     #FIXME need to obsolete item in RES space
12193:                 } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
12194:                     my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
12195:                                                                  $itemid,$configuserok,$switchserver,
12196:                                                                  $author_ok);
12197:                     if ($imgurl) {
12198:                         $confhash{$itemid}{'image'} = $imgurl;
12199:                         $changes{$itemid} = 1;
12200:                     }
12201:                     if ($error) {
12202:                         &Apache::lonnet::logthis($error);
12203:                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12204:                     }
12205:                 } elsif ($domconfig{$action}{$itemid}{'image'}) {
12206:                     $confhash{$itemid}{'image'} =
12207:                        $domconfig{$action}{$itemid}{'image'};
12208:                 }
12209:                 if ($customadds{$i}) {
12210:                     my $name = $env{'form.ltitools_custom_name_'.$i};
12211:                     $name =~ s/(`)/'/g;
12212:                     $name =~ s/^\s+//;
12213:                     $name =~ s/\s+$//;
12214:                     my $value = $env{'form.ltitools_custom_value_'.$i};
12215:                     $value =~ s/(`)/'/g;
12216:                     $value =~ s/^\s+//;
12217:                     $value =~ s/\s+$//;
12218:                     if ($name ne '') {
12219:                         $confhash{$itemid}{'custom'}{$name} = $value;
12220:                         $changes{$itemid} = 1;
12221:                     }
12222:                 }
12223:                 my %customdels;
12224:                 my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i); 
12225:                 if (@customdeletions) {
12226:                     $changes{$itemid} = 1;
12227:                 }
12228:                 map { $customdels{$_} = 1; } @customdeletions;
12229:                 if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
12230:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
12231:                         unless ($customdels{$key}) {
12232:                             if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
12233:                                 $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i}; 
12234:                             }
12235:                             if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
12236:                                 $changes{$itemid} = 1;
12237:                             }
12238:                         }
12239:                     }
12240:                 }
12241:                 unless ($changes{$itemid}) {
12242:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
12243:                         if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
12244:                             if (ref($confhash{$itemid}{$key}) eq 'HASH') {
12245:                                 foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
12246:                                     unless (exists($confhash{$itemid}{$key}{$innerkey})) {
12247:                                         $changes{$itemid} = 1;
12248:                                         last;
12249:                                     }
12250:                                 }
12251:                             } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
12252:                                 $changes{$itemid} = 1;
12253:                             }
12254:                         }
12255:                         last if ($changes{$itemid});
12256:                     }
12257:                 }
12258:             }
12259:         }
12260:     }
12261:     if (@allpos > 0) {
12262:         my $idx = 0;
12263:         foreach my $itemid (@allpos) {
12264:             if ($itemid ne '') {
12265:                 $confhash{$itemid}{'order'} = $idx;
12266:                 if (ref($domconfig{$action}) eq 'HASH') {
12267:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
12268:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
12269:                             $changes{$itemid} = 1;
12270:                         }
12271:                     }
12272:                 }
12273:                 $idx ++;
12274:             }
12275:         }
12276:     }
12277:     my %ltitoolshash = (
12278:                           $action => { %confhash }
12279:                        );
12280:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
12281:                                              $dom);
12282:     if ($putresult eq 'ok') {
12283:         my %ltienchash = (
12284:                              $action => { %encconfig }
12285:                          );
12286:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom);
12287:         if (keys(%changes) > 0) {
12288:             my $cachetime = 24*60*60;
12289:             my %ltiall = %confhash;
12290:             foreach my $id (keys(%ltiall)) {
12291:                 if (ref($encconfig{$id}) eq 'HASH') {
12292:                     foreach my $item ('key','secret') {
12293:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
12294:                     }
12295:                 }
12296:             }
12297:             &Apache::lonnet::do_cache_new('ltitools',$dom,\%ltiall,$cachetime);
12298:             if (ref($lastactref) eq 'HASH') {
12299:                 $lastactref->{'ltitools'} = 1;
12300:             }
12301:             $resulttext = &mt('Changes made:').'<ul>';
12302:             my %bynum;
12303:             foreach my $itemid (sort(keys(%changes))) {
12304:                 my $position = $confhash{$itemid}{'order'};
12305:                 $bynum{$position} = $itemid;
12306:             }
12307:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
12308:                 my $itemid = $bynum{$pos}; 
12309:                 if (ref($confhash{$itemid}) ne 'HASH') {
12310:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
12311:                 } else {
12312:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
12313:                     if ($confhash{$itemid}{'image'}) {
12314:                         $resulttext .= '&nbsp;'.
12315:                                        '<img src="'.$confhash{$itemid}{'image'}.'"'.
12316:                                        ' alt="'.&mt('Tool Provider icon').'" />';
12317:                     }
12318:                     $resulttext .= '</li><ul>';
12319:                     my $position = $pos + 1;
12320:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
12321:                     foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
12322:                         if ($confhash{$itemid}{$item} ne '') {
12323:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
12324:                         }
12325:                     }
12326:                     if ($encconfig{$itemid}{'key'} ne '') {
12327:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
12328:                     }
12329:                     if ($encconfig{$itemid}{'secret'} ne '') {
12330:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
12331:                         my $num = length($encconfig{$itemid}{'secret'});
12332:                         $resulttext .= ('*'x$num).'</li>';
12333:                     }
12334:                     $resulttext .= '<li>'.&mt('Configurable in course:');
12335:                     my @possconfig = ('label','title','target','linktext','explanation','append');
12336:                     my $numconfig = 0; 
12337:                     if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') { 
12338:                         foreach my $item (@possconfig) {
12339:                             if ($confhash{$itemid}{'crsconf'}{$item}) {
12340:                                 $numconfig ++;
12341:                                 $resulttext .= ' "'.$lt{'crs'.$item}.'"';
12342:                             }
12343:                         }
12344:                     }
12345:                     if (!$numconfig) {
12346:                         $resulttext .= &mt('None');
12347:                     }
12348:                     $resulttext .= '</li>';
12349:                     foreach my $item ('passback','roster') {
12350:                         $resulttext .= '<li>'.$lt{$item}.'&nbsp;';
12351:                         if ($confhash{$itemid}{$item}) {
12352:                             $resulttext .= &mt('Yes');
12353:                             if ($confhash{$itemid}{$item.'valid'}) {
12354:                                 if ($item eq 'passback') {
12355:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,day] after launch',
12356:                                                            $confhash{$itemid}{$item.'valid'});
12357:                                 } else {
12358:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,second] after launch',
12359:                                                            $confhash{$itemid}{$item.'valid'});
12360:                                 }
12361:                             }
12362:                         } else {
12363:                             $resulttext .= &mt('No');
12364:                         }
12365:                         $resulttext .= '</li>';
12366:                     }
12367:                     if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
12368:                         my $displaylist;
12369:                         if ($confhash{$itemid}{'display'}{'target'}) {
12370:                             $displaylist = &mt('Display target').':&nbsp;'.
12371:                                            $confhash{$itemid}{'display'}{'target'}.',';
12372:                         }
12373:                         foreach my $size ('width','height') { 
12374:                             if ($confhash{$itemid}{'display'}{$size}) {
12375:                                 $displaylist .= ('&nbsp;'x2).$lt{$size}.':&nbsp;'.
12376:                                                 $confhash{$itemid}{'display'}{$size}.',';
12377:                             }
12378:                         }
12379:                         if ($displaylist) {
12380:                             $displaylist =~ s/,$//;
12381:                             $resulttext .= '<li>'.$displaylist.'</li>';
12382:                         }
12383:                         foreach my $item ('linktext','explanation') {
12384:                             if ($confhash{$itemid}{'display'}{$item}) {
12385:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{'display'}{$item}.'</li>';
12386:                             }
12387:                         }
12388:                     }
12389:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
12390:                         my $fieldlist;
12391:                         foreach my $field (@allfields) {
12392:                             if ($confhash{$itemid}{'fields'}{$field}) {
12393:                                 $fieldlist .= ('&nbsp;'x2).$lt{$field}.',';
12394:                             }
12395:                         }
12396:                         if ($fieldlist) {
12397:                             $fieldlist =~ s/,$//;
12398:                             if ($confhash{$itemid}{'fields'}{'user'}) {
12399:                                 if ($confhash{$itemid}{'incdom'}) {
12400:                                     $fieldlist .= ' ('.&mt('username:domain').')';
12401:                                 } else {
12402:                                     $fieldlist .= ' ('.&mt('username').')';
12403:                                 }
12404:                             }
12405:                             $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
12406:                         }
12407:                     }
12408:                     if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
12409:                         my $rolemaps;
12410:                         foreach my $role (@courseroles) {
12411:                             if ($confhash{$itemid}{'roles'}{$role}) {
12412:                                 $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
12413:                                              $confhash{$itemid}{'roles'}{$role}.',';
12414:                             }
12415:                         }
12416:                         if ($rolemaps) {
12417:                             $rolemaps =~ s/,$//; 
12418:                             $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
12419:                         }
12420:                     }
12421:                     if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
12422:                         my $customlist;
12423:                         if (keys(%{$confhash{$itemid}{'custom'}})) {
12424:                             foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
12425:                                 $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.('&nbsp;'x2);
12426:                             } 
12427:                         }
12428:                         if ($customlist) {
12429:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
12430:                         }
12431:                     } 
12432:                     $resulttext .= '</ul></li>';
12433:                 }
12434:             }
12435:             $resulttext .= '</ul>';
12436:         } else {
12437:             $resulttext = &mt('No changes made.');
12438:         }
12439:     } else {
12440:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
12441:     }
12442:     if ($errors) {
12443:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
12444:                        $errors.'</ul>';
12445:     }
12446:     return $resulttext;
12447: }
12448: 
12449: sub process_ltitools_image {
12450:     my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
12451:     my $filename = $env{'form.'.$caller.'.filename'};
12452:     my ($error,$url);
12453:     my ($width,$height) = (21,21);
12454:     if ($configuserok eq 'ok') {
12455:         if ($switchserver) {
12456:             $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
12457:                          $switchserver);
12458:         } elsif ($author_ok eq 'ok') {
12459:             my ($result,$imageurl,$madethumb) =
12460:                 &publishlogo($r,'upload',$caller,$dom,$confname,
12461:                              "ltitools/$itemid/icon",$width,$height);
12462:             if ($result eq 'ok') {
12463:                 if ($madethumb) {
12464:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
12465:                     my $imagethumb = "$path/tn-".$imagefile;
12466:                     $url = $imagethumb;
12467:                 } else {
12468:                     $url = $imageurl;
12469:                 }
12470:             } else {
12471:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
12472:             }
12473:         } else {
12474:             $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);
12475:         }
12476:     } else {
12477:         $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);
12478:     }
12479:     return ($url,$error);
12480: }
12481: 
12482: sub get_ltitools_id {
12483:     my ($cdom,$title) = @_;
12484:     # get lock on ltitools db
12485:     my $lockhash = {
12486:                       lock => $env{'user.name'}.
12487:                               ':'.$env{'user.domain'},
12488:                    };
12489:     my $tries = 0;
12490:     my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
12491:     my ($id,$error);
12492:  
12493:     while (($gotlock ne 'ok') && ($tries<10)) {
12494:         $tries ++;
12495:         sleep (0.1);
12496:         $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
12497:     }
12498:     if ($gotlock eq 'ok') {
12499:         my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
12500:         if ($currids{'lock'}) {
12501:             delete($currids{'lock'});
12502:             if (keys(%currids)) {
12503:                 my @curr = sort { $a <=> $b } keys(%currids);
12504:                 if ($curr[-1] =~ /^\d+$/) {
12505:                     $id = 1 + $curr[-1];
12506:                 }
12507:             } else {
12508:                 $id = 1;
12509:             }
12510:             if ($id) {
12511:                 unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
12512:                     $error = 'nostore';
12513:                 }
12514:             } else {
12515:                 $error = 'nonumber';
12516:             }
12517:         }
12518:         my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
12519:     } else {
12520:         $error = 'nolock';
12521:     }
12522:     return ($id,$error);
12523: }
12524: 
12525: sub modify_lti {
12526:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
12527:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12528:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
12529:     my (%posslti,%posslticrs,%posscrstype);
12530:     my @courseroles = ('cc','in','ta','ep','st');
12531:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
12532:     my @lticourseroles = qw(Instructor TeachingAssistant Mentor Learner);
12533:     my @coursetypes = ('official','unofficial','community','textbook','placement');
12534:     my %coursetypetitles = &Apache::lonlocal::texthash (
12535:                                official   => 'Official',
12536:                                unofficial => 'Unofficial',
12537:                                community  => 'Community',
12538:                                textbook   => 'Textbook',
12539:                                placement  => 'Placement Test',
12540:     );
12541:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
12542:     my %lt = &lti_names();
12543:     map { $posslti{$_} = 1; } @ltiroles;
12544:     map { $posslticrs{$_} = 1; } @lticourseroles;
12545:     map { $posscrstype{$_} = 1; } @coursetypes;
12546: 
12547:     my %menutitles = &ltimenu_titles();
12548: 
12549:     my (@items,%deletions,%itemids);
12550:     if ($env{'form.lti_add'}) {
12551:         my $consumer = $env{'form.lti_consumer_add'};
12552:         $consumer =~ s/(`)/'/g;
12553:         ($newid,my $error) = &get_lti_id($dom,$consumer);
12554:         if ($newid) {
12555:             $itemids{'add'} = $newid;
12556:             push(@items,'add');
12557:             $changes{$newid} = 1;
12558:         } else {
12559:             my $error = &mt('Failed to acquire unique ID for new LTI configuration');
12560:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12561:         }
12562:     }
12563:     if (ref($domconfig{$action}) eq 'HASH') {
12564:         my @todelete = &Apache::loncommon::get_env_multiple('form.lti_del');
12565:         if (@todelete) {
12566:             map { $deletions{$_} = 1; } @todelete;
12567:         }
12568:         my $maxnum = $env{'form.lti_maxnum'};
12569:         for (my $i=0; $i<=$maxnum; $i++) {
12570:             my $itemid = $env{'form.lti_id_'.$i};
12571:             $itemid =~ s/\D+//g;
12572:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
12573:                 if ($deletions{$itemid}) {
12574:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'consumer'};
12575:                 } else {
12576:                    push(@items,$i);
12577:                    $itemids{$i} = $itemid;
12578:                 }
12579:             }
12580:         }
12581:     }
12582:     foreach my $idx (@items) {
12583:         my $itemid = $itemids{$idx};
12584:         next unless ($itemid);
12585:         my $position = $env{'form.lti_pos_'.$idx};
12586:         $position =~ s/\D+//g;
12587:         if ($position ne '') {
12588:             $allpos[$position] = $itemid;
12589:         }
12590:         foreach my $item ('consumer','key','secret','lifetime','requser') {
12591:             my $formitem = 'form.lti_'.$item.'_'.$idx;
12592:             $env{$formitem} =~ s/(`)/'/g;
12593:             if ($item eq 'lifetime') {
12594:                 $env{$formitem} =~ s/[^\d.]//g;
12595:             }
12596:             if ($env{$formitem} ne '') {
12597:                 if (($item eq 'key') || ($item eq 'secret')) {
12598:                     $encconfig{$itemid}{$item} = $env{$formitem};
12599:                 } else {
12600:                     $confhash{$itemid}{$item} = $env{$formitem};
12601:                     unless (($idx eq 'add') || ($changes{$itemid})) {
12602:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
12603:                             $changes{$itemid} = 1;
12604:                         }
12605:                     }
12606:                 }
12607:             }
12608:         }
12609:         if ($env{'form.lti_version_'.$idx} eq 'LTI-1p0') {
12610:             $confhash{$itemid}{'version'} = $env{'form.lti_version_'.$idx};
12611:         }
12612:         if ($confhash{$itemid}{'requser'}) {
12613:             if ($env{'form.lti_mapuser_'.$idx} eq 'sourcedid') {
12614:                 $confhash{$itemid}{'mapuser'} = 'lis_person_sourcedid'; 
12615:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'email') {
12616:                 $confhash{$itemid}{'mapuser'} = 'lis_person_contact_email_primary';
12617:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'other') {
12618:                 my $mapuser = $env{'form.lti_customuser_'.$idx};
12619:                 $mapuser =~ s/(`)/'/g;
12620:                 $mapuser =~ s/^\s+|\s+$//g; 
12621:                 $confhash{$itemid}{'mapuser'} = $mapuser; 
12622:             }
12623:             foreach my $ltirole (@lticourseroles) {
12624:                 my $possrole = $env{'form.lti_maprole_'.$ltirole.'_'.$idx};
12625:                 if (grep(/^\Q$possrole\E$/,@courseroles)) {
12626:                     $confhash{$itemid}{'maproles'}{$ltirole} = $possrole;
12627:                 }
12628:             }
12629:             my @possmakeuser = &Apache::loncommon::get_env_multiple('form.lti_makeuser_'.$idx);
12630:             my @makeuser;
12631:             foreach my $ltirole (sort(@possmakeuser)) {
12632:                 if ($posslti{$ltirole}) {
12633:                     push(@makeuser,$ltirole);
12634:                 }
12635:             }
12636:             $confhash{$itemid}{'makeuser'} = \@makeuser;
12637:             if (@makeuser) {
12638:                 my $lcauth = $env{'form.lti_lcauth_'.$idx};
12639:                 if ($lcauth =~ /^(internal|krb4|krb5|localauth)$/) {
12640:                     $confhash{$itemid}{'lcauth'} = $lcauth;
12641:                     if ($lcauth ne 'internal') {
12642:                         my $lcauthparm = $env{'form.lti_lcauthparm_'.$idx};
12643:                         $lcauthparm =~ s/^(\s+|\s+)$//g;
12644:                         $lcauthparm =~ s/`//g;
12645:                         if ($lcauthparm ne '') {
12646:                             $confhash{$itemid}{'lcauthparm'} = $lcauthparm;
12647:                         }
12648:                     }
12649:                 } else {
12650:                     $confhash{$itemid}{'lcauth'} = 'lti';
12651:                 }
12652:             }
12653:             my @possinstdata =  &Apache::loncommon::get_env_multiple('form.lti_instdata_'.$idx);
12654:             if (@possinstdata) {
12655:                 foreach my $field (@possinstdata) {
12656:                     if (exists($fieldtitles{$field})) {
12657:                         push(@{$confhash{$itemid}{'instdata'}});
12658:                     }
12659:                 }
12660:             }
12661:             if (($env{'form.lti_mapcrs_'.$idx} eq 'course_offering_sourcedid') ||
12662:                 ($env{'form.lti_mapcrs_'.$idx} eq 'context_id'))  {
12663:                 $confhash{$itemid}{'mapcrs'} = $env{'form.lti_mapcrs_'.$idx};
12664:             } elsif ($env{'form.lti_mapcrs_'.$idx} eq 'other') {
12665:                 my $mapcrs = $env{'form.lti_mapcrsfield_'.$idx}; 
12666:                 $mapcrs =~ s/(`)/'/g;
12667:                 $mapcrs =~ s/^\s+|\s+$//g;
12668:                 $confhash{$itemid}{'mapcrs'} = $mapcrs;
12669:             }
12670:             my @posstypes = &Apache::loncommon::get_env_multiple('form.lti_mapcrstype_'.$idx);
12671:             my @crstypes;
12672:             foreach my $type (sort(@posstypes)) {
12673:                 if ($posscrstype{$type}) {
12674:                     push(@crstypes,$type);
12675:                 }
12676:             }
12677:             $confhash{$itemid}{'mapcrstype'} = \@crstypes;
12678:             if ($env{'form.lti_makecrs_'.$idx}) {
12679:                 $confhash{$itemid}{'makecrs'} = 1;
12680:             }
12681:             my @possenroll = &Apache::loncommon::get_env_multiple('form.lti_selfenroll_'.$idx);
12682:             my @selfenroll;
12683:             foreach my $type (sort(@possenroll)) {
12684:                 if ($posslticrs{$type}) {
12685:                     push(@selfenroll,$type);
12686:                 }
12687:             }
12688:             $confhash{$itemid}{'selfenroll'} = \@selfenroll;
12689:             if ($env{'form.lti_crssec_'.$idx}) {
12690:                 if ($env{'form.lti_crssecsrc_'.$idx} eq 'course_section_sourcedid') {
12691:                     $confhash{$itemid}{'section'} = $env{'form.lti_crssecsrc_'.$idx};
12692:                 } elsif ($env{'form.lti_crssecsrc_'.$idx} eq 'other') {
12693:                     my $section = $env{'form.lti_customsection_'.$idx};
12694:                     $section =~ s/(`)/'/g;
12695:                     $section =~ s/^\s+|\s+$//g;
12696:                     if ($section ne '') {
12697:                         $confhash{$itemid}{'section'} = $section;
12698:                     }
12699:                 }
12700:             }
12701:             if ($env{'form.lti_callback_'.$idx}) {
12702:                 if ($env{'form.lti_callbackparam_'.$idx}) {
12703:                     my $callback = $env{'form.lti_callbackparam_'.$idx};
12704:                     $callback =~ s/^\s+|\s+$//g;
12705:                     $confhash{$itemid}{'callback'} = $callback;
12706:                 }
12707:             }
12708:             foreach my $field ('passback','roster','topmenu','inlinemenu') {
12709:                 if ($env{'form.lti_'.$field.'_'.$idx}) {
12710:                     $confhash{$itemid}{$field} = 1;
12711:                 }
12712:             }
12713:             if ($env{'form.lti_passback_'.$idx}) {
12714:                 if ($env{'form.lti_passbackformat_'.$idx} eq '1.0') {
12715:                     $confhash{$itemid}{'passbackformat'} = '1.0';
12716:                 } else {
12717:                     $confhash{$itemid}{'passbackformat'} = '1.1';
12718:                 }
12719:             }
12720:             if ($env{'form.lti_topmenu_'.$idx} || $env{'form.lti_inlinemenu_'.$idx}) {
12721:                 $confhash{$itemid}{lcmenu} = [];
12722:                 my @possmenu = &Apache::loncommon::get_env_multiple('form.lti_menuitem_'.$idx);
12723:                 foreach my $field (@possmenu) {
12724:                     if (exists($menutitles{$field})) {
12725:                         if ($field eq 'grades') {
12726:                             next unless ($env{'form.lti_inlinemenu_'.$idx});
12727:                         }
12728:                         push(@{$confhash{$itemid}{lcmenu}},$field);
12729:                     }
12730:                 }
12731:             }
12732:             unless (($idx eq 'add') || ($changes{$itemid})) {
12733:                 foreach my $field ('mapuser','mapcrs','makecrs','section','passback','roster','lcauth','lcauthparm','topmenu','inlinemenu','callback') {
12734:                     if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
12735:                         $changes{$itemid} = 1;
12736:                     }
12737:                 }
12738:                 unless ($changes{$itemid}) {
12739:                     if ($domconfig{$action}{$itemid}{'passback'} eq $confhash{$itemid}{'passback'}) {
12740:                         if ($domconfig{$action}{$itemid}{'passbackformat'} ne $confhash{$itemid}{'passbackformat'}) {
12741:                             $changes{$itemid} = 1;
12742:                         }
12743:                     }
12744:                 }
12745:                 foreach my $field ('makeuser','mapcrstype','selfenroll','instdata','lcmenu') {
12746:                     unless ($changes{$itemid}) {
12747:                         if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
12748:                             if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
12749:                                 my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
12750:                                                                                $confhash{$itemid}{$field});
12751:                                 if (@diffs) {
12752:                                     $changes{$itemid} = 1;
12753:                                 }
12754:                             } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
12755:                                 $changes{$itemid} = 1;
12756:                             }
12757:                         } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
12758:                             if (@{$confhash{$itemid}{$field}} > 0) {
12759:                                 $changes{$itemid} = 1;
12760:                             }
12761:                         }
12762:                     }
12763:                 }
12764:                 unless ($changes{$itemid}) {
12765:                     if (ref($domconfig{$action}{$itemid}{'maproles'}) eq 'HASH') {
12766:                         if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
12767:                             foreach my $ltirole (keys(%{$domconfig{$action}{$itemid}{'maproles'}})) {
12768:                                 if ($domconfig{$action}{$itemid}{'maproles'}{$ltirole} ne 
12769:                                     $confhash{$itemid}{'maproles'}{$ltirole}) {
12770:                                     $changes{$itemid} = 1;
12771:                                     last;
12772:                                 }
12773:                             }
12774:                             unless ($changes{$itemid}) {
12775:                                 foreach my $ltirole (keys(%{$confhash{$itemid}{'maproles'}})) {
12776:                                     if ($confhash{$itemid}{'maproles'}{$ltirole} ne 
12777:                                         $domconfig{$action}{$itemid}{'maproles'}{$ltirole}) {
12778:                                         $changes{$itemid} = 1;
12779:                                         last;
12780:                                     }
12781:                                 }
12782:                             }
12783:                         } elsif (keys(%{$domconfig{$action}{$itemid}{'maproles'}}) > 0) {
12784:                             $changes{$itemid} = 1;
12785:                         }
12786:                     } elsif (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
12787:                         unless ($changes{$itemid}) {
12788:                             if (keys(%{$confhash{$itemid}{'maproles'}}) > 0) {
12789:                                 $changes{$itemid} = 1;
12790:                             }
12791:                         }
12792:                     }
12793:                 }
12794:             }
12795:         }
12796:     }
12797:     if (@allpos > 0) {
12798:         my $idx = 0;
12799:         foreach my $itemid (@allpos) {
12800:             if ($itemid ne '') {
12801:                 $confhash{$itemid}{'order'} = $idx;
12802:                 if (ref($domconfig{$action}) eq 'HASH') {
12803:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
12804:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
12805:                             $changes{$itemid} = 1;
12806:                         }
12807:                     }
12808:                 }
12809:                 $idx ++;
12810:             }
12811:         }
12812:     }
12813:     my %ltihash = (
12814:                           $action => { %confhash }
12815:                        );
12816:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,
12817:                                              $dom);
12818:     if ($putresult eq 'ok') {
12819:         my %ltienchash = (
12820:                              $action => { %encconfig }
12821:                          );
12822:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom);
12823:         if (keys(%changes) > 0) {
12824:             my $cachetime = 24*60*60;
12825:             my %ltiall = %confhash;
12826:             foreach my $id (keys(%ltiall)) {
12827:                 if (ref($encconfig{$id}) eq 'HASH') {
12828:                     foreach my $item ('key','secret') {
12829:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
12830:                     }
12831:                 }
12832:             }
12833:             &Apache::lonnet::do_cache_new('lti',$dom,\%ltiall,$cachetime);
12834:             if (ref($lastactref) eq 'HASH') {
12835:                 $lastactref->{'lti'} = 1;
12836:             }
12837:             $resulttext = &mt('Changes made:').'<ul>';
12838:             my %bynum;
12839:             foreach my $itemid (sort(keys(%changes))) {
12840:                 my $position = $confhash{$itemid}{'order'};
12841:                 $bynum{$position} = $itemid;
12842:             }
12843:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
12844:                 my $itemid = $bynum{$pos};
12845:                 if (ref($confhash{$itemid}) ne 'HASH') {
12846:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
12847:                 } else {
12848:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'consumer'}.'</b></li><ul>';
12849:                     my $position = $pos + 1;
12850:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
12851:                     foreach my $item ('version','lifetime') {
12852:                         if ($confhash{$itemid}{$item} ne '') {
12853:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
12854:                         }
12855:                     }
12856:                     if ($encconfig{$itemid}{'key'} ne '') {
12857:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
12858:                     }
12859:                     if ($encconfig{$itemid}{'secret'} ne '') {
12860:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
12861:                         my $num = length($encconfig{$itemid}{'secret'});
12862:                         $resulttext .= ('*'x$num).'</li>';
12863:                     }
12864:                     if ($confhash{$itemid}{'requser'}) {
12865:                         if ($confhash{$itemid}{'mapuser'}) {
12866:                             my $shownmapuser;
12867:                             if ($confhash{$itemid}{'mapuser'} eq 'lis_person_sourcedid') {
12868:                                 $shownmapuser = $lt{'sourcedid'}.' (lis_person_sourcedid)';
12869:                             } elsif ($confhash{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') {
12870:                                 $shownmapuser = $lt{'email'}.' (lis_person_contact_email_primary)';
12871:                             } else {
12872:                                 $shownmapuser = &mt('Other').' ('.$confhash{$itemid}{'mapuser'}.')';
12873:                             }
12874:                             $resulttext .= '<li>'.&mt('LON-CAPA username').': '.$shownmapuser.'</li>';
12875:                         }
12876:                         if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
12877:                             my $rolemaps;
12878:                             foreach my $role (@ltiroles) {
12879:                                 if ($confhash{$itemid}{'maproles'}{$role}) {
12880:                                     $rolemaps .= ('&nbsp;'x2).$role.'='.
12881:                                                  &Apache::lonnet::plaintext($confhash{$itemid}{'maproles'}{$role},
12882:                                                                             'Course').',';
12883:                                 }
12884:                             }
12885:                             if ($rolemaps) {
12886:                                 $rolemaps =~ s/,$//;
12887:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
12888:                             }
12889:                         }
12890:                         if (ref($confhash{$itemid}{'makeuser'}) eq 'ARRAY') {
12891:                             if (@{$confhash{$itemid}{'makeuser'}} > 0) { 
12892:                                 $resulttext .= '<li>'.&mt('Following roles may create user accounts: [_1]',
12893:                                                           join(', ',@{$confhash{$itemid}{'makeuser'}})).'<br />';
12894:                                 if ($confhash{$itemid}{'lcauth'} eq 'lti') {
12895:                                     $resulttext .= &mt('New users will only be able to authenticate via LTI').'</li>';
12896:                                 } else {
12897:                                     $resulttext .= &mt('New users will be assigned LON-CAPA authentication: [_1]',
12898:                                                        $confhash{$itemid}{'lcauth'});
12899:                                     if ($confhash{$itemid}{'lcauth'} eq 'internal') {
12900:                                         $resulttext .= '; '.&mt('a randomly generated password will be created');
12901:                                     } elsif ($confhash{$itemid}{'lcauth'} eq 'localauth') {
12902:                                         if ($confhash{$itemid}{'lcauthparm'} ne '') {
12903:                                             $resulttext .= ' '.&mt('with argument: [_1]',$confhash{$itemid}{'lcauthparm'});
12904:                                         }
12905:                                     } else {
12906:                                         $resulttext .= '; '.&mt('Kerberos domain: [_1]',$confhash{$itemid}{'lcauthparm'});
12907:                                     }
12908:                                 }
12909:                                 $resulttext .= '</li>';
12910:                             } else {
12911:                                 $resulttext .= '<li>'.&mt('User account creation not permitted.').'</li>';
12912:                             }
12913:                         }
12914:                         if (ref($confhash{$itemid}{'instdata'}) eq 'ARRAY') {
12915:                             if (@{$confhash{$itemid}{'instdata'}} > 0) {
12916:                                 $resulttext .= '<li>'.&mt('Institutional data will be used when creating a new user for: [_1]',
12917:                                                           join(', ',map { $fieldtitles{$_}; } @{$confhash{$itemid}{'instdata'}})).'</li>';
12918:                             } else {
12919:                                 $resulttext .= '<li>'.&mt('No institutional data used when creating a new user.').'</li>';
12920:                             }
12921:                         }
12922:                         if ($confhash{$itemid}{'mapcrs'}) {
12923:                             $resulttext .= '<li>'.&mt('Unique course identifier').': '.$confhash{$itemid}{'mapcrs'}.'</li>';
12924:                         }
12925:                         if (ref($confhash{$itemid}{'mapcrstype'}) eq 'ARRAY') {
12926:                             if (@{$confhash{$itemid}{'mapcrstype'}} > 0) {
12927:                                 $resulttext .= '<li>'.&mt('Mapping for the following LON-CAPA course types: [_1]',
12928:                                                join(', ',map { $coursetypetitles{$_}; } @coursetypes)).
12929:                                                '</li>';
12930:                             } else {
12931:                                 $resulttext .= '<li>'.&mt('No mapping to LON-CAPA courses').'</li>';
12932:                             }
12933:                         }
12934:                         if ($confhash{$itemid}{'makecrs'}) {
12935:                             $resulttext .= '<li>'.&mt('Instructor may create course (if absent).').'</li>';
12936:                         } else {
12937:                             $resulttext .= '<li>'.&mt('Instructor may not create course (if absent).').'</li>';
12938:                         }
12939:                         if (ref($confhash{$itemid}{'selfenroll'}) eq 'ARRAY') {
12940:                             if (@{$confhash{$itemid}{'selfenroll'}} > 0) {
12941:                                 $resulttext .= '<li>'.&mt('Self-enrollment for following roles: [_1]',
12942:                                                           join(', ',@{$confhash{$itemid}{'selfenroll'}})).
12943:                                                '</li>';
12944:                             } else {
12945:                                 $resulttext .= '<li>'.&mt('Self-enrollment not permitted').'</li>';
12946:                             }
12947:                         }
12948:                         if ($confhash{$itemid}{'section'}) {
12949:                             if ($confhash{$itemid}{'section'} eq 'course_section_sourcedid') {
12950:                                 $resulttext .= '<li>'.&mt('User section from standard field:').
12951:                                                      ' (course_section_sourcedid)'.'</li>';  
12952:                             } else {
12953:                                 $resulttext .= '<li>'.&mt('User section from:').' '.
12954:                                                       $confhash{$itemid}{'section'}.'</li>';
12955:                             }
12956:                         } else {
12957:                             $resulttext .= '<li>'.&mt('No section assignment').'</li>';
12958:                         }
12959:                         if ($confhash{$itemid}{'callback'}) {
12960:                             $resulttext .= '<li>'.&mt('Callback setting').': '.$confhash{$itemid}{'callback'}.'</li>';
12961:                         } else {
12962:                             $resulttext .= '<li>'.&mt('No callback to logout LON-CAPA session when user logs out of Comsumer');
12963:                         }
12964:                         foreach my $item ('passback','roster','topmenu','inlinemenu') {
12965:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
12966:                             if ($confhash{$itemid}{$item}) {
12967:                                 $resulttext .= &mt('Yes');
12968:                                 if ($item eq 'passback') {
12969:                                     if ($confhash{$itemid}{'passbackformat'} eq '1.0') {
12970:                                         $resulttext .= '&nbsp;('.&mt('Outcomes Extension (1.0)').')';
12971:                                     } elsif ($confhash{$itemid}{'passbackformat'} eq '1.1') {
12972:                                         $resulttext .= '&nbsp;('.&mt('Outcomes Service (1.1)').')';
12973:                                     }
12974:                                 }
12975:                             } else {
12976:                                 $resulttext .= &mt('No');
12977:                             }
12978:                             $resulttext .= '</li>';
12979:                         }
12980:                         if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
12981:                             if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
12982:                                 $resulttext .= '<li>'.&mt('Menu items:').' '.
12983:                                                join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>'; 
12984:                             } else {
12985:                                 $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>'; 
12986:                             }
12987:                         }
12988:                     }
12989:                     $resulttext .= '</ul></li>';
12990:                 }
12991:             }
12992:             $resulttext .= '</ul>';
12993:         } else {
12994:             $resulttext = &mt('No changes made.');
12995:         }
12996:     } else {
12997:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
12998:     }
12999:     if ($errors) {
13000:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
13001:                        $errors.'</ul>';
13002:     }
13003:     return $resulttext;
13004: }
13005: 
13006: sub get_lti_id {
13007:     my ($domain,$consumer) = @_;
13008:     # get lock on lti db
13009:     my $lockhash = {
13010:                       lock => $env{'user.name'}.
13011:                               ':'.$env{'user.domain'},
13012:                    };
13013:     my $tries = 0;
13014:     my $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
13015:     my ($id,$error);
13016: 
13017:     while (($gotlock ne 'ok') && ($tries<10)) {
13018:         $tries ++;
13019:         sleep (0.1);
13020:         $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
13021:     }
13022:     if ($gotlock eq 'ok') {
13023:         my %currids = &Apache::lonnet::dump_dom('lti',$domain);
13024:         if ($currids{'lock'}) {
13025:             delete($currids{'lock'});
13026:             if (keys(%currids)) {
13027:                 my @curr = sort { $a <=> $b } keys(%currids);
13028:                 if ($curr[-1] =~ /^\d+$/) {
13029:                     $id = 1 + $curr[-1];
13030:                 }
13031:             } else {
13032:                 $id = 1;
13033:             }
13034:             if ($id) {
13035:                 unless (&Apache::lonnet::newput_dom('lti',{ $id => $consumer },$domain) eq 'ok') {
13036:                     $error = 'nostore';
13037:                 }
13038:             } else {
13039:                 $error = 'nonumber';
13040:             }
13041:         }
13042:         my $dellockoutcome = &Apache::lonnet::del_dom('lti',['lock'],$domain);
13043:     } else {
13044:         $error = 'nolock';
13045:     }
13046:     return ($id,$error);
13047: }
13048: 
13049: sub modify_autoenroll {
13050:     my ($dom,$lastactref,%domconfig) = @_;
13051:     my ($resulttext,%changes);
13052:     my %currautoenroll;
13053:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
13054:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
13055:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
13056:         }
13057:     }
13058:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
13059:     my %title = ( run => 'Auto-enrollment active',
13060:                   sender => 'Sender for notification messages',
13061:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
13062:                   failsafe => 'Failsafe for no drops if institutional data missing for a section');
13063:     my @offon = ('off','on');
13064:     my $sender_uname = $env{'form.sender_uname'};
13065:     my $sender_domain = $env{'form.sender_domain'};
13066:     if ($sender_domain eq '') {
13067:         $sender_uname = '';
13068:     } elsif ($sender_uname eq '') {
13069:         $sender_domain = '';
13070:     }
13071:     my $coowners = $env{'form.autoassign_coowners'};
13072:     my $failsafe = $env{'form.autoenroll_failsafe'};
13073:     $failsafe =~ s{^\s+|\s+$}{}g;
13074:     if ($failsafe =~ /\D/) {
13075:         undef($failsafe);
13076:     }
13077:     my %autoenrollhash =  (
13078:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
13079:                                        'sender_uname' => $sender_uname,
13080:                                        'sender_domain' => $sender_domain,
13081:                                        'co-owners' => $coowners,
13082:                                        'autofailsafe' => $failsafe,
13083:                                 }
13084:                      );
13085:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
13086:                                              $dom);
13087:     if ($putresult eq 'ok') {
13088:         if (exists($currautoenroll{'run'})) {
13089:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
13090:                  $changes{'run'} = 1;
13091:              }
13092:         } elsif ($autorun) {
13093:             if ($env{'form.autoenroll_run'} ne '1') {
13094:                  $changes{'run'} = 1;
13095:             }
13096:         }
13097:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
13098:             $changes{'sender'} = 1;
13099:         }
13100:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
13101:             $changes{'sender'} = 1;
13102:         }
13103:         if ($currautoenroll{'co-owners'} ne '') {
13104:             if ($currautoenroll{'co-owners'} ne $coowners) {
13105:                 $changes{'coowners'} = 1;
13106:             }
13107:         } elsif ($coowners) {
13108:             $changes{'coowners'} = 1;
13109:         }
13110:         if ($currautoenroll{'autofailsafe'} ne $failsafe) {
13111:             $changes{'autofailsafe'} = 1;
13112:         }
13113:         if (keys(%changes) > 0) {
13114:             $resulttext = &mt('Changes made:').'<ul>';
13115:             if ($changes{'run'}) {
13116:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
13117:             }
13118:             if ($changes{'sender'}) {
13119:                 if ($sender_uname eq '' || $sender_domain eq '') {
13120:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
13121:                 } else {
13122:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
13123:                 }
13124:             }
13125:             if ($changes{'coowners'}) {
13126:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
13127:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
13128:                 if (ref($lastactref) eq 'HASH') {
13129:                     $lastactref->{'domainconfig'} = 1;
13130:                 }
13131:             }
13132:             if ($changes{'autofailsafe'}) {
13133:                 if ($failsafe ne '') {
13134:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$failsafe).'</li>';
13135:                 } else {
13136:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section: deleted');
13137:                 }
13138:                 &Apache::lonnet::get_domain_defaults($dom,1);
13139:                 if (ref($lastactref) eq 'HASH') {
13140:                     $lastactref->{'domdefaults'} = 1;
13141:                 }
13142:             }
13143:             $resulttext .= '</ul>';
13144:         } else {
13145:             $resulttext = &mt('No changes made to auto-enrollment settings');
13146:         }
13147:     } else {
13148:         $resulttext = '<span class="LC_error">'.
13149: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
13150:     }
13151:     return $resulttext;
13152: }
13153: 
13154: sub modify_autoupdate {
13155:     my ($dom,%domconfig) = @_;
13156:     my ($resulttext,%currautoupdate,%fields,%changes);
13157:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
13158:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
13159:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
13160:         }
13161:     }
13162:     my @offon = ('off','on');
13163:     my %title = &Apache::lonlocal::texthash (
13164:                    run => 'Auto-update:',
13165:                    classlists => 'Updates to user information in classlists?'
13166:                 );
13167:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13168:     my %fieldtitles = &Apache::lonlocal::texthash (
13169:                         id => 'Student/Employee ID',
13170:                         permanentemail => 'E-mail address',
13171:                         lastname => 'Last Name',
13172:                         firstname => 'First Name',
13173:                         middlename => 'Middle Name',
13174:                         generation => 'Generation',
13175:                       );
13176:     $othertitle = &mt('All users');
13177:     if (keys(%{$usertypes}) >  0) {
13178:         $othertitle = &mt('Other users');
13179:     }
13180:     foreach my $key (keys(%env)) {
13181:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
13182:             my ($usertype,$item) = ($1,$2);
13183:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
13184:                 if ($usertype eq 'default') {   
13185:                     push(@{$fields{$1}},$2);
13186:                 } elsif (ref($types) eq 'ARRAY') {
13187:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
13188:                         push(@{$fields{$1}},$2);
13189:                     }
13190:                 }
13191:             }
13192:         }
13193:     }
13194:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
13195:     @lockablenames = sort(@lockablenames);
13196:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
13197:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
13198:         if (@changed) {
13199:             $changes{'lockablenames'} = 1;
13200:         }
13201:     } else {
13202:         if (@lockablenames) {
13203:             $changes{'lockablenames'} = 1;
13204:         }
13205:     }
13206:     my %updatehash = (
13207:                       autoupdate => { run => $env{'form.autoupdate_run'},
13208:                                       classlists => $env{'form.classlists'},
13209:                                       fields => {%fields},
13210:                                       lockablenames => \@lockablenames,
13211:                                     }
13212:                      );
13213:     foreach my $key (keys(%currautoupdate)) {
13214:         if (($key eq 'run') || ($key eq 'classlists')) {
13215:             if (exists($updatehash{autoupdate}{$key})) {
13216:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
13217:                     $changes{$key} = 1;
13218:                 }
13219:             }
13220:         } elsif ($key eq 'fields') {
13221:             if (ref($currautoupdate{$key}) eq 'HASH') {
13222:                 foreach my $item (@{$types},'default') {
13223:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
13224:                         my $change = 0;
13225:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
13226:                             if (!exists($fields{$item})) {
13227:                                 $change = 1;
13228:                                 last;
13229:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
13230:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
13231:                                     $change = 1;
13232:                                     last;
13233:                                 }
13234:                             }
13235:                         }
13236:                         if ($change) {
13237:                             push(@{$changes{$key}},$item);
13238:                         }
13239:                     } 
13240:                 }
13241:             }
13242:         } elsif ($key eq 'lockablenames') {
13243:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
13244:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
13245:                 if (@changed) {
13246:                     $changes{'lockablenames'} = 1;
13247:                 }
13248:             } else {
13249:                 if (@lockablenames) {
13250:                     $changes{'lockablenames'} = 1;
13251:                 }
13252:             }
13253:         }
13254:     }
13255:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
13256:         if (@lockablenames) {
13257:             $changes{'lockablenames'} = 1;
13258:         }
13259:     }
13260:     foreach my $item (@{$types},'default') {
13261:         if (defined($fields{$item})) {
13262:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
13263:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
13264:                     my $change = 0;
13265:                     if (ref($fields{$item}) eq 'ARRAY') {
13266:                         foreach my $type (@{$fields{$item}}) {
13267:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
13268:                                 $change = 1;
13269:                                 last;
13270:                             }
13271:                         }
13272:                     }
13273:                     if ($change) {
13274:                         push(@{$changes{'fields'}},$item);
13275:                     }
13276:                 } else {
13277:                     push(@{$changes{'fields'}},$item);
13278:                 }
13279:             } else {
13280:                 push(@{$changes{'fields'}},$item);
13281:             }
13282:         }
13283:     }
13284:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
13285:                                              $dom);
13286:     if ($putresult eq 'ok') {
13287:         if (keys(%changes) > 0) {
13288:             $resulttext = &mt('Changes made:').'<ul>';
13289:             foreach my $key (sort(keys(%changes))) {
13290:                 if ($key eq 'lockablenames') {
13291:                     $resulttext .= '<li>';
13292:                     if (@lockablenames) {
13293:                         $usertypes->{'default'} = $othertitle;
13294:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
13295:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
13296:                     } else {
13297:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
13298:                     }
13299:                     $resulttext .= '</li>';
13300:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
13301:                     foreach my $item (@{$changes{$key}}) {
13302:                         my @newvalues;
13303:                         foreach my $type (@{$fields{$item}}) {
13304:                             push(@newvalues,$fieldtitles{$type});
13305:                         }
13306:                         my $newvaluestr;
13307:                         if (@newvalues > 0) {
13308:                             $newvaluestr = join(', ',@newvalues);
13309:                         } else {
13310:                             $newvaluestr = &mt('none');
13311:                         }
13312:                         if ($item eq 'default') {
13313:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
13314:                         } else {
13315:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
13316:                         }
13317:                     }
13318:                 } else {
13319:                     my $newvalue;
13320:                     if ($key eq 'run') {
13321:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
13322:                     } else {
13323:                         $newvalue = $offon[$env{'form.'.$key}];
13324:                     }
13325:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
13326:                 }
13327:             }
13328:             $resulttext .= '</ul>';
13329:         } else {
13330:             $resulttext = &mt('No changes made to autoupdates');
13331:         }
13332:     } else {
13333:         $resulttext = '<span class="LC_error">'.
13334: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
13335:     }
13336:     return $resulttext;
13337: }
13338: 
13339: sub modify_autocreate {
13340:     my ($dom,%domconfig) = @_;
13341:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
13342:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
13343:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
13344:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
13345:         }
13346:     }
13347:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
13348:                  req => 'Auto-creation of validated requests for official courses',
13349:                  xmldc => 'Identity of course creator of courses from XML files',
13350:                );
13351:     my @types = ('xml','req');
13352:     foreach my $item (@types) {
13353:         $newvals{$item} = $env{'form.autocreate_'.$item};
13354:         $newvals{$item} =~ s/\D//g;
13355:         $newvals{$item} = 0 if ($newvals{$item} eq '');
13356:     }
13357:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
13358:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
13359:     unless (exists($domcoords{$newvals{'xmldc'}})) {
13360:         $newvals{'xmldc'} = '';
13361:     } 
13362:     %autocreatehash =  (
13363:                         autocreate => { xml => $newvals{'xml'},
13364:                                         req => $newvals{'req'},
13365:                                       }
13366:                        );
13367:     if ($newvals{'xmldc'} ne '') {
13368:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
13369:     }
13370:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
13371:                                              $dom);
13372:     if ($putresult eq 'ok') {
13373:         my @items = @types;
13374:         if ($newvals{'xml'}) {
13375:             push(@items,'xmldc');
13376:         }
13377:         foreach my $item (@items) {
13378:             if (exists($currautocreate{$item})) {
13379:                 if ($currautocreate{$item} ne $newvals{$item}) {
13380:                     $changes{$item} = 1;
13381:                 }
13382:             } elsif ($newvals{$item}) {
13383:                 $changes{$item} = 1;
13384:             }
13385:         }
13386:         if (keys(%changes) > 0) {
13387:             my @offon = ('off','on'); 
13388:             $resulttext = &mt('Changes made:').'<ul>';
13389:             foreach my $item (@types) {
13390:                 if ($changes{$item}) {
13391:                     my $newtxt = $offon[$newvals{$item}];
13392:                     $resulttext .= '<li>'.
13393:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
13394:                                        '<b>','</b>').
13395:                                    '</li>';
13396:                 }
13397:             }
13398:             if ($changes{'xmldc'}) {
13399:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
13400:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
13401:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
13402:             }
13403:             $resulttext .= '</ul>';
13404:         } else {
13405:             $resulttext = &mt('No changes made to auto-creation settings');
13406:         }
13407:     } else {
13408:         $resulttext = '<span class="LC_error">'.
13409:             &mt('An error occurred: [_1]',$putresult).'</span>';
13410:     }
13411:     return $resulttext;
13412: }
13413: 
13414: sub modify_directorysrch {
13415:     my ($dom,$lastactref,%domconfig) = @_;
13416:     my ($resulttext,%changes);
13417:     my %currdirsrch;
13418:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
13419:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
13420:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
13421:         }
13422:     }
13423:     my %title = ( available => 'Institutional directory search available',
13424:                   localonly => 'Other domains can search institution',
13425:                   lcavailable => 'LON-CAPA directory search available',
13426:                   lclocalonly => 'Other domains can search LON-CAPA domain',
13427:                   searchby => 'Search types',
13428:                   searchtypes => 'Search latitude');
13429:     my @offon = ('off','on');
13430:     my @otherdoms = ('Yes','No');
13431: 
13432:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
13433:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
13434:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
13435: 
13436:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13437:     if (keys(%{$usertypes}) == 0) {
13438:         @cansearch = ('default');
13439:     } else {
13440:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
13441:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
13442:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
13443:                     push(@{$changes{'cansearch'}},$type);
13444:                 }
13445:             }
13446:             foreach my $type (@cansearch) {
13447:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
13448:                     push(@{$changes{'cansearch'}},$type);
13449:                 }
13450:             }
13451:         } else {
13452:             push(@{$changes{'cansearch'}},@cansearch);
13453:         }
13454:     }
13455: 
13456:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
13457:         foreach my $by (@{$currdirsrch{'searchby'}}) {
13458:             if (!grep(/^\Q$by\E$/,@searchby)) {
13459:                 push(@{$changes{'searchby'}},$by);
13460:             }
13461:         }
13462:         foreach my $by (@searchby) {
13463:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
13464:                 push(@{$changes{'searchby'}},$by);
13465:             }
13466:         }
13467:     } else {
13468:         push(@{$changes{'searchby'}},@searchby);
13469:     }
13470: 
13471:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
13472:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
13473:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
13474:                 push(@{$changes{'searchtypes'}},$type);
13475:             }
13476:         }
13477:         foreach my $type (@searchtypes) {
13478:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
13479:                 push(@{$changes{'searchtypes'}},$type);
13480:             }
13481:         }
13482:     } else {
13483:         if (exists($currdirsrch{'searchtypes'})) {
13484:             foreach my $type (@searchtypes) {  
13485:                 if ($type ne $currdirsrch{'searchtypes'}) { 
13486:                     push(@{$changes{'searchtypes'}},$type);
13487:                 }
13488:             }
13489:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
13490:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
13491:             }   
13492:         } else {
13493:             push(@{$changes{'searchtypes'}},@searchtypes); 
13494:         }
13495:     }
13496: 
13497:     my %dirsrch_hash =  (
13498:             directorysrch => { available => $env{'form.dirsrch_available'},
13499:                                cansearch => \@cansearch,
13500:                                localonly => $env{'form.dirsrch_instlocalonly'},
13501:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
13502:                                lcavailable => $env{'form.dirsrch_domavailable'},
13503:                                searchby => \@searchby,
13504:                                searchtypes => \@searchtypes,
13505:                              }
13506:             );
13507:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
13508:                                              $dom);
13509:     if ($putresult eq 'ok') {
13510:         if (exists($currdirsrch{'available'})) {
13511:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
13512:                  $changes{'available'} = 1;
13513:              }
13514:         } else {
13515:             if ($env{'form.dirsrch_available'} eq '1') {
13516:                 $changes{'available'} = 1;
13517:             }
13518:         }
13519:         if (exists($currdirsrch{'lcavailable'})) {
13520:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
13521:                 $changes{'lcavailable'} = 1;
13522:             }
13523:         } else {
13524:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
13525:                 $changes{'lcavailable'} = 1;
13526:             }
13527:         }
13528:         if (exists($currdirsrch{'localonly'})) {
13529:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
13530:                 $changes{'localonly'} = 1;
13531:             }
13532:         } else {
13533:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
13534:                 $changes{'localonly'} = 1;
13535:             }
13536:         }
13537:         if (exists($currdirsrch{'lclocalonly'})) {
13538:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
13539:                 $changes{'lclocalonly'} = 1;
13540:             }
13541:         } else {
13542:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
13543:                 $changes{'lclocalonly'} = 1;
13544:             }
13545:         }
13546:         if (keys(%changes) > 0) {
13547:             $resulttext = &mt('Changes made:').'<ul>';
13548:             if ($changes{'available'}) {
13549:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
13550:             }
13551:             if ($changes{'lcavailable'}) {
13552:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
13553:             }
13554:             if ($changes{'localonly'}) {
13555:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
13556:             }
13557:             if ($changes{'lclocalonly'}) {
13558:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
13559:             }
13560:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
13561:                 my $chgtext;
13562:                 if (ref($usertypes) eq 'HASH') {
13563:                     if (keys(%{$usertypes}) > 0) {
13564:                         foreach my $type (@{$types}) {
13565:                             if (grep(/^\Q$type\E$/,@cansearch)) {
13566:                                 $chgtext .= $usertypes->{$type}.'; ';
13567:                             }
13568:                         }
13569:                         if (grep(/^default$/,@cansearch)) {
13570:                             $chgtext .= $othertitle;
13571:                         } else {
13572:                             $chgtext =~ s/\; $//;
13573:                         }
13574:                         $resulttext .=
13575:                             '<li>'.
13576:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
13577:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
13578:                             '</li>';
13579:                     }
13580:                 }
13581:             }
13582:             if (ref($changes{'searchby'}) eq 'ARRAY') {
13583:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
13584:                 my $chgtext;
13585:                 foreach my $type (@{$titleorder}) {
13586:                     if (grep(/^\Q$type\E$/,@searchby)) {
13587:                         if (defined($searchtitles->{$type})) {
13588:                             $chgtext .= $searchtitles->{$type}.'; ';
13589:                         }
13590:                     }
13591:                 }
13592:                 $chgtext =~ s/\; $//;
13593:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
13594:             }
13595:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
13596:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
13597:                 my $chgtext;
13598:                 foreach my $type (@{$srchtypeorder}) {
13599:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
13600:                         if (defined($srchtypes_desc->{$type})) {
13601:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
13602:                         }
13603:                     }
13604:                 }
13605:                 $chgtext =~ s/\; $//;
13606:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
13607:             }
13608:             $resulttext .= '</ul>';
13609:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
13610:             if (ref($lastactref) eq 'HASH') {
13611:                 $lastactref->{'directorysrch'} = 1;
13612:             }
13613:         } else {
13614:             $resulttext = &mt('No changes made to directory search settings');
13615:         }
13616:     } else {
13617:         $resulttext = '<span class="LC_error">'.
13618:                       &mt('An error occurred: [_1]',$putresult).'</span>';
13619:     }
13620:     return $resulttext;
13621: }
13622: 
13623: sub modify_contacts {
13624:     my ($dom,$lastactref,%domconfig) = @_;
13625:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
13626:     if (ref($domconfig{'contacts'}) eq 'HASH') {
13627:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
13628:             $currsetting{$key} = $domconfig{'contacts'}{$key};
13629:         }
13630:     }
13631:     my (%others,%to,%bcc,%includestr,%includeloc);
13632:     my @contacts = ('supportemail','adminemail');
13633:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
13634:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
13635:     my @toggles = ('reporterrors','reportupdates','reportstatus');
13636:     my @lonstatus = ('threshold','sysmail','weights','excluded');
13637:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
13638:     foreach my $type (@mailings) {
13639:         @{$newsetting{$type}} = 
13640:             &Apache::loncommon::get_env_multiple('form.'.$type);
13641:         foreach my $item (@contacts) {
13642:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
13643:                 $contacts_hash{contacts}{$type}{$item} = 1;
13644:             } else {
13645:                 $contacts_hash{contacts}{$type}{$item} = 0;
13646:             }
13647:         }
13648:         $others{$type} = $env{'form.'.$type.'_others'};
13649:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
13650:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
13651:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
13652:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
13653:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
13654:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
13655:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
13656:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
13657:             }
13658:         }
13659:     }
13660:     foreach my $item (@contacts) {
13661:         $to{$item} = $env{'form.'.$item};
13662:         $contacts_hash{'contacts'}{$item} = $to{$item};
13663:     }
13664:     foreach my $item (@toggles) {
13665:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
13666:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
13667:         }
13668:     }
13669:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
13670:     foreach my $item (@lonstatus) {
13671:         if ($item eq 'excluded') {
13672:             my (%serverhomes,@excluded);
13673:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
13674:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
13675:             if (@possexcluded) {
13676:                 foreach my $id (sort(@possexcluded)) {
13677:                     if ($serverhomes{$id}) {
13678:                         push(@excluded,$id);
13679:                     }
13680:                 }
13681:             }
13682:             if (@excluded) {
13683:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
13684:             }
13685:         } elsif ($item eq 'weights') {
13686:             foreach my $type ('E','W','N') {
13687:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
13688:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
13689:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
13690:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
13691:                             $env{'form.error'.$item.'_'.$type};
13692:                     }
13693:                 }
13694:             }
13695:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
13696:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
13697:             if ($env{'form.error'.$item} =~ /^\d+$/) {
13698:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
13699:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
13700:                 }
13701:             }
13702:         }
13703:     }
13704:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
13705:         foreach my $field (@{$fields}) {
13706:             if (ref($possoptions->{$field}) eq 'ARRAY') {
13707:                 my $value = $env{'form.helpform_'.$field};
13708:                 $value =~ s/^\s+|\s+$//g;
13709:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
13710:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
13711:                     if ($field eq 'screenshot') {
13712:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
13713:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
13714:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
13715:                         }
13716:                     }
13717:                 }
13718:             }
13719:         }
13720:     }
13721:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13722:     my (@statuses,%usertypeshash,@overrides);
13723:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
13724:         @statuses = @{$types};
13725:         if (ref($usertypes) eq 'HASH') {
13726:             %usertypeshash = %{$usertypes};
13727:         }
13728:     }
13729:     if (@statuses) {
13730:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
13731:         foreach my $type (@possoverrides) {
13732:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
13733:                 push(@overrides,$type);
13734:             }
13735:         }
13736:         if (@overrides) {
13737:             foreach my $type (@overrides) {
13738:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
13739:                 foreach my $item (@contacts) {
13740:                     if (grep(/^\Q$item\E$/,@standard)) {
13741:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
13742:                         $newsetting{'override_'.$type}{$item} = 1;
13743:                     } else {
13744:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
13745:                         $newsetting{'override_'.$type}{$item} = 0;
13746:                     }
13747:                 }
13748:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
13749:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
13750:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
13751:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
13752:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
13753:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
13754:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
13755:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
13756:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
13757:                 }
13758:             }     
13759:         }
13760:     }
13761:     if (keys(%currsetting) > 0) {
13762:         foreach my $item (@contacts) {
13763:             if ($to{$item} ne $currsetting{$item}) {
13764:                 $changes{$item} = 1;
13765:             }
13766:         }
13767:         foreach my $type (@mailings) {
13768:             foreach my $item (@contacts) {
13769:                 if (ref($currsetting{$type}) eq 'HASH') {
13770:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
13771:                         push(@{$changes{$type}},$item);
13772:                     }
13773:                 } else {
13774:                     push(@{$changes{$type}},@{$newsetting{$type}});
13775:                 }
13776:             }
13777:             if ($others{$type} ne $currsetting{$type}{'others'}) {
13778:                 push(@{$changes{$type}},'others');
13779:             }
13780:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
13781:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
13782:                     push(@{$changes{$type}},'bcc'); 
13783:                 }
13784:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
13785:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
13786:                     push(@{$changes{$type}},'include');
13787:                 }
13788:             }
13789:         }
13790:         if (ref($fields) eq 'ARRAY') {
13791:             if (ref($currsetting{'helpform'}) eq 'HASH') {
13792:                 foreach my $field (@{$fields}) {
13793:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
13794:                         push(@{$changes{'helpform'}},$field);
13795:                     }
13796:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
13797:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
13798:                             push(@{$changes{'helpform'}},'maxsize');
13799:                         }
13800:                     }
13801:                 }
13802:             } else {
13803:                 foreach my $field (@{$fields}) {
13804:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
13805:                         push(@{$changes{'helpform'}},$field);
13806:                     }
13807:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
13808:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
13809:                             push(@{$changes{'helpform'}},'maxsize');
13810:                         }
13811:                     }
13812:                 }
13813:             }
13814:         }
13815:         if (@statuses) {
13816:             if (ref($currsetting{'overrides'}) eq 'HASH') { 
13817:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
13818:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
13819:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
13820:                             foreach my $item (@contacts,'bcc','others','include') {
13821:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) { 
13822:                                     push(@{$changes{'overrides'}},$key);
13823:                                     last;
13824:                                 }
13825:                             }
13826:                         } else {
13827:                             push(@{$changes{'overrides'}},$key);
13828:                         }
13829:                     }
13830:                 }
13831:                 foreach my $key (@overrides) {
13832:                     unless (exists($currsetting{'overrides'}{$key})) {
13833:                         push(@{$changes{'overrides'}},$key);
13834:                     }
13835:                 }
13836:             } else {
13837:                 foreach my $key (@overrides) {
13838:                     push(@{$changes{'overrides'}},$key); 
13839:                 }
13840:             }
13841:         }
13842:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
13843:             foreach my $key ('excluded','weights','threshold','sysmail') {
13844:                 if ($key eq 'excluded') {
13845:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
13846:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
13847:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
13848:                             (@{$currsetting{'lonstatus'}{$key}})) {
13849:                             my @diffs =
13850:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
13851:                                                                    $currsetting{'lonstatus'}{$key});
13852:                             if (@diffs) {
13853:                                 push(@{$changes{'lonstatus'}},$key);
13854:                             }
13855:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
13856:                             push(@{$changes{'lonstatus'}},$key);
13857:                         }
13858:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
13859:                              (@{$currsetting{'lonstatus'}{$key}})) {
13860:                         push(@{$changes{'lonstatus'}},$key);
13861:                     }
13862:                 } elsif ($key eq 'weights') {
13863:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
13864:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
13865:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
13866:                             foreach my $type ('E','W','N','U') {
13867:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
13868:                                         $currsetting{'lonstatus'}{$key}{$type}) {
13869:                                     push(@{$changes{'lonstatus'}},$key);
13870:                                     last;
13871:                                 }
13872:                             }
13873:                         } else {
13874:                             foreach my $type ('E','W','N','U') {
13875:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
13876:                                     push(@{$changes{'lonstatus'}},$key);
13877:                                     last;
13878:                                 }
13879:                             }
13880:                         }
13881:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
13882:                         foreach my $type ('E','W','N','U') {
13883:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
13884:                                 push(@{$changes{'lonstatus'}},$key);
13885:                                 last;
13886:                             }
13887:                         }
13888:                     }
13889:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
13890:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
13891:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
13892:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
13893:                                 push(@{$changes{'lonstatus'}},$key);
13894:                             }
13895:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
13896:                             push(@{$changes{'lonstatus'}},$key);
13897:                         }
13898:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
13899:                         push(@{$changes{'lonstatus'}},$key);
13900:                     }
13901:                 }
13902:             }
13903:         } else {
13904:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
13905:                 foreach my $key ('excluded','weights','threshold','sysmail') {
13906:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
13907:                         push(@{$changes{'lonstatus'}},$key);
13908:                     }
13909:                 }
13910:             }
13911:         }
13912:     } else {
13913:         my %default;
13914:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
13915:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
13916:         $default{'errormail'} = 'adminemail';
13917:         $default{'packagesmail'} = 'adminemail';
13918:         $default{'helpdeskmail'} = 'supportemail';
13919:         $default{'otherdomsmail'} = 'supportemail';
13920:         $default{'lonstatusmail'} = 'adminemail';
13921:         $default{'requestsmail'} = 'adminemail';
13922:         $default{'updatesmail'} = 'adminemail';
13923:         $default{'hostipmail'} = 'adminemail';
13924:         foreach my $item (@contacts) {
13925:            if ($to{$item} ne $default{$item}) {
13926:                $changes{$item} = 1;
13927:            }
13928:         }
13929:         foreach my $type (@mailings) {
13930:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
13931:                 push(@{$changes{$type}},@{$newsetting{$type}});
13932:             }
13933:             if ($others{$type} ne '') {
13934:                 push(@{$changes{$type}},'others');
13935:             }
13936:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
13937:                 if ($bcc{$type} ne '') {
13938:                     push(@{$changes{$type}},'bcc');
13939:                 }
13940:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
13941:                     push(@{$changes{$type}},'include');
13942:                 }
13943:             }
13944:         }
13945:         if (ref($fields) eq 'ARRAY') {
13946:             foreach my $field (@{$fields}) {
13947:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
13948:                     push(@{$changes{'helpform'}},$field);
13949:                 }
13950:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
13951:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
13952:                         push(@{$changes{'helpform'}},'maxsize');
13953:                     }
13954:                 }
13955:             }
13956:         }
13957:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
13958:             foreach my $key ('excluded','weights','threshold','sysmail') {
13959:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
13960:                     push(@{$changes{'lonstatus'}},$key);
13961:                 }
13962:             }
13963:         }
13964:     }
13965:     foreach my $item (@toggles) {
13966:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
13967:             $changes{$item} = 1;
13968:         } elsif ((!$env{'form.'.$item}) &&
13969:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
13970:             $changes{$item} = 1;
13971:         }
13972:     }
13973:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
13974:                                              $dom);
13975:     if ($putresult eq 'ok') {
13976:         if (keys(%changes) > 0) {
13977:             &Apache::loncommon::devalidate_domconfig_cache($dom);
13978:             if (ref($lastactref) eq 'HASH') {
13979:                 $lastactref->{'domainconfig'} = 1;
13980:             }
13981:             my ($titles,$short_titles)  = &contact_titles();
13982:             $resulttext = &mt('Changes made:').'<ul>';
13983:             foreach my $item (@contacts) {
13984:                 if ($changes{$item}) {
13985:                     $resulttext .= '<li>'.$titles->{$item}.
13986:                                     &mt(' set to: ').
13987:                                     '<span class="LC_cusr_emph">'.
13988:                                     $to{$item}.'</span></li>';
13989:                 }
13990:             }
13991:             foreach my $type (@mailings) {
13992:                 if (ref($changes{$type}) eq 'ARRAY') {
13993:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
13994:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
13995:                     } else {
13996:                         $resulttext .= '<li>'.$titles->{$type}.': ';
13997:                     }
13998:                     my @text;
13999:                     foreach my $item (@{$newsetting{$type}}) {
14000:                         push(@text,$short_titles->{$item});
14001:                     }
14002:                     if ($others{$type} ne '') {
14003:                         push(@text,$others{$type});
14004:                     }
14005:                     if (@text) {
14006:                         $resulttext .= '<span class="LC_cusr_emph">'.
14007:                                        join(', ',@text).'</span>';
14008:                     }
14009:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
14010:                         if ($bcc{$type} ne '') {
14011:                             my $bcctext;
14012:                             if (@text) {
14013:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
14014:                             } else {
14015:                                 $bcctext = '(Bcc)';
14016:                             }
14017:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
14018:                         } elsif (!@text) {
14019:                             $resulttext .= &mt('No one');
14020:                         }   
14021:                         if ($includestr{$type} ne '') {
14022:                             if ($includeloc{$type} eq 'b') {
14023:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
14024:                             } elsif ($includeloc{$type} eq 's') {
14025:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
14026:                             }
14027:                         }
14028:                     } elsif (!@text) {
14029:                         $resulttext .= &mt('No recipients');
14030:                     }
14031:                     $resulttext .= '</li>';
14032:                 }
14033:             }
14034:             if (ref($changes{'overrides'}) eq 'ARRAY') {
14035:                 my @deletions;
14036:                 foreach my $type (@{$changes{'overrides'}}) {
14037:                     if ($usertypeshash{$type}) {
14038:                         if (grep(/^\Q$type\E/,@overrides)) {
14039:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
14040:                                                       $usertypeshash{$type}).'<ul><li>';
14041:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
14042:                                 my @text;
14043:                                 foreach my $item (@contacts) {
14044:                                     if ($newsetting{'override_'.$type}{$item}) { 
14045:                                         push(@text,$short_titles->{$item});
14046:                                     }
14047:                                 }
14048:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
14049:                                     push(@text,$newsetting{'override_'.$type}{'others'});
14050:                                 }
14051:   
14052:                                 if (@text) {
14053:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
14054:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
14055:                                 }
14056:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
14057:                                     my $bcctext;
14058:                                     if (@text) {
14059:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
14060:                                     } else {
14061:                                         $bcctext = '(Bcc)';
14062:                                     }
14063:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
14064:                                 } elsif (!@text) {
14065:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
14066:                                 }
14067:                                 $resulttext .= '</li>';
14068:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
14069:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
14070:                                     if ($loc eq 'b') {
14071:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
14072:                                     } elsif ($loc eq 's') {
14073:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
14074:                                     }
14075:                                 }
14076:                             }
14077:                             $resulttext .= '</li></ul></li>';
14078:                         } else {
14079:                             push(@deletions,$usertypeshash{$type});
14080:                         }
14081:                     }
14082:                 }
14083:                 if (@deletions) {
14084:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
14085:                                               join(', ',@deletions)).'</li>';
14086:                 }
14087:             }
14088:             my @offon = ('off','on');
14089:             my $corelink = &core_link_msu();
14090:             if ($changes{'reporterrors'}) {
14091:                 $resulttext .= '<li>'.
14092:                                &mt('E-mail error reports to [_1] set to "'.
14093:                                    $offon[$env{'form.reporterrors'}].'".',
14094:                                    $corelink).
14095:                                '</li>';
14096:             }
14097:             if ($changes{'reportupdates'}) {
14098:                 $resulttext .= '<li>'.
14099:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
14100:                                     $offon[$env{'form.reportupdates'}].'".',
14101:                                     $corelink).
14102:                                 '</li>';
14103:             }
14104:             if ($changes{'reportstatus'}) {
14105:                 $resulttext .= '<li>'.
14106:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
14107:                                     $offon[$env{'form.reportstatus'}].'".',
14108:                                     $corelink).
14109:                                 '</li>';
14110:             }
14111:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
14112:                 $resulttext .= '<li>'.
14113:                                &mt('Nightly status check e-mail settings').':<ul>';
14114:                 my (%defval,%use_def,%shown);
14115:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
14116:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
14117:                 $defval{'weights'} =
14118:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
14119:                 $defval{'excluded'} = &mt('None');
14120:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
14121:                     foreach my $item ('threshold','sysmail','weights','excluded') {
14122:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
14123:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
14124:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
14125:                             } elsif ($item eq 'weights') {
14126:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
14127:                                     foreach my $type ('E','W','N','U') {
14128:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
14129:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
14130:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
14131:                                         } else {
14132:                                             $shown{$item} .= $lonstatus_defs->{$type};
14133:                                         }
14134:                                         $shown{$item} .= ', ';
14135:                                     }
14136:                                     $shown{$item} =~ s/, $//;
14137:                                 } else {
14138:                                     $shown{$item} = $defval{$item};
14139:                                 }
14140:                             } elsif ($item eq 'excluded') {
14141:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
14142:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
14143:                                 } else {
14144:                                     $shown{$item} = $defval{$item};
14145:                                 }
14146:                             }
14147:                         } else {
14148:                             $shown{$item} = $defval{$item};
14149:                         }
14150:                     }
14151:                 } else {
14152:                     foreach my $item ('threshold','weights','excluded','sysmail') {
14153:                         $shown{$item} = $defval{$item};
14154:                     }
14155:                 }
14156:                 foreach my $item ('threshold','weights','excluded','sysmail') {
14157:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
14158:                                           $shown{$item}).'</li>';
14159:                 }
14160:                 $resulttext .= '</ul></li>';
14161:             }
14162:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
14163:                 my (@optional,@required,@unused,$maxsizechg);
14164:                 foreach my $field (@{$changes{'helpform'}}) {
14165:                     if ($field eq 'maxsize') {
14166:                         $maxsizechg = 1;
14167:                         next;
14168:                     }
14169:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
14170:                         push(@optional,$field);
14171:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
14172:                         push(@unused,$field);
14173:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
14174:                         push(@required,$field);
14175:                     }
14176:                 }
14177:                 if (@optional) {
14178:                     $resulttext .= '<li>'.
14179:                                    &mt('Help form fields changed to "Optional": [_1].',
14180:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
14181:                                    '</li>';
14182:                 }
14183:                 if (@required) {
14184:                     $resulttext .= '<li>'.
14185:                                    &mt('Help form fields changed to "Required": [_1].',
14186:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
14187:                                    '</li>';
14188:                 }
14189:                 if (@unused) {
14190:                     $resulttext .= '<li>'.
14191:                                    &mt('Help form fields changed to "Not shown": [_1].',
14192:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
14193:                                    '</li>';
14194:                 }
14195:                 if ($maxsizechg) {
14196:                     $resulttext .= '<li>'.
14197:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
14198:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
14199:                                    '</li>';
14200:                 }
14201:             }
14202:             $resulttext .= '</ul>';
14203:         } else {
14204:             $resulttext = &mt('No changes made to contacts and form settings');
14205:         }
14206:     } else {
14207:         $resulttext = '<span class="LC_error">'.
14208:             &mt('An error occurred: [_1].',$putresult).'</span>';
14209:     }
14210:     return $resulttext;
14211: }
14212: 
14213: sub modify_privacy {
14214:     my ($dom,%domconfig) = @_;
14215:     my ($resulttext,%current,%changes);
14216:     if (ref($domconfig{'privacy'}) eq 'HASH') {
14217:         %current = %{$domconfig{'privacy'}};
14218:     }
14219:     my @fields = ('lastname','firstname','middlename','generation','permanentemail','id');
14220:     my @items = ('domain','author','course','community');
14221:     my %names = &Apache::lonlocal::texthash (
14222:                    domain => 'Assigned domain role(s)',
14223:                    author => 'Assigned co-author role(s)',
14224:                    course => 'Assigned course role(s)',
14225:                    community => 'Assigned community role',
14226:                 );
14227:     my %roles = &Apache::lonlocal::texthash (
14228:                    domain => 'Domain role',
14229:                    author => 'Co-author role',
14230:                    course => 'Course role',
14231:                    community => 'Community role',
14232:                 );
14233:     my %titles = &Apache::lonlocal::texthash (
14234:                   approval => 'Approval for role in different domain',
14235:                   othdom   => 'User information available in other domain',
14236:                   priv     => 'Information viewable by privileged user in same domain',
14237:                   unpriv   => 'Information viewable by unprivileged user in same domain',
14238:                   instdom  => 'Other domain shares institution/provider',
14239:                   extdom   => 'Other domain has different institution/provider',
14240:                   none     => 'Not allowed',
14241:                   user     => 'User authorizes',
14242:                   domain   => 'Domain Coordinator authorizes',
14243:                   auto     => 'Unrestricted',
14244:     );
14245:     my %fieldnames = &Apache::lonlocal::texthash (
14246:                         id => 'Student/Employee ID',
14247:                         permanentemail => 'E-mail address',
14248:                         lastname => 'Last Name',
14249:                         firstname => 'First Name',
14250:                         middlename => 'Middle Name',
14251:                         generation => 'Generation',
14252:     );
14253:     my ($othertitle,$usertypes,$types) =
14254:         &Apache::loncommon::sorted_inst_types($dom);
14255:     my (%by_ip,%by_location,@intdoms,@instdoms);
14256:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
14257: 
14258:     my %privacyhash = (
14259:                        'approval' => {
14260:                                        instdom => {},
14261:                                        extdom  => {},
14262:                                      },
14263:                        'othdom'   => {},
14264:                        'priv'     => {},
14265:                        'unpriv'   => {},
14266:                       );
14267:     foreach my $item (@items) {
14268:         if (@instdoms > 1) {
14269:             if ($env{'form.privacy_approval_instdom'.$item} =~ /^(none|user|domain|auto)$/) {
14270:                 $privacyhash{'approval'}{'instdom'}{$item} = $env{'form.privacy_approval_instdom_'.$item};
14271:             }
14272:             if (ref($current{'approval'}) eq 'HASH') {
14273:                 if (ref($current{'approval'}{'instdom'}) eq 'HASH') {
14274:                     unless ($privacyhash{'approval'}{'instdom'}{$item} eq $current{'approval'}{'instdom'}{$item}) {
14275:                         $changes{'approval'} = 1;
14276:                     }
14277:                 }
14278:             } elsif ($privacyhash{'approval'}{'instdom'}{$item} ne 'auto') {
14279:                 $changes{'approval'} = 1;
14280:             }
14281:         }
14282:         if (keys(%by_location) > 0) {
14283:             if ($env{'form.privacy_approval_extdom_'.$item} =~ /^(none|user|domain|auto)$/) {
14284:                 $privacyhash{'approval'}{'extdom'}{$item} = $env{'form.privacy_approval_extdom_'.$item};
14285:             }
14286:             if (ref($current{'approval'}) eq 'HASH') {
14287:                 if (ref($current{'approval'}{'extdom'}) eq 'HASH') {
14288:                     unless ($privacyhash{'approval'}{'extdom'}{$item} eq $current{'approval'}{'extdom'}{$item}) {
14289:                         $changes{'approval'} = 1;
14290:                     }
14291:                 }
14292:             } elsif ($privacyhash{'approval'}{'extdom'}{$item} ne 'auto') {
14293:                 $changes{'approval'} = 1;
14294:             }
14295:         }
14296:         foreach my $status ('priv','unpriv') {
14297:             my @possibles = sort(&Apache::loncommon::get_env_multiple('form.privacy_'.$status.'_'.$item));
14298:             my @newvalues;
14299:             foreach my $field (@possibles) {
14300:                 if (grep(/^\Q$field\E$/,@fields)) {
14301:                     $privacyhash{$status}{$item}{$field} = 1;
14302:                     push(@newvalues,$field);
14303:                 }
14304:             }
14305:             @newvalues = sort(@newvalues);
14306:             if (ref($current{$status}) eq 'HASH') {
14307:                 if (ref($current{$status}{$item}) eq 'HASH') {
14308:                     my @currvalues = sort(keys(%{$current{$status}{$item}}));
14309:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
14310:                     if (@diffs > 0) {
14311:                         $changes{$status} = 1;
14312:                     }
14313:                 }
14314:             } else {
14315:                 my @stdfields;
14316:                 foreach my $field (@fields) {
14317:                     if ($field eq 'id') {
14318:                         next if ($status eq 'unpriv');
14319:                         next if (($status eq 'priv') && ($item eq 'community'));
14320:                     }
14321:                     push(@stdfields,$field);
14322:                 }
14323:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
14324:                 if (@diffs > 0) {
14325:                     $changes{$status} = 1;
14326:                 }
14327:             }
14328:         }
14329:     }
14330:     if ((@instdoms > 1) || (keys(%by_location) > 0)) {
14331:         my @statuses;
14332:         if (ref($types) eq 'ARRAY') {
14333:             @statuses = @{$types};
14334:         }
14335:         foreach my $type (@statuses,'default') {
14336:             my @possfields = &Apache::loncommon::get_env_multiple('form.privacy_othdom_'.$type);
14337:             my @newvalues;
14338:             foreach my $field (sort(@possfields)) {
14339:                 if (grep(/^\Q$field\E$/,@fields)) {
14340:                     $privacyhash{'othdom'}{$type}{$field} = 1;
14341:                     push(@newvalues,$field);
14342:                 }
14343:             }
14344:             @newvalues = sort(@newvalues);
14345:             if (ref($current{'othdom'}) eq 'HASH') {
14346:                 if (ref($current{'othdom'}{$type}) eq 'HASH') {
14347:                     my @currvalues = sort(keys(%{$current{'othdom'}{$type}}));
14348:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
14349:                     if (@diffs > 0) {
14350:                         $changes{'othdom'} = 1;
14351:                     }
14352:                 }
14353:             } else {
14354:                 my @stdfields = ('lastname','firstname','middlename','generation','permanentemail');
14355:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
14356:                 if (@diffs > 0) {
14357:                     $changes{'othdom'} = 1;
14358:                 }
14359:             }
14360:         }
14361:     }
14362:     my %confighash = (
14363:                         privacy => \%privacyhash,
14364:                      );
14365:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
14366:     if ($putresult eq 'ok') {
14367:         if (keys(%changes) > 0) {
14368:             $resulttext = &mt('Changes made: ').'<ul>';
14369:             foreach my $key ('approval','othdom','priv','unpriv') {
14370:                 if ($changes{$key}) {
14371:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
14372:                     if ($key eq 'approval') {
14373:                         if (keys(%{$privacyhash{$key}{instdom}})) {
14374:                             $resulttext .= '<li>'.$titles{'instdom'}.'<ul>';
14375:                             foreach my $item (@items) {
14376:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{instdom}{$item}}.'</li>';
14377:                             }
14378:                             $resulttext .= '</ul></li>';
14379:                         }
14380:                         if (keys(%{$privacyhash{$key}{extdom}})) {
14381:                             $resulttext .= '<li>'.$titles{'extdom'}.'<ul>';
14382:                             foreach my $item (@items) {
14383:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{extdom}{$item}}.'</li>';
14384:                             }
14385:                             $resulttext .= '</ul></li>';
14386:                         }
14387:                     } elsif ($key eq 'othdom') {
14388:                         my @statuses;
14389:                         if (ref($types) eq 'ARRAY') {
14390:                             @statuses = @{$types};
14391:                         }
14392:                         if (ref($privacyhash{$key}) eq 'HASH') {
14393:                             foreach my $status (@statuses,'default') {
14394:                                 if ($status eq 'default') {
14395:                                     $resulttext .= '<li>'.$othertitle.': ';
14396:                                 } elsif (ref($usertypes) eq 'HASH') {
14397:                                     $resulttext .= '<li>'.$usertypes->{$status}.': ';
14398:                                 } else {
14399:                                     next;
14400:                                 }
14401:                                 if (ref($privacyhash{$key}{$status}) eq 'HASH') {
14402:                                     if (keys(%{$privacyhash{$key}{$status}})) {
14403:                                         $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$status}}))));
14404:                                     } else {
14405:                                         $resulttext .= &mt('none');
14406:                                     }
14407:                                 }
14408:                                 $resulttext .= '</li>';
14409:                             }
14410:                         }
14411:                     } else {
14412:                         foreach my $item (@items) {
14413:                             if (ref($privacyhash{$key}{$item}) eq 'HASH') {
14414:                                 $resulttext .= '<li>'.$names{$item}.': ';
14415:                                 if (keys(%{$privacyhash{$key}{$item}})) {
14416:                                     $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$item}}))));
14417:                                 } else {
14418:                                     $resulttext .= &mt('none');
14419:                                 }
14420:                                 $resulttext .= '</li>';
14421:                             }
14422:                         }
14423:                     }
14424:                     $resulttext .= '</ul></li>';
14425:                 }
14426:             }
14427:         } else {
14428:             $resulttext = &mt('No changes made to user information settings');
14429:         }
14430:     } else {
14431:         $resulttext = '<span class="LC_error">'.
14432:             &mt('An error occurred: [_1]',$putresult).'</span>';
14433:     }
14434:     return $resulttext;
14435: }
14436: 
14437: sub modify_passwords {
14438:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
14439:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
14440:         $updatedefaults,$updateconf);
14441:     my $customfn = 'resetpw.html';
14442:     if (ref($domconfig{'passwords'}) eq 'HASH') {
14443:         %current = %{$domconfig{'passwords'}};
14444:     }
14445:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14446:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
14447:     if (ref($types) eq 'ARRAY') {
14448:         @oktypes = @{$types};
14449:     }
14450:     push(@oktypes,'default');
14451: 
14452:     my %titles = &Apache::lonlocal::texthash (
14453:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
14454:         intauth_check  => 'Check bcrypt cost if authenticated',
14455:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
14456:         permanent      => 'Permanent e-mail address',
14457:         critical       => 'Critical notification address',
14458:         notify         => 'Notification address',
14459:         min            => 'Minimum password length',
14460:         max            => 'Maximum password length',
14461:         chars          => 'Required characters',
14462:         expire         => 'Password expiration (days)',
14463:         numsaved       => 'Number of previous passwords to save',
14464:         reset          => 'Resetting Forgotten Password',
14465:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
14466:         rules          => 'Rules for LON-CAPA Passwords',
14467:         crsownerchg    => 'Course Owner Changing Student Passwords',
14468:         username       => 'Username',
14469:         email          => 'E-mail address',
14470:     );
14471: 
14472: #
14473: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
14474: #
14475:     my (%curr_defaults,%save_defaults);
14476:     if (ref($domconfig{'defaults'}) eq 'HASH') {
14477:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
14478:             if ($key =~ /^intauth_(cost|check|switch)$/) {
14479:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
14480:             } else {
14481:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
14482:             }
14483:         }
14484:     }
14485:     my %staticdefaults = (
14486:         'resetlink'      => 2,
14487:         'resetcase'      => \@oktypes,
14488:         'resetprelink'   => 'both',
14489:         'resetemail'     => ['critical','notify','permanent'],
14490:         'intauth_cost'   => 10,
14491:         'intauth_check'  => 0,
14492:         'intauth_switch' => 0,
14493:         'min'            => 7,
14494:     );
14495:     foreach my $type (@oktypes) {
14496:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
14497:     }
14498:     my $linklife = $env{'form.passwords_link'};
14499:     $linklife =~ s/^\s+|\s+$//g;
14500:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
14501:         $newvalues{'resetlink'} = $linklife;
14502:         if ($current{'resetlink'}) {
14503:             if ($current{'resetlink'} ne $linklife) {
14504:                 $changes{'reset'} = 1;
14505:             }
14506:         } elsif (!exists($domconfig{passwords})) {
14507:             if ($staticdefaults{'resetlink'} ne $linklife) {
14508:                 $changes{'reset'} = 1;
14509:             }
14510:         }
14511:     } elsif ($current{'resetlink'}) {
14512:         $changes{'reset'} = 1;
14513:     }
14514:     my @casesens;
14515:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
14516:     foreach my $case (sort(@posscase)) {
14517:         if (grep(/^\Q$case\E$/,@oktypes)) {
14518:             push(@casesens,$case);
14519:         }
14520:     }
14521:     $newvalues{'resetcase'} = \@casesens;
14522:     if (ref($current{'resetcase'}) eq 'ARRAY') {
14523:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
14524:         if (@diffs > 0) {
14525:             $changes{'reset'} = 1;
14526:         }
14527:     } elsif (!exists($domconfig{passwords})) {
14528:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
14529:         if (@diffs > 0) {
14530:             $changes{'reset'} = 1;
14531:         }
14532:     }
14533:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
14534:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
14535:         if (exists($current{'resetprelink'})) {
14536:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
14537:                 $changes{'reset'} = 1;
14538:             }
14539:         } elsif (!exists($domconfig{passwords})) {
14540:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
14541:                 $changes{'reset'} = 1;
14542:             }
14543:         }
14544:     } elsif ($current{'resetprelink'}) {
14545:         $changes{'reset'} = 1;
14546:     }
14547:     foreach my $type (@oktypes) {
14548:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
14549:         my @postlink;
14550:         foreach my $item (sort(@possplink)) {
14551:             if ($item =~ /^(email|username)$/) {
14552:                 push(@postlink,$item);
14553:             }
14554:         }
14555:         $newvalues{'resetpostlink'}{$type} = \@postlink;
14556:         unless ($changes{'reset'}) {
14557:             if (ref($current{'resetpostlink'}) eq 'HASH') {
14558:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
14559:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
14560:                     if (@diffs > 0) {
14561:                         $changes{'reset'} = 1;
14562:                     }
14563:                 } else {
14564:                     $changes{'reset'} = 1;
14565:                 }
14566:             } elsif (!exists($domconfig{passwords})) {
14567:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
14568:                 if (@diffs > 0) {
14569:                     $changes{'reset'} = 1;
14570:                 }
14571:             }
14572:         }
14573:     }
14574:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
14575:     my @resetemail;
14576:     foreach my $item (sort(@possemailsrc)) {
14577:         if ($item =~ /^(permanent|critical|notify)$/) {
14578:             push(@resetemail,$item);
14579:         }
14580:     }
14581:     $newvalues{'resetemail'} = \@resetemail;
14582:     unless ($changes{'reset'}) {
14583:         if (ref($current{'resetemail'}) eq 'ARRAY') {
14584:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
14585:             if (@diffs > 0) {
14586:                 $changes{'reset'} = 1;
14587:             }
14588:         } elsif (!exists($domconfig{passwords})) {
14589:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
14590:             if (@diffs > 0) {
14591:                 $changes{'reset'} = 1;
14592:             }
14593:         }
14594:     }
14595:     if ($env{'form.passwords_stdtext'} == 0) {
14596:         $newvalues{'resetremove'} = 1;
14597:         unless ($current{'resetremove'}) {
14598:             $changes{'reset'} = 1;
14599:         }
14600:     } elsif ($current{'resetremove'}) {
14601:         $changes{'reset'} = 1;
14602:     }
14603:     if ($env{'form.passwords_customfile.filename'} ne '') {
14604:         my $servadm = $r->dir_config('lonAdmEMail');
14605:         my ($configuserok,$author_ok,$switchserver) =
14606:             &config_check($dom,$confname,$servadm);
14607:         my $error;
14608:         if ($configuserok eq 'ok') {
14609:             if ($switchserver) {
14610:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
14611:             } else {
14612:                 if ($author_ok eq 'ok') {
14613:                     my ($result,$customurl) =
14614:                         &publishlogo($r,'upload','passwords_customfile',$dom,
14615:                                      $confname,'customtext/resetpw','','',$customfn);
14616:                     if ($result eq 'ok') {
14617:                         $newvalues{'resetcustom'} = $customurl;
14618:                         $changes{'reset'} = 1;
14619:                     } else {
14620:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
14621:                     }
14622:                 } else {
14623:                     $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);
14624:                 }
14625:             }
14626:         } else {
14627:             $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);
14628:         }
14629:         if ($error) {
14630:             &Apache::lonnet::logthis($error);
14631:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14632:         }
14633:     } elsif ($current{'resetcustom'}) {
14634:         if ($env{'form.passwords_custom_del'}) {
14635:             $changes{'reset'} = 1;
14636:         } else {
14637:             $newvalues{'resetcustom'} = $current{'resetcustom'};
14638:         }
14639:     }
14640:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
14641:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
14642:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
14643:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
14644:             $changes{'intauth'} = 1;
14645:         }
14646:     } else {
14647:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
14648:     }
14649:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
14650:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
14651:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
14652:             $changes{'intauth'} = 1;
14653:         }
14654:     } else {
14655:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
14656:     }
14657:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
14658:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
14659:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
14660:             $changes{'intauth'} = 1;
14661:         }
14662:     } else {
14663:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
14664:     }
14665:     foreach my $item ('cost','check','switch') {
14666:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
14667:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
14668:             $updatedefaults = 1;
14669:         }
14670:     }
14671:     foreach my $rule ('min','max','expire','numsaved') {
14672:         $env{'form.passwords_'.$rule} =~ s/^\s+|\s+$//g;
14673:         my $ruleok;
14674:         if ($rule eq 'expire') {
14675:             if ($env{'form.passwords_'.$rule} =~ /^\d+(|\.\d*)$/) {
14676:                 $ruleok = 1;
14677:             }
14678:         } elsif ($env{'form.passwords_'.$rule} =~ /^\d+$/) {
14679:             $ruleok = 1;
14680:         }
14681:         if ($ruleok) {
14682:             $newvalues{$rule} = $env{'form.passwords_'.$rule};
14683:             if (exists($current{$rule})) {
14684:                 if ($newvalues{$rule} ne $current{$rule}) {
14685:                     $changes{'rules'} = 1;
14686:                 }
14687:             } elsif ($rule eq 'min') {
14688:                 if ($staticdefaults{$rule} ne $newvalues{$rule}) {
14689:                     $changes{'rules'} = 1;
14690:                 }
14691:             }
14692:         } elsif (exists($current{$rule})) {
14693:             $changes{'rules'} = 1;
14694:         }
14695:     }
14696:     my @posschars = &Apache::loncommon::get_env_multiple('form.passwords_chars');
14697:     my @chars;
14698:     foreach my $item (sort(@posschars)) {
14699:         if ($item =~ /^(uc|lc|num|spec)$/) {
14700:             push(@chars,$item);
14701:         }
14702:     }
14703:     $newvalues{'chars'} = \@chars;
14704:     unless ($changes{'rules'}) {
14705:         if (ref($current{'chars'}) eq 'ARRAY') {
14706:             my @diffs = &Apache::loncommon::compare_arrays($current{'chars'},\@chars);
14707:             if (@diffs > 0) {
14708:                 $changes{'rules'} = 1;
14709:             }
14710:         } else {
14711:             if (@chars > 0) {
14712:                 $changes{'rules'} = 1;
14713:             }
14714:         }
14715:     }
14716:     my %crsownerchg = (
14717:                         by => [],
14718:                         for => [],
14719:                       );
14720:     foreach my $item ('by','for') {
14721:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
14722:         foreach my $type (sort(@posstypes)) {
14723:             if (grep(/^\Q$type\E$/,@oktypes)) {
14724:                 push(@{$crsownerchg{$item}},$type);
14725:             }
14726:         }
14727:     }
14728:     $newvalues{'crsownerchg'} = \%crsownerchg;
14729:     if (ref($current{'crsownerchg'}) eq 'HASH') {
14730:         foreach my $item ('by','for') {
14731:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
14732:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
14733:                 if (@diffs > 0) {
14734:                     $changes{'crsownerchg'} = 1;
14735:                     last;
14736:                 }
14737:             }
14738:         }
14739:     } elsif (!exists($domconfig{passwords})) {
14740:         foreach my $item ('by','for') {
14741:             if (@{$crsownerchg{$item}} > 0) {
14742:                 $changes{'crsownerchg'} = 1;
14743:                 last;
14744:             }
14745:         }
14746:     }
14747: 
14748:     my %confighash = (
14749:                         defaults  => \%save_defaults,
14750:                         passwords => \%newvalues,
14751:                      );
14752:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
14753: 
14754:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
14755:     if ($putresult eq 'ok') {
14756:         if (keys(%changes) > 0) {
14757:             $resulttext = &mt('Changes made: ').'<ul>';
14758:             foreach my $key ('reset','intauth','rules','crsownerchg') {
14759:                 if ($changes{$key}) {
14760:                     unless ($key eq 'intauth') {
14761:                         $updateconf = 1;
14762:                     }
14763:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
14764:                     if ($key eq 'reset') {
14765:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
14766:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
14767:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
14768:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
14769:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />'.
14770:                                            &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchapub'}).'</br>'.
14771:                                            &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchapriv'}).'</li>';
14772:                         } else {
14773:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
14774:                         }
14775:                         if ($confighash{'passwords'}{'resetlink'}) {
14776:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
14777:                         } else {
14778:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
14779:                                                   &mt('Will default to 2 hours').'</li>';
14780:                         }
14781:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
14782:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
14783:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
14784:                             } else {
14785:                                 my $casesens;
14786:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
14787:                                     if ($type eq 'default') {
14788:                                         $casesens .= $othertitle.', ';
14789:                                     } elsif ($usertypes->{$type} ne '') {
14790:                                         $casesens .= $usertypes->{$type}.', ';
14791:                                     }
14792:                                 }
14793:                                 $casesens =~ s/\Q, \E$//;
14794:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
14795:                             }
14796:                         } else {
14797:                             $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>';
14798:                         }
14799:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
14800:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
14801:                         } else {
14802:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
14803:                         }
14804:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
14805:                             my $output;
14806:                             if (ref($types) eq 'ARRAY') {
14807:                                 foreach my $type (@{$types}) {
14808:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
14809:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
14810:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
14811:                                         } else {
14812:                                             $output .= $usertypes->{$type}.' -- '.
14813:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
14814:                                         }
14815:                                     }
14816:                                 }
14817:                             }
14818:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
14819:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
14820:                                     $output .= $othertitle.' -- '.&mt('none');
14821:                                 } else {
14822:                                     $output .= $othertitle.' -- '.
14823:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
14824:                                 }
14825:                             }
14826:                             if ($output) {
14827:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
14828:                             } else {
14829:                                 $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>';
14830:                             }
14831:                         } else {
14832:                             $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>';
14833:                         }
14834:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
14835:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
14836:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
14837:                             } else {
14838:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
14839:                             }
14840:                         } else {
14841:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA usedfor verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
14842:                         }
14843:                         if ($confighash{'passwords'}{'resetremove'}) {
14844:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
14845:                         } else {
14846:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
14847:                         }
14848:                         if ($confighash{'passwords'}{'resetcustom'}) {
14849:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
14850:                                                                             $titles{custom},600,500);
14851:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes [_1]',$customlink).'</li>';
14852:                         } else {
14853:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
14854:                         }
14855:                     } elsif ($key eq 'intauth') {
14856:                         foreach my $item ('cost','switch','check') {
14857:                             my $value = $save_defaults{$key.'_'.$item};
14858:                             if ($item eq 'switch') {
14859:                                 my %optiondesc = &Apache::lonlocal::texthash (
14860:                                                      0 => 'No',
14861:                                                      1 => 'Yes',
14862:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
14863:                                                  );
14864:                                 if ($value =~ /^(0|1|2)$/) {
14865:                                     $value = $optiondesc{$value};
14866:                                 } else {
14867:                                     $value = &mt('none -- defaults to No');
14868:                                 }
14869:                             } elsif ($item eq 'check') {
14870:                                 my %optiondesc = &Apache::lonlocal::texthash (
14871:                                                      0 => 'No',
14872:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
14873:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
14874:                                                  );
14875:                                 if ($value =~ /^(0|1|2)$/) {
14876:                                     $value = $optiondesc{$value};
14877:                                 } else {
14878:                                     $value = &mt('none -- defaults to No');
14879:                                 }
14880:                             }
14881:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
14882:                         }
14883:                     } elsif ($key eq 'rules') {
14884:                         foreach my $rule ('min','max','expire','numsaved') {
14885:                             if ($confighash{'passwords'}{$rule} eq '') {
14886:                                 if ($rule eq 'min') {
14887:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
14888:                                                    ' '.&mt('Default of 7 will be used').'</li>';
14889:                                 } else {
14890:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
14891:                                 }
14892:                             } else {
14893:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
14894:                             }
14895:                         }
14896:                     } elsif ($key eq 'crsownerchg') {
14897:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
14898:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
14899:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
14900:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
14901:                             } else {
14902:                                 my %crsownerstr;
14903:                                 foreach my $item ('by','for') {
14904:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
14905:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
14906:                                             if ($type eq 'default') {
14907:                                                 $crsownerstr{$item} .= $othertitle.', ';
14908:                                             } elsif ($usertypes->{$type} ne '') {
14909:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
14910:                                             }
14911:                                         }
14912:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
14913:                                     }
14914:                                 }
14915:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
14916:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
14917:                             }
14918:                         } else {
14919:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
14920:                         }
14921:                     }
14922:                     $resulttext .= '</ul></li>';
14923:                 }
14924:             }
14925:             $resulttext .= '</ul>';
14926:         } else {
14927:             $resulttext = &mt('No changes made to password settings');
14928:         }
14929:         my $cachetime = 24*60*60;
14930:         if ($updatedefaults) {
14931:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14932:             if (ref($lastactref) eq 'HASH') {
14933:                 $lastactref->{'domdefaults'} = 1;
14934:             }
14935:         }
14936:         if ($updateconf) {
14937:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
14938:             if (ref($lastactref) eq 'HASH') {
14939:                 $lastactref->{'passwdconf'} = 1;
14940:             }
14941:         }
14942:     } else {
14943:         $resulttext = '<span class="LC_error">'.
14944:             &mt('An error occurred: [_1]',$putresult).'</span>';
14945:     }
14946:     if ($errors) {
14947:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
14948:                        $errors.'</ul></p>';
14949:     }
14950:     return $resulttext;
14951: }
14952: 
14953: sub modify_usercreation {
14954:     my ($dom,%domconfig) = @_;
14955:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
14956:     my $warningmsg;
14957:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
14958:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
14959:             if ($key eq 'cancreate') {
14960:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
14961:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
14962:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
14963:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
14964:                         } else {
14965:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
14966:                         }
14967:                     }
14968:                 }
14969:             } elsif ($key eq 'email_rule') {
14970:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
14971:             } else {
14972:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
14973:             }
14974:         }
14975:     }
14976:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
14977:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
14978:     my @contexts = ('author','course','requestcrs');
14979:     foreach my $item(@contexts) {
14980:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
14981:     }
14982:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
14983:         foreach my $item (@contexts) {
14984:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
14985:                 push(@{$changes{'cancreate'}},$item);
14986:             }
14987:         }
14988:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
14989:         foreach my $item (@contexts) {
14990:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
14991:                 if ($cancreate{$item} ne 'any') {
14992:                     push(@{$changes{'cancreate'}},$item);
14993:                 }
14994:             } else {
14995:                 if ($cancreate{$item} ne 'none') {
14996:                     push(@{$changes{'cancreate'}},$item);
14997:                 }
14998:             }
14999:         }
15000:     } else {
15001:         foreach my $item (@contexts)  {
15002:             push(@{$changes{'cancreate'}},$item);
15003:         }
15004:     }
15005: 
15006:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
15007:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
15008:             if (!grep(/^\Q$type\E$/,@username_rule)) {
15009:                 push(@{$changes{'username_rule'}},$type);
15010:             }
15011:         }
15012:         foreach my $type (@username_rule) {
15013:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
15014:                 push(@{$changes{'username_rule'}},$type);
15015:             }
15016:         }
15017:     } else {
15018:         push(@{$changes{'username_rule'}},@username_rule);
15019:     }
15020: 
15021:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
15022:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
15023:             if (!grep(/^\Q$type\E$/,@id_rule)) {
15024:                 push(@{$changes{'id_rule'}},$type);
15025:             }
15026:         }
15027:         foreach my $type (@id_rule) {
15028:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
15029:                 push(@{$changes{'id_rule'}},$type);
15030:             }
15031:         }
15032:     } else {
15033:         push(@{$changes{'id_rule'}},@id_rule);
15034:     }
15035: 
15036:     my @authen_contexts = ('author','course','domain');
15037:     my @authtypes = ('int','krb4','krb5','loc','lti');
15038:     my %authhash;
15039:     foreach my $item (@authen_contexts) {
15040:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
15041:         foreach my $auth (@authtypes) {
15042:             if (grep(/^\Q$auth\E$/,@authallowed)) {
15043:                 $authhash{$item}{$auth} = 1;
15044:             } else {
15045:                 $authhash{$item}{$auth} = 0;
15046:             }
15047:         }
15048:     }
15049:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
15050:         foreach my $item (@authen_contexts) {
15051:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
15052:                 foreach my $auth (@authtypes) {
15053:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
15054:                         push(@{$changes{'authtypes'}},$item);
15055:                         last;
15056:                     }
15057:                 }
15058:             }
15059:         }
15060:     } else {
15061:         foreach my $item (@authen_contexts) {
15062:             push(@{$changes{'authtypes'}},$item);
15063:         }
15064:     }
15065: 
15066:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
15067:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
15068:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
15069:     $save_usercreate{'id_rule'} = \@id_rule;
15070:     $save_usercreate{'username_rule'} = \@username_rule,
15071:     $save_usercreate{'authtypes'} = \%authhash;
15072: 
15073:     my %usercreation_hash =  (
15074:         usercreation     => \%save_usercreate,
15075:     );
15076: 
15077:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
15078:                                              $dom);
15079: 
15080:     if ($putresult eq 'ok') {
15081:         if (keys(%changes) > 0) {
15082:             $resulttext = &mt('Changes made:').'<ul>';
15083:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
15084:                 my %lt = &usercreation_types();
15085:                 foreach my $type (@{$changes{'cancreate'}}) {
15086:                     my $chgtext = $lt{$type}.', ';
15087:                     if ($cancreate{$type} eq 'none') {
15088:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
15089:                     } elsif ($cancreate{$type} eq 'any') {
15090:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
15091:                     } elsif ($cancreate{$type} eq 'official') {
15092:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
15093:                     } elsif ($cancreate{$type} eq 'unofficial') {
15094:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
15095:                     }
15096:                     $resulttext .= '<li>'.$chgtext.'</li>';
15097:                 }
15098:             }
15099:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
15100:                 my ($rules,$ruleorder) = 
15101:                     &Apache::lonnet::inst_userrules($dom,'username');
15102:                 my $chgtext = '<ul>';
15103:                 foreach my $type (@username_rule) {
15104:                     if (ref($rules->{$type}) eq 'HASH') {
15105:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
15106:                     }
15107:                 }
15108:                 $chgtext .= '</ul>';
15109:                 if (@username_rule > 0) {
15110:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
15111:                 } else {
15112:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
15113:                 }
15114:             }
15115:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
15116:                 my ($idrules,$idruleorder) = 
15117:                     &Apache::lonnet::inst_userrules($dom,'id');
15118:                 my $chgtext = '<ul>';
15119:                 foreach my $type (@id_rule) {
15120:                     if (ref($idrules->{$type}) eq 'HASH') {
15121:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
15122:                     }
15123:                 }
15124:                 $chgtext .= '</ul>';
15125:                 if (@id_rule > 0) {
15126:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
15127:                 } else {
15128:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
15129:                 }
15130:             }
15131:             my %authname = &authtype_names();
15132:             my %context_title = &context_names();
15133:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
15134:                 my $chgtext = '<ul>';
15135:                 foreach my $type (@{$changes{'authtypes'}}) {
15136:                     my @allowed;
15137:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
15138:                     foreach my $auth (@authtypes) {
15139:                         if ($authhash{$type}{$auth}) {
15140:                             push(@allowed,$authname{$auth});
15141:                         }
15142:                     }
15143:                     if (@allowed > 0) {
15144:                         $chgtext .= join(', ',@allowed).'</li>';
15145:                     } else {
15146:                         $chgtext .= &mt('none').'</li>';
15147:                     }
15148:                 }
15149:                 $chgtext .= '</ul>';
15150:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
15151:                 $resulttext .= '</li>';
15152:             }
15153:             $resulttext .= '</ul>';
15154:         } else {
15155:             $resulttext = &mt('No changes made to user creation settings');
15156:         }
15157:     } else {
15158:         $resulttext = '<span class="LC_error">'.
15159:             &mt('An error occurred: [_1]',$putresult).'</span>';
15160:     }
15161:     if ($warningmsg ne '') {
15162:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
15163:     }
15164:     return $resulttext;
15165: }
15166: 
15167: sub modify_selfcreation {
15168:     my ($dom,$lastactref,%domconfig) = @_;
15169:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
15170:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
15171:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15172:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
15173:     if (ref($typesref) eq 'ARRAY') {
15174:         @types = @{$typesref};
15175:     }
15176:     if (ref($usertypesref) eq 'HASH') {
15177:         %usertypes = %{$usertypesref};
15178:     }
15179:     $usertypes{'default'} = $othertitle;
15180: #
15181: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
15182: #
15183:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
15184:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
15185:             if ($key eq 'cancreate') {
15186:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
15187:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
15188:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
15189:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
15190:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
15191:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
15192:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
15193:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
15194:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
15195:                         } else {
15196:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
15197:                         }
15198:                     }
15199:                 }
15200:             } elsif ($key eq 'email_rule') {
15201:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
15202:             } else {
15203:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
15204:             }
15205:         }
15206:     }
15207: #
15208: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
15209: #
15210:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
15211:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
15212:             if ($key eq 'selfcreate') {
15213:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
15214:             } else {
15215:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
15216:             }
15217:         }
15218:     }
15219: #
15220: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
15221: #
15222:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
15223:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
15224:             if ($key eq 'inststatusguest') {
15225:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
15226:             } else {
15227:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
15228:             }
15229:         }
15230:     }
15231: 
15232:     my @contexts = ('selfcreate');
15233:     @{$cancreate{'selfcreate'}} = ();
15234:     %{$cancreate{'emailusername'}} = ();
15235:     if (@types) {
15236:         @{$cancreate{'statustocreate'}} = ();
15237:     }
15238:     %{$cancreate{'selfcreateprocessing'}} = ();
15239:     %{$cancreate{'shibenv'}} = ();
15240:     %{$cancreate{'emailverified'}} = ();
15241:     %{$cancreate{'emailoptions'}} = ();
15242:     %{$cancreate{'emaildomain'}} = ();
15243:     my %selfcreatetypes = (
15244:                              sso   => 'users authenticated by institutional single sign on',
15245:                              login => 'users authenticated by institutional log-in',
15246:                              email => 'users verified by e-mail',
15247:                           );
15248: #
15249: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
15250: # is permitted.
15251: #
15252:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
15253: 
15254:     my (@statuses,%email_rule);
15255:     foreach my $item ('login','sso','email') {
15256:         if ($item eq 'email') {
15257:             if ($env{'form.cancreate_email'}) {
15258:                 if (@types) {
15259:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
15260:                     foreach my $status (@poss_statuses) {
15261:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
15262:                             push(@statuses,$status);
15263:                         }
15264:                     }
15265:                     $save_inststatus{'inststatusguest'} = \@statuses;
15266:                 } else {
15267:                     push(@statuses,'default');
15268:                 }
15269:                 if (@statuses) {
15270:                     my %curr_rule;
15271:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
15272:                         foreach my $type (@statuses) {
15273:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
15274:                         }
15275:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
15276:                         foreach my $type (@statuses) {
15277:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
15278:                         }
15279:                     }
15280:                     push(@{$cancreate{'selfcreate'}},'email');
15281:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
15282:                     my %curremaildom;
15283:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
15284:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
15285:                     }
15286:                     foreach my $type (@statuses) {
15287:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
15288:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
15289:                         }
15290:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
15291:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
15292:                         }
15293:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
15294: #
15295: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
15296: #
15297:                             my $chosen = $1;
15298:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
15299:                                 my $emaildom;
15300:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
15301:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type}; 
15302:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
15303:                                     if (ref($curremaildom{$type}) eq 'HASH') {
15304:                                         if (exists($curremaildom{$type}{$chosen})) {
15305:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
15306:                                                 push(@{$changes{'cancreate'}},'emaildomain');
15307:                                             }
15308:                                         } elsif ($emaildom ne '') {
15309:                                             push(@{$changes{'cancreate'}},'emaildomain');
15310:                                         }
15311:                                     } elsif ($emaildom ne '') {
15312:                                         push(@{$changes{'cancreate'}},'emaildomain');
15313:                                     } 
15314:                                 }
15315:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
15316:                             } elsif ($chosen eq 'custom') {
15317:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
15318:                                 $email_rule{$type} = [];
15319:                                 if (ref($emailrules) eq 'HASH') {
15320:                                     foreach my $rule (@possemail_rules) {
15321:                                         if (exists($emailrules->{$rule})) {
15322:                                             push(@{$email_rule{$type}},$rule);
15323:                                         }
15324:                                     }
15325:                                 }
15326:                                 if (@{$email_rule{$type}}) {
15327:                                     $cancreate{'emailoptions'}{$type} = 'custom';
15328:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
15329:                                         if (@{$curr_rule{$type}} > 0) {
15330:                                             foreach my $rule (@{$curr_rule{$type}}) {
15331:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
15332:                                                     push(@{$changes{'email_rule'}},$type);
15333:                                                 }
15334:                                             }
15335:                                         }
15336:                                         foreach my $type (@{$email_rule{$type}}) {
15337:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
15338:                                                 push(@{$changes{'email_rule'}},$type);
15339:                                             }
15340:                                         }
15341:                                     } else {
15342:                                         push(@{$changes{'email_rule'}},$type);
15343:                                     }
15344:                                 }
15345:                             } else {
15346:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
15347:                             }
15348:                         }
15349:                     }
15350:                     if (@types) {
15351:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
15352:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
15353:                             if (@changed) {
15354:                                 push(@{$changes{'inststatus'}},'inststatusguest');
15355:                             }
15356:                         } else {
15357:                             push(@{$changes{'inststatus'}},'inststatusguest');
15358:                         }
15359:                     }
15360:                 } else {
15361:                     delete($env{'form.cancreate_email'});
15362:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
15363:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
15364:                             push(@{$changes{'inststatus'}},'inststatusguest');
15365:                         }
15366:                     }
15367:                 }
15368:             } else {
15369:                 $save_inststatus{'inststatusguest'} = [];
15370:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
15371:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
15372:                         push(@{$changes{'inststatus'}},'inststatusguest');
15373:                     }
15374:                 }
15375:             }
15376:         } else {
15377:             if ($env{'form.cancreate_'.$item}) {
15378:                 push(@{$cancreate{'selfcreate'}},$item);
15379:             }
15380:         }
15381:     }
15382:     my (%userinfo,%savecaptcha);
15383:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
15384: #
15385: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
15386: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
15387: #
15388: 
15389:     if ($env{'form.cancreate_email'}) {
15390:         push(@contexts,'emailusername');
15391:         if (@statuses) {
15392:             foreach my $type (@statuses) {
15393:                 if (ref($infofields) eq 'ARRAY') {
15394:                     foreach my $field (@{$infofields}) {
15395:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
15396:                             $cancreate{'emailusername'}{$type}{$field} = $1;
15397:                         }
15398:                     }
15399:                 }
15400:             }
15401:         }
15402: #
15403: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
15404: # queued requests for self-creation of account verified by e-mail.
15405: #
15406: 
15407:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
15408:         @approvalnotify = sort(@approvalnotify);
15409:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
15410:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
15411:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
15412:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
15413:                     push(@{$changes{'cancreate'}},'notify');
15414:                 }
15415:             } else {
15416:                 if ($cancreate{'notify'}{'approval'}) {
15417:                     push(@{$changes{'cancreate'}},'notify');
15418:                 }
15419:             }
15420:         } elsif ($cancreate{'notify'}{'approval'}) {
15421:             push(@{$changes{'cancreate'}},'notify');
15422:         }
15423: 
15424:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
15425:     }
15426: #  
15427: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
15428: # institutional log-in.
15429: #
15430:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
15431:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
15432:                ($domdefaults{'auth_def'} eq 'localauth'))) {
15433:             $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.').' '.
15434:                           &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.');
15435:         }
15436:     }
15437:     my @fields = ('lastname','firstname','middlename','generation',
15438:                   'permanentemail','id');
15439:     my @shibfields = (@fields,'inststatus');
15440:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
15441: #
15442: # Where usernames may created for institutional log-in and/or institutional single sign on:
15443: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
15444: # may self-create accounts 
15445: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
15446: # which the user may supply, if institutional data is unavailable.
15447: #
15448:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
15449:         if (@types) {
15450:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
15451:             push(@contexts,'statustocreate');
15452:             foreach my $type (@types) {
15453:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
15454:                 foreach my $field (@fields) {
15455:                     if (grep(/^\Q$field\E$/,@modifiable)) {
15456:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
15457:                     } else {
15458:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
15459:                     }
15460:                 }
15461:             }
15462:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
15463:                 foreach my $type (@types) {
15464:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
15465:                         foreach my $field (@fields) {
15466:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
15467:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
15468:                                 push(@{$changes{'selfcreate'}},$type);
15469:                                 last;
15470:                             }
15471:                         }
15472:                     }
15473:                 }
15474:             } else {
15475:                 foreach my $type (@types) {
15476:                     push(@{$changes{'selfcreate'}},$type);
15477:                 }
15478:             }
15479:         }
15480:         foreach my $field (@shibfields) {
15481:             if ($env{'form.shibenv_'.$field} ne '') {
15482:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
15483:             }
15484:         }
15485:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
15486:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
15487:                 foreach my $field (@shibfields) {
15488:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
15489:                         push(@{$changes{'cancreate'}},'shibenv');
15490:                     }
15491:                 }
15492:             } else {
15493:                 foreach my $field (@shibfields) {
15494:                     if ($env{'form.shibenv_'.$field}) {
15495:                         push(@{$changes{'cancreate'}},'shibenv');
15496:                         last;
15497:                     }
15498:                 }
15499:             }
15500:         }
15501:     }
15502:     foreach my $item (@contexts) {
15503:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
15504:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
15505:                 if (ref($cancreate{$item}) eq 'ARRAY') {
15506:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
15507:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15508:                             push(@{$changes{'cancreate'}},$item);
15509:                         }
15510:                     }
15511:                 }
15512:             }
15513:             if (ref($cancreate{$item}) eq 'ARRAY') {
15514:                 foreach my $type (@{$cancreate{$item}}) {
15515:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
15516:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15517:                             push(@{$changes{'cancreate'}},$item);
15518:                         }
15519:                     }
15520:                 }
15521:             }
15522:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
15523:             if (ref($cancreate{$item}) eq 'HASH') {
15524:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
15525:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
15526:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
15527:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
15528:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15529:                                     push(@{$changes{'cancreate'}},$item);
15530:                                 }
15531:                             }
15532:                         }
15533:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
15534:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
15535:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15536:                                 push(@{$changes{'cancreate'}},$item);
15537:                             }
15538:                         }
15539:                     }
15540:                 }
15541:                 foreach my $type (keys(%{$cancreate{$item}})) {
15542:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
15543:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
15544:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
15545:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
15546:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15547:                                         push(@{$changes{'cancreate'}},$item);
15548:                                     }
15549:                                 }
15550:                             } else {
15551:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15552:                                     push(@{$changes{'cancreate'}},$item);
15553:                                 }
15554:                             }
15555:                         }
15556:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
15557:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
15558:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15559:                                 push(@{$changes{'cancreate'}},$item);
15560:                             }
15561:                         }
15562:                     }
15563:                 }
15564:             }
15565:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
15566:             if (ref($cancreate{$item}) eq 'ARRAY') {
15567:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
15568:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15569:                         push(@{$changes{'cancreate'}},$item);
15570:                     }
15571:                 }
15572:             }
15573:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
15574:             if (ref($cancreate{$item}) eq 'HASH') {
15575:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15576:                     push(@{$changes{'cancreate'}},$item);
15577:                 }
15578:             }
15579:         } elsif ($item eq 'emailusername') {
15580:             if (ref($cancreate{$item}) eq 'HASH') {
15581:                 foreach my $type (keys(%{$cancreate{$item}})) {
15582:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
15583:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
15584:                             if ($cancreate{$item}{$type}{$field}) {
15585:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15586:                                     push(@{$changes{'cancreate'}},$item);
15587:                                 }
15588:                                 last;
15589:                             }
15590:                         }
15591:                     }
15592:                 }
15593:             }
15594:         }
15595:     }
15596: #
15597: # Populate %save_usercreate hash with updates to self-creation configuration.
15598: #
15599:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
15600:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
15601:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
15602:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
15603:     if (ref($cancreate{'notify'}) eq 'HASH') {
15604:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
15605:     }
15606:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
15607:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
15608:     }
15609:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
15610:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
15611:     }
15612:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
15613:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
15614:     }
15615:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
15616:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
15617:     }
15618:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
15619:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
15620:     }
15621:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
15622:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
15623:     }
15624:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
15625:     $save_usercreate{'email_rule'} = \%email_rule;
15626: 
15627:     my %userconfig_hash = (
15628:             usercreation     => \%save_usercreate,
15629:             usermodification => \%save_usermodify,
15630:             inststatus       => \%save_inststatus,
15631:     );
15632: 
15633:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
15634:                                              $dom);
15635: #
15636: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
15637: #
15638:     if ($putresult eq 'ok') {
15639:         if (keys(%changes) > 0) {
15640:             $resulttext = &mt('Changes made:').'<ul>';
15641:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
15642:                 my %lt = &selfcreation_types();
15643:                 foreach my $type (@{$changes{'cancreate'}}) {
15644:                     my $chgtext = '';
15645:                     if ($type eq 'selfcreate') {
15646:                         if (@{$cancreate{$type}} == 0) {
15647:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
15648:                         } else {
15649:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
15650:                                         '<ul>';
15651:                             foreach my $case (@{$cancreate{$type}}) {
15652:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
15653:                             }
15654:                             $chgtext .= '</ul>';
15655:                             if (ref($cancreate{$type}) eq 'ARRAY') {
15656:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
15657:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
15658:                                         if (@{$cancreate{'statustocreate'}} == 0) {
15659:                                             $chgtext .= '<span class="LC_warning">'.
15660:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
15661:                                                         '</span><br />';
15662:                                         }
15663:                                     }
15664:                                 }
15665:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
15666:                                     if (!@statuses) {
15667:                                         $chgtext .= '<span class="LC_warning">'.
15668:                                                     &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.").
15669:                                                     '</span><br />';
15670: 
15671:                                     }
15672:                                 }
15673:                             }
15674:                         }
15675:                     } elsif ($type eq 'shibenv') {
15676:                         if (keys(%{$cancreate{$type}}) == 0) {
15677:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
15678:                         } else {
15679:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
15680:                                         '<ul>';
15681:                             foreach my $field (@shibfields) {
15682:                                 next if ($cancreate{$type}{$field} eq '');
15683:                                 if ($field eq 'inststatus') {
15684:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
15685:                                 } else {
15686:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
15687:                                 }
15688:                             }
15689:                             $chgtext .= '</ul>';
15690:                         }
15691:                     } elsif ($type eq 'statustocreate') {
15692:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
15693:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
15694:                             if (@{$cancreate{'selfcreate'}} > 0) {
15695:                                 if (@{$cancreate{'statustocreate'}} == 0) {
15696:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
15697:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
15698:                                         $chgtext .= '<br />'.
15699:                                                     '<span class="LC_warning">'.
15700:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
15701:                                                     '</span>';
15702:                                     }
15703:                                 } elsif (keys(%usertypes) > 0) {
15704:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
15705:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
15706:                                     } else {
15707:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
15708:                                     }
15709:                                     $chgtext .= '<ul>';
15710:                                     foreach my $case (@{$cancreate{$type}}) {
15711:                                         if ($case eq 'default') {
15712:                                             $chgtext .= '<li>'.$othertitle.'</li>';
15713:                                         } else {
15714:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
15715:                                         }
15716:                                     }
15717:                                     $chgtext .= '</ul>';
15718:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
15719:                                         $chgtext .= '<span class="LC_warning">'.
15720:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
15721:                                                     '</span>';
15722:                                     }
15723:                                 }
15724:                             } else {
15725:                                 if (@{$cancreate{$type}} == 0) {
15726:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
15727:                                 } else {
15728:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
15729:                                 }
15730:                             }
15731:                             $chgtext .= '<br />';
15732:                         }
15733:                     } elsif ($type eq 'selfcreateprocessing') {
15734:                         my %choices = &Apache::lonlocal::texthash (
15735:                                                                     automatic => 'Automatic approval',
15736:                                                                     approval  => 'Queued for approval',
15737:                                                                   );
15738:                         if (@types) {
15739:                             if (@statuses) {
15740:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:'). 
15741:                                             '<ul>';
15742:                                 foreach my $status (@statuses) {
15743:                                     if ($status eq 'default') {
15744:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
15745:                                     } else {
15746:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
15747:                                     }
15748:                                 }
15749:                                 $chgtext .= '</ul>';
15750:                             }
15751:                         } else {
15752:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
15753:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
15754:                         }
15755:                     } elsif ($type eq 'emailverified') {
15756:                         my %options = &Apache::lonlocal::texthash (
15757:                                                                     all   => 'Same as e-mail',
15758:                                                                     first => 'Omit @domain',
15759:                                                                     free  => 'Free to choose',
15760:                                                                   );
15761:                         if (@types) {
15762:                             if (@statuses) {
15763:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
15764:                                             '<ul>';
15765:                                 foreach my $status (@statuses) {
15766:                                     if ($status eq 'default') {
15767:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
15768:                                     } else {
15769:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
15770:                                     }
15771:                                 }
15772:                                 $chgtext .= '</ul>';
15773:                             }
15774:                         } else {
15775:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
15776:                                             $options{$cancreate{'emailverified'}{'default'}});
15777:                         }
15778:                     } elsif ($type eq 'emailoptions') {
15779:                         my %options = &Apache::lonlocal::texthash (
15780:                                                                     any     => 'Any e-mail',
15781:                                                                     inst    => 'Institutional only',
15782:                                                                     noninst => 'Non-institutional only',
15783:                                                                     custom  => 'Custom restrictions',
15784:                                                                   );
15785:                         if (@types) {
15786:                             if (@statuses) {
15787:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
15788:                                             '<ul>';
15789:                                 foreach my $status (@statuses) {
15790:                                     if ($type eq 'default') {
15791:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
15792:                                     } else {
15793:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
15794:                                     }
15795:                                 }
15796:                                 $chgtext .= '</ul>';
15797:                             }
15798:                         } else {
15799:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
15800:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
15801:                             } else {
15802:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
15803:                                                 $options{$cancreate{'emailoptions'}{'default'}});
15804:                             }
15805:                         }
15806:                     } elsif ($type eq 'emaildomain') {
15807:                         my $output;
15808:                         if (@statuses) {
15809:                             foreach my $type (@statuses) {
15810:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
15811:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
15812:                                         if ($type eq 'default') {
15813:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15814:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
15815:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
15816:                                             } else {
15817:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
15818:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
15819:                                             }
15820:                                         } else {
15821:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15822:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
15823:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
15824:                                             } else {
15825:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
15826:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>'; 
15827:                                             }
15828:                                         }
15829:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
15830:                                         if ($type eq 'default') {
15831:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15832:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
15833:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
15834:                                             } else {
15835:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
15836:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
15837:                                             }
15838:                                         } else {
15839:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15840:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
15841:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
15842:                                             } else {
15843:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
15844:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';   
15845:                                             }
15846:                                         }
15847:                                     }
15848:                                 }
15849:                             }
15850:                         }
15851:                         if ($output ne '') {
15852:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
15853:                                         '<ul>'.$output.'</ul>';
15854:                         }
15855:                     } elsif ($type eq 'captcha') {
15856:                         if ($savecaptcha{$type} eq 'notused') {
15857:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
15858:                         } else {
15859:                             my %captchas = &captcha_phrases();
15860:                             if ($captchas{$savecaptcha{$type}}) {
15861:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
15862:                             } else {
15863:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
15864:                             }
15865:                         }
15866:                     } elsif ($type eq 'recaptchakeys') {
15867:                         my ($privkey,$pubkey);
15868:                         if (ref($savecaptcha{$type}) eq 'HASH') {
15869:                             $pubkey = $savecaptcha{$type}{'public'};
15870:                             $privkey = $savecaptcha{$type}{'private'};
15871:                         }
15872:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
15873:                         if (!$pubkey) {
15874:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
15875:                         } else {
15876:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
15877:                         }
15878:                         if (!$privkey) {
15879:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
15880:                         } else {
15881:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
15882:                         }
15883:                         $chgtext .= '</ul>';
15884:                     } elsif ($type eq 'recaptchaversion') {
15885:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
15886:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
15887:                         }
15888:                     } elsif ($type eq 'emailusername') {
15889:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
15890:                             if (@statuses) {
15891:                                 foreach my $type (@statuses) {
15892:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
15893:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
15894:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
15895:                                                     '<ul>';
15896:                                             foreach my $field (@{$infofields}) {
15897:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
15898:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
15899:                                                 }
15900:                                             }
15901:                                             $chgtext .= '</ul>';
15902:                                         } else {
15903:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
15904:                                         }
15905:                                     } else {
15906:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
15907:                                     }
15908:                                 }
15909:                             }
15910:                         }
15911:                     } elsif ($type eq 'notify') {
15912:                         my $numapprove = 0;
15913:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
15914:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
15915:                                 if ($cancreate{'notify'}{'approval'}) {
15916:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
15917:                                     $numapprove ++;
15918:                                 }
15919:                             }
15920:                         }
15921:                         unless ($numapprove) {
15922:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
15923:                         }
15924:                     }
15925:                     if ($chgtext) {
15926:                         $resulttext .= '<li>'.$chgtext.'</li>';
15927:                     }
15928:                 }
15929:             }
15930:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
15931:                 my ($emailrules,$emailruleorder) =
15932:                     &Apache::lonnet::inst_userrules($dom,'email');
15933:                 foreach my $type (@{$changes{'email_rule'}}) {
15934:                     if (ref($email_rule{$type}) eq 'ARRAY') {
15935:                         my $chgtext = '<ul>';
15936:                         foreach my $rule (@{$email_rule{$type}}) {
15937:                             if (ref($emailrules->{$rule}) eq 'HASH') {
15938:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
15939:                             }
15940:                         }
15941:                         $chgtext .= '</ul>';
15942:                         my $typename;
15943:                         if (@types) {
15944:                             if ($type eq 'default') {
15945:                                 $typename = $othertitle;
15946:                             } else {
15947:                                 $typename = $usertypes{$type};
15948:                             } 
15949:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
15950:                         }
15951:                         if (@{$email_rule{$type}} > 0) {
15952:                             $resulttext .= '<li>'.
15953:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
15954:                                                $usertypes{$type}).
15955:                                            $chgtext.
15956:                                            '</li>';
15957:                         } else {
15958:                             $resulttext .= '<li>'.
15959:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
15960:                                            '</li>'.
15961:                                            &mt('(Affiliation: [_1])',$typename);
15962:                         }
15963:                     }
15964:                 }
15965:             }
15966:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
15967:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
15968:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
15969:                         my $chgtext = '<ul>';
15970:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
15971:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
15972:                         }
15973:                         $chgtext .= '</ul>';
15974:                         $resulttext .= '<li>'.
15975:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
15976:                                           $chgtext.
15977:                                        '</li>';
15978:                     } else {
15979:                         $resulttext .= '<li>'.
15980:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
15981:                                        '</li>';
15982:                     }
15983:                 }
15984:             }
15985:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
15986:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
15987:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
15988:                 foreach my $type (@{$changes{'selfcreate'}}) {
15989:                     my $typename = $type;
15990:                     if (keys(%usertypes) > 0) {
15991:                         if ($usertypes{$type} ne '') {
15992:                             $typename = $usertypes{$type};
15993:                         }
15994:                     }
15995:                     my @modifiable;
15996:                     $resulttext .= '<li>'.
15997:                                     &mt('Self-creation of account by users with status: [_1]',
15998:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
15999:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
16000:                     foreach my $field (@fields) {
16001:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
16002:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
16003:                         }
16004:                     }
16005:                     if (@modifiable > 0) {
16006:                         $resulttext .= join(', ',@modifiable);
16007:                     } else {
16008:                         $resulttext .= &mt('none');
16009:                     }
16010:                     $resulttext .= '</li>';
16011:                 }
16012:                 $resulttext .= '</ul></li>';
16013:             }
16014:             $resulttext .= '</ul>';
16015:             my $cachetime = 24*60*60;
16016:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
16017:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16018:             if (ref($lastactref) eq 'HASH') {
16019:                 $lastactref->{'domdefaults'} = 1;
16020:             }
16021:         } else {
16022:             $resulttext = &mt('No changes made to self-creation settings');
16023:         }
16024:     } else {
16025:         $resulttext = '<span class="LC_error">'.
16026:             &mt('An error occurred: [_1]',$putresult).'</span>';
16027:     }
16028:     if ($warningmsg ne '') {
16029:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
16030:     }
16031:     return $resulttext;
16032: }
16033: 
16034: sub process_captcha {
16035:     my ($container,$changes,$newsettings,$current) = @_;
16036:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH') || (ref($current) eq 'HASH'));
16037:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
16038:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
16039:         $newsettings->{'captcha'} = 'original';
16040:     }
16041:     if ($current->{'captcha'} ne $newsettings->{'captcha'}) {
16042:         if ($container eq 'cancreate') {
16043:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
16044:                 push(@{$changes->{'cancreate'}},'captcha');
16045:             } elsif (!defined($changes->{'cancreate'})) {
16046:                 $changes->{'cancreate'} = ['captcha'];
16047:             }
16048:         } else {
16049:             $changes->{'captcha'} = 1;
16050:         }
16051:     }
16052:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
16053:     if ($newsettings->{'captcha'} eq 'recaptcha') {
16054:         $newpub = $env{'form.'.$container.'_recaptchapub'};
16055:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
16056:         $newpub =~ s/[^\w\-]//g;
16057:         $newpriv =~ s/[^\w\-]//g;
16058:         $newsettings->{'recaptchakeys'} = {
16059:                                              public  => $newpub,
16060:                                              private => $newpriv,
16061:                                           };
16062:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
16063:         $newversion =~ s/\D//g;
16064:         if ($newversion ne '2') {
16065:             $newversion = 1;
16066:         }
16067:         $newsettings->{'recaptchaversion'} = $newversion;
16068:     }
16069:     if (ref($current->{'recaptchakeys'}) eq 'HASH') {
16070:         $currpub = $current->{'recaptchakeys'}{'public'};
16071:         $currpriv = $current->{'recaptchakeys'}{'private'};
16072:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
16073:             $newsettings->{'recaptchakeys'} = {
16074:                                                  public  => '',
16075:                                                  private => '',
16076:                                               }
16077:         }
16078:     }
16079:     if ($current->{'captcha'} eq 'recaptcha') {
16080:         $currversion = $current->{'recaptchaversion'};
16081:         if ($currversion ne '2') {
16082:             $currversion = 1;
16083:         }
16084:     }
16085:     if ($currversion ne $newversion) {
16086:         if ($container eq 'cancreate') {
16087:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
16088:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
16089:             } elsif (!defined($changes->{'cancreate'})) {
16090:                 $changes->{'cancreate'} = ['recaptchaversion'];
16091:             }
16092:         } else {
16093:             $changes->{'recaptchaversion'} = 1;
16094:         }
16095:     }
16096:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
16097:         if ($container eq 'cancreate') {
16098:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
16099:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
16100:             } elsif (!defined($changes->{'cancreate'})) {
16101:                 $changes->{'cancreate'} = ['recaptchakeys'];
16102:             }
16103:         } else {
16104:             $changes->{'recaptchakeys'} = 1;
16105:         }
16106:     }
16107:     return;
16108: }
16109: 
16110: sub modify_usermodification {
16111:     my ($dom,%domconfig) = @_;
16112:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
16113:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
16114:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
16115:             if ($key eq 'selfcreate') {
16116:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
16117:             } else {  
16118:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
16119:             }
16120:         }
16121:     }
16122:     my @contexts = ('author','course');
16123:     my %context_title = (
16124:                            author => 'In author context',
16125:                            course => 'In course context',
16126:                         );
16127:     my @fields = ('lastname','firstname','middlename','generation',
16128:                   'permanentemail','id');
16129:     my %roles = (
16130:                   author => ['ca','aa'],
16131:                   course => ['st','ep','ta','in','cr'],
16132:                 );
16133:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
16134:     foreach my $context (@contexts) {
16135:         foreach my $role (@{$roles{$context}}) {
16136:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
16137:             foreach my $item (@fields) {
16138:                 if (grep(/^\Q$item\E$/,@modifiable)) {
16139:                     $modifyhash{$context}{$role}{$item} = 1;
16140:                 } else {
16141:                     $modifyhash{$context}{$role}{$item} = 0;
16142:                 }
16143:             }
16144:         }
16145:         if (ref($curr_usermodification{$context}) eq 'HASH') {
16146:             foreach my $role (@{$roles{$context}}) {
16147:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
16148:                     foreach my $field (@fields) {
16149:                         if ($modifyhash{$context}{$role}{$field} ne 
16150:                                 $curr_usermodification{$context}{$role}{$field}) {
16151:                             push(@{$changes{$context}},$role);
16152:                             last;
16153:                         }
16154:                     }
16155:                 }
16156:             }
16157:         } else {
16158:             foreach my $context (@contexts) {
16159:                 foreach my $role (@{$roles{$context}}) {
16160:                     push(@{$changes{$context}},$role);
16161:                 }
16162:             }
16163:         }
16164:     }
16165:     my %usermodification_hash =  (
16166:                                    usermodification => \%modifyhash,
16167:                                  );
16168:     my $putresult = &Apache::lonnet::put_dom('configuration',
16169:                                              \%usermodification_hash,$dom);
16170:     if ($putresult eq 'ok') {
16171:         if (keys(%changes) > 0) {
16172:             $resulttext = &mt('Changes made: ').'<ul>';
16173:             foreach my $context (@contexts) {
16174:                 if (ref($changes{$context}) eq 'ARRAY') {
16175:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
16176:                     if (ref($changes{$context}) eq 'ARRAY') {
16177:                         foreach my $role (@{$changes{$context}}) {
16178:                             my $rolename;
16179:                             if ($role eq 'cr') {
16180:                                 $rolename = &mt('Custom');
16181:                             } else {
16182:                                 $rolename = &Apache::lonnet::plaintext($role);
16183:                             }
16184:                             my @modifiable;
16185:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
16186:                             foreach my $field (@fields) {
16187:                                 if ($modifyhash{$context}{$role}{$field}) {
16188:                                     push(@modifiable,$fieldtitles{$field});
16189:                                 }
16190:                             }
16191:                             if (@modifiable > 0) {
16192:                                 $resulttext .= join(', ',@modifiable);
16193:                             } else {
16194:                                 $resulttext .= &mt('none'); 
16195:                             }
16196:                             $resulttext .= '</li>';
16197:                         }
16198:                         $resulttext .= '</ul></li>';
16199:                     }
16200:                 }
16201:             }
16202:             $resulttext .= '</ul>';
16203:         } else {
16204:             $resulttext = &mt('No changes made to user modification settings');
16205:         }
16206:     } else {
16207:         $resulttext = '<span class="LC_error">'.
16208:             &mt('An error occurred: [_1]',$putresult).'</span>';
16209:     }
16210:     return $resulttext;
16211: }
16212: 
16213: sub modify_defaults {
16214:     my ($dom,$lastactref,%domconfig) = @_;
16215:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
16216:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16217:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
16218:                  'portal_def');
16219:     my @authtypes = ('internal','krb4','krb5','localauth','lti');
16220:     foreach my $item (@items) {
16221:         $newvalues{$item} = $env{'form.'.$item};
16222:         if ($item eq 'auth_def') {
16223:             if ($newvalues{$item} ne '') {
16224:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
16225:                     push(@errors,$item);
16226:                 }
16227:             }
16228:         } elsif ($item eq 'lang_def') {
16229:             if ($newvalues{$item} ne '') {
16230:                 if ($newvalues{$item} =~ /^(\w+)/) {
16231:                     my $langcode = $1;
16232:                     if ($langcode ne 'x_chef') {
16233:                         if (code2language($langcode) eq '') {
16234:                             push(@errors,$item);
16235:                         }
16236:                     }
16237:                 } else {
16238:                     push(@errors,$item);
16239:                 }
16240:             }
16241:         } elsif ($item eq 'timezone_def') {
16242:             if ($newvalues{$item} ne '') {
16243:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
16244:                     push(@errors,$item);   
16245:                 }
16246:             }
16247:         } elsif ($item eq 'datelocale_def') {
16248:             if ($newvalues{$item} ne '') {
16249:                 my @datelocale_ids = DateTime::Locale->ids();
16250:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
16251:                     push(@errors,$item);
16252:                 }
16253:             }
16254:         } elsif ($item eq 'portal_def') {
16255:             if ($newvalues{$item} ne '') {
16256:                 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])\/?$/) {
16257:                     push(@errors,$item);
16258:                 }
16259:             }
16260:         }
16261:         if (grep(/^\Q$item\E$/,@errors)) {
16262:             $newvalues{$item} = $domdefaults{$item};
16263:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
16264:             $changes{$item} = 1;
16265:         }
16266:         $domdefaults{$item} = $newvalues{$item};
16267:     }
16268:     my %staticdefaults = (
16269:                            'intauth_cost'   => 10,
16270:                            'intauth_check'  => 0,
16271:                            'intauth_switch' => 0,
16272:                          );
16273:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
16274:         if (exists($domdefaults{$item})) {
16275:             $newvalues{$item} = $domdefaults{$item};
16276:         } else {
16277:             $newvalues{$item} = $staticdefaults{$item};
16278:         }
16279:     }
16280:     my %defaults_hash = (
16281:                          defaults => \%newvalues,
16282:                         );
16283:     my $title = &defaults_titles();
16284: 
16285:     my $currinststatus;
16286:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
16287:         $currinststatus = $domconfig{'inststatus'};
16288:     } else {
16289:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16290:         $currinststatus = {
16291:                              inststatustypes => $usertypes,
16292:                              inststatusorder => $types,
16293:                              inststatusguest => [],
16294:                           };
16295:     }
16296:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
16297:     my @allpos;
16298:     my %alltypes;
16299:     my @inststatusguest;
16300:     if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
16301:         foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
16302:             unless (grep(/^\Q$type\E$/,@todelete)) {
16303:                 push(@inststatusguest,$type);
16304:             }
16305:         }
16306:     }
16307:     my ($currtitles,$currorder);
16308:     if (ref($currinststatus) eq 'HASH') {
16309:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
16310:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
16311:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
16312:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
16313:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
16314:                     }
16315:                 }
16316:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
16317:                     my $position = $env{'form.inststatus_pos_'.$type};
16318:                     $position =~ s/\D+//g;
16319:                     $allpos[$position] = $type;
16320:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
16321:                     $alltypes{$type} =~ s/`//g;
16322:                 }
16323:             }
16324:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
16325:             $currtitles =~ s/,$//;
16326:         }
16327:     }
16328:     if ($env{'form.addinststatus'}) {
16329:         my $newtype = $env{'form.addinststatus'};
16330:         $newtype =~ s/\W//g;
16331:         unless (exists($alltypes{$newtype})) {
16332:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
16333:             $alltypes{$newtype} =~ s/`//g; 
16334:             my $position = $env{'form.addinststatus_pos'};
16335:             $position =~ s/\D+//g;
16336:             if ($position ne '') {
16337:                 $allpos[$position] = $newtype;
16338:             }
16339:         }
16340:     }
16341:     my @orderedstatus;
16342:     foreach my $type (@allpos) {
16343:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
16344:             push(@orderedstatus,$type);
16345:         }
16346:     }
16347:     foreach my $type (keys(%alltypes)) {
16348:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
16349:             delete($alltypes{$type});
16350:         }
16351:     }
16352:     $defaults_hash{'inststatus'} = {
16353:                                      inststatustypes => \%alltypes,
16354:                                      inststatusorder => \@orderedstatus,
16355:                                      inststatusguest => \@inststatusguest,
16356:                                    };
16357:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
16358:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
16359:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
16360:         }
16361:     }
16362:     if ($currorder ne join(',',@orderedstatus)) {
16363:         $changes{'inststatus'}{'inststatusorder'} = 1;
16364:     }
16365:     my $newtitles;
16366:     foreach my $item (@orderedstatus) {
16367:         $newtitles .= $alltypes{$item}.',';
16368:     }
16369:     $newtitles =~ s/,$//;
16370:     if ($currtitles ne $newtitles) {
16371:         $changes{'inststatus'}{'inststatustypes'} = 1;
16372:     }
16373:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
16374:                                              $dom);
16375:     if ($putresult eq 'ok') {
16376:         if (keys(%changes) > 0) {
16377:             $resulttext = &mt('Changes made:').'<ul>';
16378:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
16379:             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";
16380:             foreach my $item (sort(keys(%changes))) {
16381:                 if ($item eq 'inststatus') {
16382:                     if (ref($changes{'inststatus'}) eq 'HASH') {
16383:                         if (@orderedstatus) {
16384:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
16385:                             foreach my $type (@orderedstatus) { 
16386:                                 $resulttext .= $alltypes{$type}.', ';
16387:                             }
16388:                             $resulttext =~ s/, $//;
16389:                             $resulttext .= '</li>';
16390:                         } else {
16391:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>'; 
16392:                         }
16393:                     }
16394:                 } else {
16395:                     my $value = $env{'form.'.$item};
16396:                     if ($value eq '') {
16397:                         $value = &mt('none');
16398:                     } elsif ($item eq 'auth_def') {
16399:                         my %authnames = &authtype_names();
16400:                         my %shortauth = (
16401:                                           internal   => 'int',
16402:                                           krb4       => 'krb4',
16403:                                           krb5       => 'krb5',
16404:                                           localauth  => 'loc',
16405:                                           lti        => 'lti',
16406:                         );
16407:                         $value = $authnames{$shortauth{$value}};
16408:                     }
16409:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
16410:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
16411:                 }
16412:             }
16413:             $resulttext .= '</ul>';
16414:             $mailmsgtext .= "\n";
16415:             my $cachetime = 24*60*60;
16416:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16417:             if (ref($lastactref) eq 'HASH') {
16418:                 $lastactref->{'domdefaults'} = 1;
16419:             }
16420:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
16421:                 my $notify = 1;
16422:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
16423:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
16424:                         $notify = 0;
16425:                     }
16426:                 }
16427:                 if ($notify) {
16428:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
16429:                                                "LON-CAPA Domain Settings Change - $dom",
16430:                                                $mailmsgtext);
16431:                 }
16432:             }
16433:         } else {
16434:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
16435:         }
16436:     } else {
16437:         $resulttext = '<span class="LC_error">'.
16438:             &mt('An error occurred: [_1]',$putresult).'</span>';
16439:     }
16440:     if (@errors > 0) {
16441:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
16442:         foreach my $item (@errors) {
16443:             $resulttext .= ' "'.$title->{$item}.'",';
16444:         }
16445:         $resulttext =~ s/,$//;
16446:     }
16447:     return $resulttext;
16448: }
16449: 
16450: sub modify_scantron {
16451:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
16452:     my ($resulttext,%confhash,%changes,$errors);
16453:     my $custom = 'custom.tab';
16454:     my $default = 'default.tab';
16455:     my $servadm = $r->dir_config('lonAdmEMail');
16456:     my ($configuserok,$author_ok,$switchserver) =
16457:         &config_check($dom,$confname,$servadm);
16458:     if ($env{'form.scantronformat.filename'} ne '') {
16459:         my $error;
16460:         if ($configuserok eq 'ok') {
16461:             if ($switchserver) {
16462:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
16463:             } else {
16464:                 if ($author_ok eq 'ok') {
16465:                     my ($result,$scantronurl) =
16466:                         &publishlogo($r,'upload','scantronformat',$dom,
16467:                                      $confname,'scantron','','',$custom);
16468:                     if ($result eq 'ok') {
16469:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
16470:                         $changes{'scantronformat'} = 1;
16471:                     } else {
16472:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
16473:                     }
16474:                 } else {
16475:                     $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);
16476:                 }
16477:             }
16478:         } else {
16479:             $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);
16480:         }
16481:         if ($error) {
16482:             &Apache::lonnet::logthis($error);
16483:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
16484:         }
16485:     }
16486:     if (ref($domconfig{'scantron'}) eq 'HASH') {
16487:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
16488:             if ($env{'form.scantronformat_del'}) {
16489:                 $confhash{'scantron'}{'scantronformat'} = '';
16490:                 $changes{'scantronformat'} = 1;
16491:             } else {
16492:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
16493:             }
16494:         }
16495:     }
16496:     my @options = ('hdr','pad','rem');
16497:     my @fields = &scantroncsv_fields();
16498:     my %titles = &scantronconfig_titles();
16499:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
16500:     my ($newdat,$currdat,%newcol,%currcol);
16501:     if (grep(/^dat$/,@formats)) {
16502:         $confhash{'scantron'}{config}{dat} = 1;
16503:         $newdat = 1;
16504:     } else {
16505:         $newdat = 0;
16506:     }
16507:     if (grep(/^csv$/,@formats)) {
16508:         my %bynum;
16509:         foreach my $field (@fields) {
16510:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
16511:                 my $posscol = $1;
16512:                 if (($posscol < 20) && (!$bynum{$posscol})) {
16513:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
16514:                     $bynum{$posscol} = $field;
16515:                     $newcol{$field} = $posscol;
16516:                 }
16517:             }
16518:         }
16519:         if (keys(%newcol)) {
16520:             foreach my $option (@options) {
16521:                 if ($env{'form.scantroncsv_'.$option}) {
16522:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
16523:                 }
16524:             }
16525:         }
16526:     }
16527:     $currdat = 1;
16528:     if (ref($domconfig{'scantron'}) eq 'HASH') {
16529:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
16530:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
16531:                 $currdat = 0;
16532:             }
16533:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
16534:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
16535:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
16536:                 }
16537:             }
16538:         }
16539:     }
16540:     if ($currdat != $newdat) {
16541:         $changes{'config'} = 1;
16542:     } else {
16543:         foreach my $field (@fields) {
16544:             if ($currcol{$field} ne '') {
16545:                 if ($currcol{$field} ne $newcol{$field}) {
16546:                     $changes{'config'} = 1;
16547:                     last;
16548:                 }
16549:             } elsif ($newcol{$field} ne '') {
16550:                 $changes{'config'} = 1;
16551:                 last;
16552:             }
16553:         }
16554:     }
16555:     if (keys(%confhash) > 0) {
16556:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
16557:                                                  $dom);
16558:         if ($putresult eq 'ok') {
16559:             if (keys(%changes) > 0) {
16560:                 if (ref($confhash{'scantron'}) eq 'HASH') {
16561:                     $resulttext = &mt('Changes made:').'<ul>';
16562:                     if ($changes{'scantronformat'}) {
16563:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
16564:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
16565:                         } else {
16566:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
16567:                         }
16568:                     }
16569:                     if ($changes{'config'}) {
16570:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
16571:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
16572:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
16573:                             }
16574:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
16575:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
16576:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
16577:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
16578:                                         foreach my $field (@fields) {
16579:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
16580:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
16581:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
16582:                                             }
16583:                                         }
16584:                                         $resulttext .= '</ul></li>';
16585:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
16586:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
16587:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
16588:                                                 foreach my $option (@options) {
16589:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
16590:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
16591:                                                     }
16592:                                                 }
16593:                                                 $resulttext .= '</ul></li>';
16594:                                             }
16595:                                         }
16596:                                     }
16597:                                 }
16598:                             }
16599:                         } else {
16600:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
16601:                         }
16602:                     }
16603:                     $resulttext .= '</ul>';
16604:                 } else {
16605:                     $resulttext = &mt('Changes made to bubblesheet format file.');
16606:                 }
16607:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
16608:                 if (ref($lastactref) eq 'HASH') {
16609:                     $lastactref->{'domainconfig'} = 1;
16610:                 }
16611:             } else {
16612:                 $resulttext = &mt('No changes made to bubblesheet format settings');
16613:             }
16614:         } else {
16615:             $resulttext = '<span class="LC_error">'.
16616:                 &mt('An error occurred: [_1]',$putresult).'</span>';
16617:         }
16618:     } else {
16619:         $resulttext = &mt('No changes made to bubblesheet format file'); 
16620:     }
16621:     if ($errors) {
16622:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
16623:                        $errors.'</ul></p>';
16624:     }
16625:     return $resulttext;
16626: }
16627: 
16628: sub modify_coursecategories {
16629:     my ($dom,$lastactref,%domconfig) = @_;
16630:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
16631:         $cathash);
16632:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
16633:     my @catitems = ('unauth','auth');
16634:     my @cattypes = ('std','domonly','codesrch','none');
16635:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
16636:         $cathash = $domconfig{'coursecategories'}{'cats'};
16637:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
16638:             $changes{'togglecats'} = 1;
16639:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
16640:         }
16641:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
16642:             $changes{'categorize'} = 1;
16643:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
16644:         }
16645:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
16646:             $changes{'togglecatscomm'} = 1;
16647:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
16648:         }
16649:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
16650:             $changes{'categorizecomm'} = 1;
16651:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
16652: 
16653:         }
16654:         if ($domconfig{'coursecategories'}{'togglecatsplace'} ne $env{'form.togglecatsplace'}) {
16655:             $changes{'togglecatsplace'} = 1;
16656:             $domconfig{'coursecategories'}{'togglecatsplace'} = $env{'form.togglecatsplace'};
16657:         }
16658:         if ($domconfig{'coursecategories'}{'categorizeplace'} ne $env{'form.categorizeplace'}) {
16659:             $changes{'categorizeplace'} = 1;
16660:             $domconfig{'coursecategories'}{'categorizeplace'} = $env{'form.categorizeplace'};
16661:         }
16662:         foreach my $item (@catitems) {
16663:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
16664:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
16665:                     $changes{$item} = 1;
16666:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
16667:                 }
16668:             }
16669:         }
16670:     } else {
16671:         $changes{'togglecats'} = 1;
16672:         $changes{'categorize'} = 1;
16673:         $changes{'togglecatscomm'} = 1;
16674:         $changes{'categorizecomm'} = 1;
16675:         $changes{'togglecatsplace'} = 1;
16676:         $changes{'categorizeplace'} = 1;
16677:         $domconfig{'coursecategories'} = {
16678:                                              togglecats => $env{'form.togglecats'},
16679:                                              categorize => $env{'form.categorize'},
16680:                                              togglecatscomm => $env{'form.togglecatscomm'},
16681:                                              categorizecomm => $env{'form.categorizecomm'},
16682:                                              togglecatsplace => $env{'form.togglecatsplace'},
16683:                                              categorizeplace => $env{'form.categorizeplace'},
16684:                                          };
16685:         foreach my $item (@catitems) {
16686:             if ($env{'form.coursecat_'.$item} ne 'std') {
16687:                 $changes{$item} = 1;
16688:             }
16689:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
16690:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
16691:             }
16692:         }
16693:     }
16694:     if (ref($cathash) eq 'HASH') {
16695:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
16696:             push (@deletecategory,'instcode::0');
16697:         }
16698:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
16699:             push(@deletecategory,'communities::0');
16700:         }
16701:         if (($domconfig{'coursecategories'}{'cats'}{'placement::0'} ne '')  && ($env{'form.placement'} == 0)) {
16702:             push(@deletecategory,'placement::0');
16703:         }
16704:     }
16705:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
16706:     if (ref($cathash) eq 'HASH') {
16707:         if (@deletecategory > 0) {
16708:             #FIXME Need to remove category from all courses using a deleted category 
16709:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
16710:             foreach my $item (@deletecategory) {
16711:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
16712:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
16713:                     $deletions{$item} = 1;
16714:                     &recurse_cat_deletes($item,$cathash,\%deletions);
16715:                 }
16716:             }
16717:         }
16718:         foreach my $item (keys(%{$cathash})) {
16719:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
16720:             if ($cathash->{$item} ne $env{'form.'.$item}) {
16721:                 $reorderings{$item} = 1;
16722:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
16723:             }
16724:             if ($env{'form.addcategory_name_'.$item} ne '') {
16725:                 my $newcat = $env{'form.addcategory_name_'.$item};
16726:                 my $newdepth = $depth+1;
16727:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
16728:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
16729:                 $adds{$newitem} = 1; 
16730:             }
16731:             if ($env{'form.subcat_'.$item} ne '') {
16732:                 my $newcat = $env{'form.subcat_'.$item};
16733:                 my $newdepth = $depth+1;
16734:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
16735:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
16736:                 $adds{$newitem} = 1;
16737:             }
16738:         }
16739:     }
16740:     if ($env{'form.instcode'} eq '1') {
16741:         if (ref($cathash) eq 'HASH') {
16742:             my $newitem = 'instcode::0';
16743:             if ($cathash->{$newitem} eq '') {  
16744:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
16745:                 $adds{$newitem} = 1;
16746:             }
16747:         } else {
16748:             my $newitem = 'instcode::0';
16749:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
16750:             $adds{$newitem} = 1;
16751:         }
16752:     }
16753:     if ($env{'form.communities'} eq '1') {
16754:         if (ref($cathash) eq 'HASH') {
16755:             my $newitem = 'communities::0';
16756:             if ($cathash->{$newitem} eq '') {
16757:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
16758:                 $adds{$newitem} = 1;
16759:             }
16760:         } else {
16761:             my $newitem = 'communities::0';
16762:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
16763:             $adds{$newitem} = 1;
16764:         }
16765:     }
16766:     if ($env{'form.placement'} eq '1') {
16767:         if (ref($cathash) eq 'HASH') {
16768:             my $newitem = 'placement::0';
16769:             if ($cathash->{$newitem} eq '') {
16770:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
16771:                 $adds{$newitem} = 1;
16772:             }
16773:         } else {
16774:             my $newitem = 'placement::0';
16775:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
16776:             $adds{$newitem} = 1;
16777:         }
16778:     }
16779:     if ($env{'form.addcategory_name'} ne '') {
16780:         if (($env{'form.addcategory_name'} ne 'instcode') &&
16781:             ($env{'form.addcategory_name'} ne 'communities') &&
16782:             ($env{'form.addcategory_name'} ne 'placement')) {
16783:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
16784:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
16785:             $adds{$newitem} = 1;
16786:         }
16787:     }
16788:     my $putresult;
16789:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
16790:         if (keys(%deletions) > 0) {
16791:             foreach my $key (keys(%deletions)) {
16792:                 if ($predelallitems{$key} ne '') {
16793:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
16794:                 }
16795:             }
16796:         }
16797:         my (@chkcats,@chktrails,%chkallitems);
16798:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
16799:         if (ref($chkcats[0]) eq 'ARRAY') {
16800:             my $depth = 0;
16801:             my $chg = 0;
16802:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
16803:                 my $name = $chkcats[0][$i];
16804:                 my $item;
16805:                 if ($name eq '') {
16806:                     $chg ++;
16807:                 } else {
16808:                     $item = &escape($name).'::0';
16809:                     if ($chg) {
16810:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
16811:                     }
16812:                     $depth ++; 
16813:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
16814:                     $depth --;
16815:                 }
16816:             }
16817:         }
16818:     }
16819:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
16820:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
16821:         if ($putresult eq 'ok') {
16822:             my %title = (
16823:                          togglecats     => 'Show/Hide a course in catalog',
16824:                          categorize     => 'Assign a category to a course',
16825:                          togglecatscomm => 'Show/Hide a community in catalog',
16826:                          categorizecomm => 'Assign a category to a community',
16827:                         );
16828:             my %level = (
16829:                          dom  => 'set in Domain ("Modify Course/Community")',
16830:                          crs  => 'set in Course ("Course Configuration")',
16831:                          comm => 'set in Community ("Community Configuration")',
16832:                          none     => 'No catalog',
16833:                          std      => 'Standard catalog',
16834:                          domonly  => 'Domain-only catalog',
16835:                          codesrch => 'Code search form',
16836:                         );
16837:             $resulttext = &mt('Changes made:').'<ul>';
16838:             if ($changes{'togglecats'}) {
16839:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
16840:             }
16841:             if ($changes{'categorize'}) {
16842:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
16843:             }
16844:             if ($changes{'togglecatscomm'}) {
16845:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
16846:             }
16847:             if ($changes{'categorizecomm'}) {
16848:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
16849:             }
16850:             if ($changes{'unauth'}) {
16851:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
16852:             }
16853:             if ($changes{'auth'}) {
16854:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
16855:             }
16856:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
16857:                 my $cathash;
16858:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
16859:                     $cathash = $domconfig{'coursecategories'}{'cats'};
16860:                 } else {
16861:                     $cathash = {};
16862:                 } 
16863:                 my (@cats,@trails,%allitems);
16864:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
16865:                 if (keys(%deletions) > 0) {
16866:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
16867:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
16868:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
16869:                     }
16870:                     $resulttext .= '</ul></li>';
16871:                 }
16872:                 if (keys(%reorderings) > 0) {
16873:                     my %sort_by_trail;
16874:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
16875:                     foreach my $key (keys(%reorderings)) {
16876:                         if ($allitems{$key} ne '') {
16877:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
16878:                         }
16879:                     }
16880:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
16881:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
16882:                     }
16883:                     $resulttext .= '</ul></li>';
16884:                 }
16885:                 if (keys(%adds) > 0) {
16886:                     my %sort_by_trail;
16887:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
16888:                     foreach my $key (keys(%adds)) {
16889:                         if ($allitems{$key} ne '') {
16890:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
16891:                         }
16892:                     }
16893:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
16894:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
16895:                     }
16896:                     $resulttext .= '</ul></li>';
16897:                 }
16898:             }
16899:             $resulttext .= '</ul>';
16900:             if ($changes{'unauth'} || $changes{'auth'}) {
16901:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
16902:                 if ($changes{'auth'}) {
16903:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
16904:                 }
16905:                 if ($changes{'unauth'}) {
16906:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
16907:                 }
16908:                 my $cachetime = 24*60*60;
16909:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16910:                 if (ref($lastactref) eq 'HASH') {
16911:                     $lastactref->{'domdefaults'} = 1;
16912:                 }
16913:             }
16914:         } else {
16915:             $resulttext = '<span class="LC_error">'.
16916:                           &mt('An error occurred: [_1]',$putresult).'</span>';
16917:         }
16918:     } else {
16919:         $resulttext = &mt('No changes made to course and community categories');
16920:     }
16921:     return $resulttext;
16922: }
16923: 
16924: sub modify_serverstatuses {
16925:     my ($dom,%domconfig) = @_;
16926:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
16927:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
16928:         %currserverstatus = %{$domconfig{'serverstatuses'}};
16929:     }
16930:     my @pages = &serverstatus_pages();
16931:     foreach my $type (@pages) {
16932:         $newserverstatus{$type}{'namedusers'} = '';
16933:         $newserverstatus{$type}{'machines'} = '';
16934:         if (defined($env{'form.'.$type.'_namedusers'})) {
16935:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
16936:             my @okusers;
16937:             foreach my $user (@users) {
16938:                 my ($uname,$udom) = split(/:/,$user);
16939:                 if (($udom =~ /^$match_domain$/) &&   
16940:                     (&Apache::lonnet::domain($udom)) &&
16941:                     ($uname =~ /^$match_username$/)) {
16942:                     if (!grep(/^\Q$user\E/,@okusers)) {
16943:                         push(@okusers,$user);
16944:                     }
16945:                 }
16946:             }
16947:             if (@okusers > 0) {
16948:                  @okusers = sort(@okusers);
16949:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
16950:             }
16951:         }
16952:         if (defined($env{'form.'.$type.'_machines'})) {
16953:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
16954:             my @okmachines;
16955:             foreach my $ip (@machines) {
16956:                 my @parts = split(/\./,$ip);
16957:                 next if (@parts < 4);
16958:                 my $badip = 0;
16959:                 for (my $i=0; $i<4; $i++) {
16960:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
16961:                         $badip = 1;
16962:                         last;
16963:                     }
16964:                 }
16965:                 if (!$badip) {
16966:                     push(@okmachines,$ip);     
16967:                 }
16968:             }
16969:             @okmachines = sort(@okmachines);
16970:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
16971:         }
16972:     }
16973:     my %serverstatushash =  (
16974:                                 serverstatuses => \%newserverstatus,
16975:                             );
16976:     foreach my $type (@pages) {
16977:         foreach my $setting ('namedusers','machines') {
16978:             my (@current,@new);
16979:             if (ref($currserverstatus{$type}) eq 'HASH') {
16980:                 if ($currserverstatus{$type}{$setting} ne '') { 
16981:                     @current = split(/,/,$currserverstatus{$type}{$setting});
16982:                 }
16983:             }
16984:             if ($newserverstatus{$type}{$setting} ne '') {
16985:                 @new = split(/,/,$newserverstatus{$type}{$setting});
16986:             }
16987:             if (@current > 0) {
16988:                 if (@new > 0) {
16989:                     foreach my $item (@current) {
16990:                         if (!grep(/^\Q$item\E$/,@new)) {
16991:                             $changes{$type}{$setting} = 1;
16992:                             last;
16993:                         }
16994:                     }
16995:                     foreach my $item (@new) {
16996:                         if (!grep(/^\Q$item\E$/,@current)) {
16997:                             $changes{$type}{$setting} = 1;
16998:                             last;
16999:                         }
17000:                     }
17001:                 } else {
17002:                     $changes{$type}{$setting} = 1;
17003:                 }
17004:             } elsif (@new > 0) {
17005:                 $changes{$type}{$setting} = 1;
17006:             }
17007:         }
17008:     }
17009:     if (keys(%changes) > 0) {
17010:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
17011:         my $putresult = &Apache::lonnet::put_dom('configuration',
17012:                                                  \%serverstatushash,$dom);
17013:         if ($putresult eq 'ok') {
17014:             $resulttext .= &mt('Changes made:').'<ul>';
17015:             foreach my $type (@pages) {
17016:                 if (ref($changes{$type}) eq 'HASH') {
17017:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
17018:                     if ($changes{$type}{'namedusers'}) {
17019:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
17020:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
17021:                         } else {
17022:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
17023:                         }
17024:                     }
17025:                     if ($changes{$type}{'machines'}) {
17026:                         if ($newserverstatus{$type}{'machines'} eq '') {
17027:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
17028:                         } else {
17029:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
17030:                         }
17031: 
17032:                     }
17033:                     $resulttext .= '</ul></li>';
17034:                 }
17035:             }
17036:             $resulttext .= '</ul>';
17037:         } else {
17038:             $resulttext = '<span class="LC_error">'.
17039:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
17040: 
17041:         }
17042:     } else {
17043:         $resulttext = &mt('No changes made to access to server status pages');
17044:     }
17045:     return $resulttext;
17046: }
17047: 
17048: sub modify_helpsettings {
17049:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
17050:     my ($resulttext,$errors,%changes,%helphash);
17051:     my %defaultchecked = ('submitbugs' => 'on');
17052:     my @offon = ('off','on');
17053:     my @toggles = ('submitbugs');
17054:     my %current = ('submitbugs' => '',
17055:                    'adhoc'      => {},
17056:                   );
17057:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
17058:         %current = %{$domconfig{'helpsettings'}};
17059:     }
17060:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
17061:     foreach my $item (@toggles) {
17062:         if ($defaultchecked{$item} eq 'on') { 
17063:             if ($current{$item} eq '') {
17064:                 if ($env{'form.'.$item} eq '0') {
17065:                     $changes{$item} = 1;
17066:                 }
17067:             } elsif ($current{$item} ne $env{'form.'.$item}) {
17068:                 $changes{$item} = 1;
17069:             }
17070:         } elsif ($defaultchecked{$item} eq 'off') {
17071:             if ($current{$item} eq '') {
17072:                 if ($env{'form.'.$item} eq '1') {
17073:                     $changes{$item} = 1;
17074:                 }
17075:             } elsif ($current{$item} ne $env{'form.'.$item}) {
17076:                 $changes{$item} = 1;
17077:             }
17078:         }
17079:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
17080:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
17081:         }
17082:     }
17083:     my $maxnum = $env{'form.helproles_maxnum'};
17084:     my $confname = $dom.'-domainconfig';
17085:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
17086:     my (@allpos,%newsettings,%changedprivs,$newrole);
17087:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
17088:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
17089:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
17090:     my %lt = &Apache::lonlocal::texthash(
17091:                     s      => 'system',
17092:                     d      => 'domain',
17093:                     order  => 'Display order',
17094:                     access => 'Role usage',
17095:                     all    => 'All with domain helpdesk or helpdesk assistant role',
17096:                     dh     => 'All with domain helpdesk role',
17097:                     da     => 'All with domain helpdesk assistant role',
17098:                     none   => 'None',
17099:                     status => 'Determined based on institutional status',
17100:                     inc    => 'Include all, but exclude specific personnel',
17101:                     exc    => 'Exclude all, but include specific personnel',
17102:     );
17103:     for (my $num=0; $num<=$maxnum; $num++) {
17104:         my ($prefix,$identifier,$rolename,%curr);
17105:         if ($num == $maxnum) {
17106:             next unless ($env{'form.newcusthelp'} == $maxnum);
17107:             $identifier = 'custhelp'.$num;
17108:             $prefix = 'helproles_'.$num;
17109:             $rolename = $env{'form.custhelpname'.$num};
17110:             $rolename=~s/[^A-Za-z0-9]//gs;
17111:             next if ($rolename eq '');
17112:             next if (exists($existing{'rolesdef_'.$rolename}));
17113:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
17114:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
17115:                                                      $newprivs{'c'},$confname,$dom);
17116:             if ($result ne 'ok') {
17117:                 $errors .= '<li><span class="LC_error">'.
17118:                            &mt('An error occurred storing the new custom role: [_1]',
17119:                            $result).'</span></li>';
17120:                 next;
17121:             } else {
17122:                 $changedprivs{$rolename} = \%newprivs;
17123:                 $newrole = $rolename;
17124:             }
17125:         } else {
17126:             $prefix = 'helproles_'.$num;
17127:             $rolename = $env{'form.'.$prefix};
17128:             next if ($rolename eq '');
17129:             next unless (exists($existing{'rolesdef_'.$rolename}));
17130:             $identifier = 'custhelp'.$num;
17131:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
17132:             my %currprivs;
17133:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
17134:                 split(/\_/,$existing{'rolesdef_'.$rolename});
17135:             foreach my $level ('c','d','s') {
17136:                 if ($newprivs{$level} ne $currprivs{$level}) {
17137:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
17138:                                                              $newprivs{'c'},$confname,$dom);
17139:                     if ($result ne 'ok') {
17140:                         $errors .= '<li><span class="LC_error">'.
17141:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
17142:                                        $rolename,$result).'</span></li>';
17143:                     } else {
17144:                         $changedprivs{$rolename} = \%newprivs;
17145:                     }
17146:                     last;
17147:                 }
17148:             }
17149:             if (ref($current{'adhoc'}) eq 'HASH') {
17150:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
17151:                     %curr = %{$current{'adhoc'}{$rolename}};
17152:                 }
17153:             }
17154:         }
17155:         my $newpos = $env{'form.'.$prefix.'_pos'};
17156:         $newpos =~ s/\D+//g;
17157:         $allpos[$newpos] = $rolename;
17158:         my $newdesc = $env{'form.'.$prefix.'_desc'};
17159:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
17160:         if ($curr{'desc'}) {
17161:             if ($curr{'desc'} ne $newdesc) {
17162:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
17163:                 $newsettings{$rolename}{'desc'} = $newdesc;
17164:             }
17165:         } elsif ($newdesc ne '') {
17166:             $changes{'customrole'}{$rolename}{'desc'} = 1;
17167:             $newsettings{$rolename}{'desc'} = $newdesc;
17168:         }
17169:         my $access = $env{'form.'.$prefix.'_access'};
17170:         if (grep(/^\Q$access\E$/,@accesstypes)) {
17171:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
17172:             if ($access eq 'status') {
17173:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
17174:                 if (scalar(@statuses) == 0) {
17175:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
17176:                 } else {
17177:                     my (@shownstatus,$numtypes);
17178:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
17179:                     if (ref($types) eq 'ARRAY') {
17180:                         $numtypes = scalar(@{$types});
17181:                         foreach my $type (sort(@statuses)) {
17182:                             if ($type eq 'default') {
17183:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
17184:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
17185:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
17186:                                 push(@shownstatus,$usertypes->{$type});
17187:                             }
17188:                         }
17189:                     }
17190:                     if (grep(/^default$/,@statuses)) {
17191:                         push(@shownstatus,$othertitle);
17192:                     }
17193:                     if (scalar(@shownstatus) == 1+$numtypes) {
17194:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
17195:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
17196:                     } else {
17197:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
17198:                         if (ref($curr{'status'}) eq 'ARRAY') {
17199:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
17200:                             if (@diffs) {
17201:                                 $changes{'customrole'}{$rolename}{$access} = 1;
17202:                             }
17203:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
17204:                             $changes{'customrole'}{$rolename}{$access} = 1;
17205:                         }
17206:                     }
17207:                 }
17208:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
17209:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
17210:                 my @newspecstaff;
17211:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
17212:                 foreach my $person (sort(@personnel)) {
17213:                     if ($domhelpdesk{$person}) {
17214:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
17215:                     }
17216:                 }
17217:                 if (ref($curr{$access}) eq 'ARRAY') {
17218:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
17219:                     if (@diffs) {
17220:                         $changes{'customrole'}{$rolename}{$access} = 1;
17221:                     }
17222:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
17223:                     $changes{'customrole'}{$rolename}{$access} = 1;
17224:                 }
17225:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
17226:                     my ($uname,$udom) = split(/:/,$person);
17227:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
17228:                 }
17229:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
17230:             }
17231:         } else {
17232:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
17233:         }
17234:         unless ($curr{'access'} eq $access) {
17235:             $changes{'customrole'}{$rolename}{'access'} = 1;
17236:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
17237:         }
17238:     }
17239:     if (@allpos > 0) {
17240:         my $idx = 0;
17241:         foreach my $rolename (@allpos) {
17242:             if ($rolename ne '') {
17243:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
17244:                 if (ref($current{'adhoc'}) eq 'HASH') {
17245:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
17246:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
17247:                             $changes{'customrole'}{$rolename}{'order'} = 1;
17248:                             $newsettings{$rolename}{'order'} = $idx+1;
17249:                         }
17250:                     }
17251:                 }
17252:                 $idx ++;
17253:             }
17254:         }
17255:     }
17256:     my $putresult;
17257:     if (keys(%changes) > 0) {
17258:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
17259:         if ($putresult eq 'ok') {
17260:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
17261:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
17262:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
17263:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
17264:                 }
17265:             }
17266:             my $cachetime = 24*60*60;
17267:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17268:             if (ref($lastactref) eq 'HASH') {
17269:                 $lastactref->{'domdefaults'} = 1;
17270:             }
17271:         } else {
17272:             $errors .= '<li><span class="LC_error">'.
17273:                        &mt('An error occurred storing the settings: [_1]',
17274:                            $putresult).'</span></li>';
17275:         }
17276:     }
17277:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
17278:         $resulttext = &mt('Changes made:').'<ul>';
17279:         my (%shownprivs,@levelorder);
17280:         @levelorder = ('c','d','s');
17281:         if ((keys(%changes)) && ($putresult eq 'ok')) {
17282:             foreach my $item (sort(keys(%changes))) {
17283:                 if ($item eq 'submitbugs') {
17284:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
17285:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
17286:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
17287:                 } elsif ($item eq 'customrole') {
17288:                     if (ref($changes{'customrole'}) eq 'HASH') {
17289:                         my @keyorder = ('order','desc','access','status','exc','inc');
17290:                         my %keytext = &Apache::lonlocal::texthash(
17291:                                                                    order  => 'Order',
17292:                                                                    desc   => 'Role description',
17293:                                                                    access => 'Role usage',
17294:                                                                    status => 'Allowed institutional types',
17295:                                                                    exc    => 'Allowed personnel',
17296:                                                                    inc    => 'Disallowed personnel',
17297:                         );
17298:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
17299:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
17300:                                 if ($role eq $newrole) {
17301:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
17302:                                                               $role).'<ul>';
17303:                                 } else {
17304:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
17305:                                                               $role).'<ul>';
17306:                                 }
17307:                                 foreach my $key (@keyorder) {
17308:                                     if ($changes{'customrole'}{$role}{$key}) {
17309:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
17310:                                                                   $keytext{$key},$newsettings{$role}{$key}).
17311:                                                        '</li>';
17312:                                     }
17313:                                 }
17314:                                 if (ref($changedprivs{$role}) eq 'HASH') {
17315:                                     $shownprivs{$role} = 1;
17316:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
17317:                                     foreach my $level (@levelorder) {
17318:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
17319:                                             next if ($item eq '');
17320:                                             my ($priv) = split(/\&/,$item,2);
17321:                                             if (&Apache::lonnet::plaintext($priv)) {
17322:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
17323:                                                 unless ($level eq 'c') {
17324:                                                     $resulttext .= ' ('.$lt{$level}.')';
17325:                                                 }
17326:                                                 $resulttext .= '</li>';
17327:                                             }
17328:                                         }
17329:                                     }
17330:                                     $resulttext .= '</ul>';
17331:                                 }
17332:                                 $resulttext .= '</ul></li>';
17333:                             }
17334:                         }
17335:                     }
17336:                 }
17337:             }
17338:         }
17339:         if (keys(%changedprivs)) {
17340:             foreach my $role (sort(keys(%changedprivs))) {
17341:                 unless ($shownprivs{$role}) {
17342:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
17343:                                               $role).'<ul>'.
17344:                                    '<li>'.&mt('Privileges set to :').'<ul>';
17345:                     foreach my $level (@levelorder) {
17346:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
17347:                             next if ($item eq '');
17348:                             my ($priv) = split(/\&/,$item,2);
17349:                             if (&Apache::lonnet::plaintext($priv)) {
17350:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
17351:                                 unless ($level eq 'c') {
17352:                                     $resulttext .= ' ('.$lt{$level}.')';
17353:                                 }
17354:                                 $resulttext .= '</li>';
17355:                             }
17356:                         }
17357:                     }
17358:                     $resulttext .= '</ul></li></ul></li>';
17359:                 }
17360:             }
17361:         }
17362:         $resulttext .= '</ul>';
17363:     } else {
17364:         $resulttext = &mt('No changes made to help settings');
17365:     }
17366:     if ($errors) {
17367:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
17368:                                     $errors.'</ul>';
17369:     }
17370:     return $resulttext;
17371: }
17372: 
17373: sub modify_coursedefaults {
17374:     my ($dom,$lastactref,%domconfig) = @_;
17375:     my ($resulttext,$errors,%changes,%defaultshash);
17376:     my %defaultchecked = (
17377:                            'canuse_pdfforms' => 'off',
17378:                            'uselcmath'       => 'on',
17379:                            'usejsme'         => 'on'
17380:                          );
17381:     my @toggles = ('canuse_pdfforms','uselcmath','usejsme');
17382:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
17383:                    'uploadquota_community','uploadquota_textbook','uploadquota_placement',
17384:                    'mysqltables_official','mysqltables_unofficial','mysqltables_community',
17385:                    'mysqltables_textbook','mysqltables_placement');
17386:     my @types = ('official','unofficial','community','textbook','placement');
17387:     my %staticdefaults = (
17388:                            anonsurvey_threshold => 10,
17389:                            uploadquota          => 500,
17390:                            postsubmit           => 60,
17391:                            mysqltables          => 172800,
17392:                          );
17393:     my %texoptions = (
17394:                         MathJax  => 'MathJax',
17395:                         mimetex  => &mt('Convert to Images'),
17396:                         tth      => &mt('TeX to HTML'),
17397:                      );
17398:     $defaultshash{'coursedefaults'} = {};
17399: 
17400:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
17401:         if ($domconfig{'coursedefaults'} eq '') {
17402:             $domconfig{'coursedefaults'} = {};
17403:         }
17404:     }
17405: 
17406:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
17407:         foreach my $item (@toggles) {
17408:             if ($defaultchecked{$item} eq 'on') {
17409:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
17410:                     ($env{'form.'.$item} eq '0')) {
17411:                     $changes{$item} = 1;
17412:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
17413:                     $changes{$item} = 1;
17414:                 }
17415:             } elsif ($defaultchecked{$item} eq 'off') {
17416:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
17417:                     ($env{'form.'.$item} eq '1')) {
17418:                     $changes{$item} = 1;
17419:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
17420:                     $changes{$item} = 1;
17421:                 }
17422:             }
17423:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
17424:         }
17425:         foreach my $item (@numbers) {
17426:             my ($currdef,$newdef);
17427:             $newdef = $env{'form.'.$item};
17428:             if ($item eq 'anonsurvey_threshold') {
17429:                 $currdef = $domconfig{'coursedefaults'}{$item};
17430:                 $newdef =~ s/\D//g;
17431:                 if ($newdef eq '' || $newdef < 1) {
17432:                     $newdef = 1;
17433:                 }
17434:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
17435:             } else {
17436:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
17437:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
17438:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
17439:                 }
17440:                 $newdef =~ s/[^\w.\-]//g;
17441:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
17442:             }
17443:             if ($currdef ne $newdef) {
17444:                 if ($item eq 'anonsurvey_threshold') {
17445:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
17446:                         $changes{$item} = 1;
17447:                     }
17448:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
17449:                     my $setting = $1;
17450:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
17451:                         $changes{$setting} = 1;
17452:                     }
17453:                 }
17454:             }
17455:         }
17456:         my $texengine;
17457:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
17458:             $texengine = $env{'form.texengine'};
17459:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
17460:             if ($currdef eq '') {
17461:                 unless ($texengine eq $Apache::lonnet::deftex) {
17462:                     $changes{'texengine'} = 1;
17463:                 }
17464:             } elsif ($currdef ne $texengine) {
17465:                 $changes{'texengine'} = 1;
17466:             }
17467:         }
17468:         if ($texengine ne '') {
17469:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
17470:         }
17471:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
17472:         my @currclonecode;
17473:         if (ref($currclone) eq 'HASH') {
17474:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
17475:                 @currclonecode = @{$currclone->{'instcode'}};
17476:             }
17477:         }
17478:         my $newclone;
17479:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
17480:             $newclone = $env{'form.canclone'};
17481:         }
17482:         if ($newclone eq 'instcode') {
17483:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
17484:             my (%codedefaults,@code_order,@clonecode);
17485:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
17486:                                                     \@code_order);
17487:             foreach my $item (@code_order) {
17488:                 if (grep(/^\Q$item\E$/,@newcodes)) {
17489:                     push(@clonecode,$item);
17490:                 }
17491:             }
17492:             if (@clonecode) {
17493:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
17494:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
17495:                 if (@diffs) {
17496:                     $changes{'canclone'} = 1;
17497:                 }
17498:             } else {
17499:                 $newclone eq '';
17500:             }
17501:         } elsif ($newclone ne '') {
17502:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
17503:         }
17504:         if ($newclone ne $currclone) {
17505:             $changes{'canclone'} = 1;
17506:         }
17507:         my %credits;
17508:         foreach my $type (@types) {
17509:             unless ($type eq 'community') {
17510:                 $credits{$type} = $env{'form.'.$type.'_credits'};
17511:                 $credits{$type} =~ s/[^\d.]+//g;
17512:             }
17513:         }
17514:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
17515:             ($env{'form.coursecredits'} eq '1')) {
17516:             $changes{'coursecredits'} = 1;
17517:             foreach my $type (keys(%credits)) {
17518:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
17519:             }
17520:         } else {
17521:             if ($env{'form.coursecredits'} eq '1') {
17522:                 foreach my $type (@types) {
17523:                     unless ($type eq 'community') {
17524:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
17525:                             $changes{'coursecredits'} = 1;
17526:                         }
17527:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
17528:                     }
17529:                 }
17530:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
17531:                 foreach my $type (@types) {
17532:                     unless ($type eq 'community') {
17533:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
17534:                             $changes{'coursecredits'} = 1;
17535:                             last;
17536:                         }
17537:                     }
17538:                 }
17539:             }
17540:         }
17541:         if ($env{'form.postsubmit'} eq '1') {
17542:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
17543:             my %currtimeout;
17544:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
17545:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
17546:                     $changes{'postsubmit'} = 1;
17547:                 }
17548:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
17549:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
17550:                 }
17551:             } else {
17552:                 $changes{'postsubmit'} = 1;
17553:             }
17554:             foreach my $type (@types) {
17555:                 my $timeout = $env{'form.'.$type.'_timeout'};
17556:                 $timeout =~ s/\D//g;
17557:                 if ($timeout == $staticdefaults{'postsubmit'}) {
17558:                     $timeout = '';
17559:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
17560:                     $timeout = '0';
17561:                 }
17562:                 unless ($timeout eq '') {
17563:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
17564:                 }
17565:                 if (exists($currtimeout{$type})) {
17566:                     if ($timeout ne $currtimeout{$type}) {
17567:                         $changes{'postsubmit'} = 1;
17568:                     }
17569:                 } elsif ($timeout ne '') {
17570:                     $changes{'postsubmit'} = 1;
17571:                 }
17572:             }
17573:         } else {
17574:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
17575:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
17576:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
17577:                     $changes{'postsubmit'} = 1;
17578:                 }
17579:             } else {
17580:                 $changes{'postsubmit'} = 1;
17581:             }
17582:         }
17583:     }
17584:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
17585:                                              $dom);
17586:     if ($putresult eq 'ok') {
17587:         if (keys(%changes) > 0) {
17588:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
17589:             if (($changes{'canuse_pdfforms'}) || ($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
17590:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
17591:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'})) {
17592:                 foreach my $item ('canuse_pdfforms','uselcmath','usejsme','texengine') {
17593:                     if ($changes{$item}) {
17594:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
17595:                     }
17596:                 }
17597:                 if ($changes{'coursecredits'}) {
17598:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
17599:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
17600:                             $domdefaults{$type.'credits'} =
17601:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
17602:                         }
17603:                     }
17604:                 }
17605:                 if ($changes{'postsubmit'}) {
17606:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
17607:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
17608:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
17609:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
17610:                                 $domdefaults{$type.'postsubtimeout'} =
17611:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
17612:                             }
17613:                         }
17614:                     }
17615:                 }
17616:                 if ($changes{'uploadquota'}) {
17617:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
17618:                         foreach my $type (@types) {
17619:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
17620:                         }
17621:                     }
17622:                 }
17623:                 if ($changes{'canclone'}) {
17624:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
17625:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
17626:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
17627:                             if (@clonecodes) {
17628:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
17629:                             }
17630:                         }
17631:                     } else {
17632:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
17633:                     }
17634:                 }
17635:                 my $cachetime = 24*60*60;
17636:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17637:                 if (ref($lastactref) eq 'HASH') {
17638:                     $lastactref->{'domdefaults'} = 1;
17639:                 }
17640:             }
17641:             $resulttext = &mt('Changes made:').'<ul>';
17642:             foreach my $item (sort(keys(%changes))) {
17643:                 if ($item eq 'canuse_pdfforms') {
17644:                     if ($env{'form.'.$item} eq '1') {
17645:                         $resulttext .= '<li>'.&mt("Course/Community users can create/upload PDF forms set to 'on'").'</li>';
17646:                     } else {
17647:                         $resulttext .= '<li>'.&mt('Course/Community users can create/upload PDF forms set to "off"').'</li>';
17648:                     }
17649:                 } elsif ($item eq 'uselcmath') {
17650:                     if ($env{'form.'.$item} eq '1') {
17651:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
17652:                     } else {
17653:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
17654:                     }
17655:                 } elsif ($item eq 'usejsme') {
17656:                     if ($env{'form.'.$item} eq '1') {
17657:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
17658:                     } else {
17659:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
17660:                     }
17661:                 } elsif ($item eq 'texengine') {
17662:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
17663:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
17664:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
17665:                     }
17666:                 } elsif ($item eq 'anonsurvey_threshold') {
17667:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
17668:                 } elsif ($item eq 'uploadquota') {
17669:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
17670:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
17671:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
17672:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
17673:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
17674:                                        '<li>'.&mt('Placement tests: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'placement'}.'</b>').'</li>'. 
17675:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
17676:                                        '</ul>'.
17677:                                        '</li>';
17678:                     } else {
17679:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
17680:                     }
17681:                 } elsif ($item eq 'mysqltables') {
17682:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
17683:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
17684:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
17685:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
17686:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
17687:                                        '<li>'.&mt('Placement tests: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'placement'}.'</b>').'</li>'.
17688:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
17689:                                        '</ul>'.
17690:                                        '</li>';
17691:                     } else {
17692:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
17693:                     }
17694:                 } elsif ($item eq 'postsubmit') {
17695:                     if ($domdefaults{'postsubmit'} eq 'off') {
17696:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
17697:                     } else {
17698:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
17699:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
17700:                             $resulttext .= &mt('durations:').'<ul>';
17701:                             foreach my $type (@types) {
17702:                                 $resulttext .= '<li>';
17703:                                 my $timeout;
17704:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
17705:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
17706:                                 }
17707:                                 my $display;
17708:                                 if ($timeout eq '0') {
17709:                                     $display = &mt('unlimited');
17710:                                 } elsif ($timeout eq '') {
17711:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
17712:                                 } else {
17713:                                     $display = &mt('[quant,_1,second]',$timeout);
17714:                                 }
17715:                                 if ($type eq 'community') {
17716:                                     $resulttext .= &mt('Communities');
17717:                                 } elsif ($type eq 'official') {
17718:                                     $resulttext .= &mt('Official courses');
17719:                                 } elsif ($type eq 'unofficial') {
17720:                                     $resulttext .= &mt('Unofficial courses');
17721:                                 } elsif ($type eq 'textbook') {
17722:                                     $resulttext .= &mt('Textbook courses');
17723:                                 } elsif ($type eq 'placement') {
17724:                                     $resulttext .= &mt('Placement tests');
17725:                                 }
17726:                                 $resulttext .= ' -- '.$display.'</li>';
17727:                             }
17728:                             $resulttext .= '</ul>';
17729:                         }
17730:                         $resulttext .= '</li>';
17731:                     }
17732:                 } elsif ($item eq 'coursecredits') {
17733:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
17734:                         if (($domdefaults{'officialcredits'} eq '') &&
17735:                             ($domdefaults{'unofficialcredits'} eq '') &&
17736:                             ($domdefaults{'textbookcredits'} eq '')) {
17737:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
17738:                         } else {
17739:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
17740:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
17741:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
17742:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
17743:                                            '</ul>'.
17744:                                            '</li>';
17745:                         }
17746:                     } else {
17747:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
17748:                     }
17749:                 } elsif ($item eq 'canclone') {
17750:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
17751:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
17752:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
17753:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
17754:                         }
17755:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
17756:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
17757:                     } else {
17758:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
17759:                     }
17760:                 }
17761:             }
17762:             $resulttext .= '</ul>';
17763:         } else {
17764:             $resulttext = &mt('No changes made to course defaults');
17765:         }
17766:     } else {
17767:         $resulttext = '<span class="LC_error">'.
17768:             &mt('An error occurred: [_1]',$putresult).'</span>';
17769:     }
17770:     return $resulttext;
17771: }
17772: 
17773: sub modify_selfenrollment {
17774:     my ($dom,$lastactref,%domconfig) = @_;
17775:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
17776:     my @types = ('official','unofficial','community','textbook','placement');
17777:     my %titles = &tool_titles();
17778:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
17779:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
17780:     $ordered{'default'} = ['types','registered','approval','limit'];
17781: 
17782:     my (%roles,%shown,%toplevel);
17783:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
17784: 
17785:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
17786:         if ($domconfig{'selfenrollment'} eq '') {
17787:             $domconfig{'selfenrollment'} = {};
17788:         }
17789:     }
17790:     %toplevel = (
17791:                   admin      => 'Configuration Rights',
17792:                   default    => 'Default settings',
17793:                   validation => 'Validation of self-enrollment requests',
17794:                 );
17795:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
17796: 
17797:     if (ref($ordered{'admin'}) eq 'ARRAY') {
17798:         foreach my $item (@{$ordered{'admin'}}) {
17799:             foreach my $type (@types) {
17800:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
17801:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
17802:                 } else {
17803:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
17804:                 }
17805:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
17806:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
17807:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
17808:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
17809:                             push(@{$changes{'admin'}{$type}},$item);
17810:                         }
17811:                     } else {
17812:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
17813:                             push(@{$changes{'admin'}{$type}},$item);
17814:                         }
17815:                     }
17816:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
17817:                     push(@{$changes{'admin'}{$type}},$item);
17818:                 }
17819:             }
17820:         }
17821:     }
17822: 
17823:     foreach my $item (@{$ordered{'default'}}) {
17824:         foreach my $type (@types) {
17825:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
17826:             if ($item eq 'types') {
17827:                 unless (($value eq 'all') || ($value eq 'dom')) {
17828:                     $value = '';
17829:                 }
17830:             } elsif ($item eq 'registered') {
17831:                 unless ($value eq '1') {
17832:                     $value = 0;
17833:                 }
17834:             } elsif ($item eq 'approval') {
17835:                 unless ($value =~ /^[012]$/) {
17836:                     $value = 0;
17837:                 }
17838:             } else {
17839:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
17840:                     $value = 'none';
17841:                 }
17842:             }
17843:             $selfenrollhash{'default'}{$type}{$item} = $value;
17844:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
17845:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
17846:                     if ($selfenrollhash{'default'}{$type}{$item} ne
17847:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
17848:                          push(@{$changes{'default'}{$type}},$item);
17849:                     }
17850:                 } else {
17851:                     push(@{$changes{'default'}{$type}},$item);
17852:                 }
17853:             } else {
17854:                 push(@{$changes{'default'}{$type}},$item);
17855:             }
17856:             if ($item eq 'limit') {
17857:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
17858:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
17859:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
17860:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
17861:                     }
17862:                 } else {
17863:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
17864:                 }
17865:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
17866:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
17867:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
17868:                          push(@{$changes{'default'}{$type}},'cap');
17869:                     }
17870:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
17871:                     push(@{$changes{'default'}{$type}},'cap');
17872:                 }
17873:             }
17874:         }
17875:     }
17876: 
17877:     foreach my $item (@{$itemsref}) {
17878:         if ($item eq 'fields') {
17879:             my @changed;
17880:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
17881:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
17882:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
17883:             }
17884:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
17885:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
17886:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
17887:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
17888:                 } else {
17889:                     @changed = @{$selfenrollhash{'validation'}{$item}};
17890:                 }
17891:             } else {
17892:                 @changed = @{$selfenrollhash{'validation'}{$item}};
17893:             }
17894:             if (@changed) {
17895:                 if ($selfenrollhash{'validation'}{$item}) { 
17896:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
17897:                 } else {
17898:                     $changes{'validation'}{$item} = &mt('None');
17899:                 }
17900:             }
17901:         } else {
17902:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
17903:             if ($item eq 'markup') {
17904:                if ($env{'form.selfenroll_validation_'.$item}) {
17905:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
17906:                }
17907:             }
17908:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
17909:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
17910:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
17911:                 }
17912:             }
17913:         }
17914:     }
17915: 
17916:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
17917:                                              $dom);
17918:     if ($putresult eq 'ok') {
17919:         if (keys(%changes) > 0) {
17920:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
17921:             $resulttext = &mt('Changes made:').'<ul>';
17922:             foreach my $key ('admin','default','validation') {
17923:                 if (ref($changes{$key}) eq 'HASH') {
17924:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
17925:                     if ($key eq 'validation') {
17926:                         foreach my $item (@{$itemsref}) {
17927:                             if (exists($changes{$key}{$item})) {
17928:                                 if ($item eq 'markup') {
17929:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
17930:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
17931:                                 } else {  
17932:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
17933:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
17934:                                 }
17935:                             }
17936:                         }
17937:                     } else {
17938:                         foreach my $type (@types) {
17939:                             if ($type eq 'community') {
17940:                                 $roles{'1'} = &mt('Community personnel');
17941:                             } else {
17942:                                 $roles{'1'} = &mt('Course personnel');
17943:                             }
17944:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
17945:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
17946:                                     if ($key eq 'admin') {
17947:                                         my @mgrdc = ();
17948:                                         if (ref($ordered{$key}) eq 'ARRAY') {
17949:                                             foreach my $item (@{$ordered{'admin'}}) {
17950:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
17951:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
17952:                                                         push(@mgrdc,$item);
17953:                                                     }
17954:                                                 }
17955:                                             }
17956:                                             if (@mgrdc) {
17957:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
17958:                                             } else {
17959:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
17960:                                             }
17961:                                         }
17962:                                     } else {
17963:                                         if (ref($ordered{$key}) eq 'ARRAY') {
17964:                                             foreach my $item (@{$ordered{$key}}) {
17965:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
17966:                                                     $domdefaults{$type.'selfenroll'.$item} =
17967:                                                         $selfenrollhash{$key}{$type}{$item};
17968:                                                 }
17969:                                             }
17970:                                         }
17971:                                     }
17972:                                 }
17973:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
17974:                                 foreach my $item (@{$ordered{$key}}) {
17975:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
17976:                                         $resulttext .= '<li>';
17977:                                         if ($key eq 'admin') {
17978:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
17979:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
17980:                                         } else {
17981:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
17982:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
17983:                                         }
17984:                                         $resulttext .= '</li>';
17985:                                     }
17986:                                 }
17987:                                 $resulttext .= '</ul></li>';
17988:                             }
17989:                         }
17990:                         $resulttext .= '</ul></li>'; 
17991:                     }
17992:                 }
17993:             }
17994:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
17995:                 my $cachetime = 24*60*60;
17996:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17997:                 if (ref($lastactref) eq 'HASH') {
17998:                     $lastactref->{'domdefaults'} = 1;
17999:                 }
18000:             }
18001:             $resulttext .= '</ul>';
18002:         } else {
18003:             $resulttext = &mt('No changes made to self-enrollment settings');
18004:         }
18005:     } else {
18006:         $resulttext = '<span class="LC_error">'.
18007:             &mt('An error occurred: [_1]',$putresult).'</span>';
18008:     }
18009:     return $resulttext;
18010: }
18011: 
18012: sub modify_usersessions {
18013:     my ($dom,$lastactref,%domconfig) = @_;
18014:     my @hostingtypes = ('version','excludedomain','includedomain');
18015:     my @offloadtypes = ('primary','default');
18016:     my %types = (
18017:                   remote => \@hostingtypes,
18018:                   hosted => \@hostingtypes,
18019:                   spares => \@offloadtypes,
18020:                 );
18021:     my @prefixes = ('remote','hosted','spares');
18022:     my @lcversions = &Apache::lonnet::all_loncaparevs();
18023:     my (%by_ip,%by_location,@intdoms,@instdoms);
18024:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
18025:     my @locations = sort(keys(%by_location));
18026:     my (%defaultshash,%changes);
18027:     foreach my $prefix (@prefixes) {
18028:         $defaultshash{'usersessions'}{$prefix} = {};
18029:     }
18030:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18031:     my $resulttext;
18032:     my %iphost = &Apache::lonnet::get_iphost();
18033:     foreach my $prefix (@prefixes) {
18034:         next if ($prefix eq 'spares');
18035:         foreach my $type (@{$types{$prefix}}) {
18036:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
18037:             if ($type eq 'version') {
18038:                 my $value = $env{'form.'.$prefix.'_'.$type};
18039:                 my $okvalue;
18040:                 if ($value ne '') {
18041:                     if (grep(/^\Q$value\E$/,@lcversions)) {
18042:                         $okvalue = $value;
18043:                     }
18044:                 }
18045:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
18046:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
18047:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
18048:                             if ($inuse == 0) {
18049:                                 $changes{$prefix}{$type} = 1;
18050:                             } else {
18051:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
18052:                                     $changes{$prefix}{$type} = 1;
18053:                                 }
18054:                                 if ($okvalue ne '') {
18055:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
18056:                                 } 
18057:                             }
18058:                         } else {
18059:                             if (($inuse == 1) && ($okvalue ne '')) {
18060:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
18061:                                 $changes{$prefix}{$type} = 1;
18062:                             }
18063:                         }
18064:                     } else {
18065:                         if (($inuse == 1) && ($okvalue ne '')) {
18066:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
18067:                             $changes{$prefix}{$type} = 1;
18068:                         }
18069:                     }
18070:                 } else {
18071:                     if (($inuse == 1) && ($okvalue ne '')) {
18072:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
18073:                         $changes{$prefix}{$type} = 1;
18074:                     }
18075:                 }
18076:             } else {
18077:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
18078:                 my @okvals;
18079:                 foreach my $val (@vals) {
18080:                     if ($val =~ /:/) {
18081:                         my @items = split(/:/,$val);
18082:                         foreach my $item (@items) {
18083:                             if (ref($by_location{$item}) eq 'ARRAY') {
18084:                                 push(@okvals,$item);
18085:                             }
18086:                         }
18087:                     } else {
18088:                         if (ref($by_location{$val}) eq 'ARRAY') {
18089:                             push(@okvals,$val);
18090:                         }
18091:                     }
18092:                 }
18093:                 @okvals = sort(@okvals);
18094:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
18095:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
18096:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
18097:                             if ($inuse == 0) {
18098:                                 $changes{$prefix}{$type} = 1; 
18099:                             } else {
18100:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
18101:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
18102:                                 if (@changed > 0) {
18103:                                     $changes{$prefix}{$type} = 1;
18104:                                 }
18105:                             }
18106:                         } else {
18107:                             if ($inuse == 1) {
18108:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
18109:                                 $changes{$prefix}{$type} = 1;
18110:                             }
18111:                         } 
18112:                     } else {
18113:                         if ($inuse == 1) {
18114:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
18115:                             $changes{$prefix}{$type} = 1;
18116:                         }
18117:                     }
18118:                 } else {
18119:                     if ($inuse == 1) {
18120:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
18121:                         $changes{$prefix}{$type} = 1;
18122:                     }
18123:                 }
18124:             }
18125:         }
18126:     }
18127: 
18128:     my @alldoms = &Apache::lonnet::all_domains();
18129:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
18130:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
18131:     my $savespares;
18132: 
18133:     foreach my $lonhost (sort(keys(%servers))) {
18134:         my $serverhomeID =
18135:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
18136:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
18137:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
18138:         my %spareschg;
18139:         foreach my $type (@{$types{'spares'}}) {
18140:             my @okspares;
18141:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
18142:             foreach my $server (@checked) {
18143:                 if (&Apache::lonnet::hostname($server) ne '') {
18144:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
18145:                         unless (grep(/^\Q$server\E$/,@okspares)) {
18146:                             push(@okspares,$server);
18147:                         }
18148:                     }
18149:                 }
18150:             }
18151:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
18152:             my $newspare;
18153:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
18154:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
18155:                     $newspare = $new;
18156:                 }
18157:             }
18158:             my @spares;
18159:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
18160:                 @spares = sort(@okspares,$newspare);
18161:             } else {
18162:                 @spares = sort(@okspares);
18163:             }
18164:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
18165:             if (ref($spareid{$lonhost}) eq 'HASH') {
18166:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
18167:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
18168:                     if (@diffs > 0) {
18169:                         $spareschg{$type} = 1;
18170:                     }
18171:                 }
18172:             }
18173:         }
18174:         if (keys(%spareschg) > 0) {
18175:             $changes{'spares'}{$lonhost} = \%spareschg;
18176:         }
18177:     }
18178:     $defaultshash{'usersessions'}{'offloadnow'} = {};
18179:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
18180:     my @okoffload;
18181:     if (@offloadnow) {
18182:         foreach my $server (@offloadnow) {
18183:             if (&Apache::lonnet::hostname($server) ne '') {
18184:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
18185:                     push(@okoffload,$server);
18186:                 }
18187:             }
18188:         }
18189:         if (@okoffload) {
18190:             foreach my $lonhost (@okoffload) {
18191:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
18192:             }
18193:         }
18194:     }
18195:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
18196:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
18197:             if (ref($changes{'spares'}) eq 'HASH') {
18198:                 if (keys(%{$changes{'spares'}}) > 0) {
18199:                     $savespares = 1;
18200:                 }
18201:             }
18202:         } else {
18203:             $savespares = 1;
18204:         }
18205:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
18206:             foreach my $lonhost (keys(%{$domconfig{'usersessions'}{'offloadnow'}})) {
18207:                 unless ($defaultshash{'usersessions'}{'offloadnow'}{$lonhost}) {
18208:                     $changes{'offloadnow'} = 1;
18209:                     last;
18210:                 }
18211:             }
18212:             unless ($changes{'offloadnow'}) {
18213:                 foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{'offloadnow'}})) {
18214:                     unless ($domconfig{'usersessions'}{'offloadnow'}{$lonhost}) {
18215:                         $changes{'offloadnow'} = 1;
18216:                         last;
18217:                     }
18218:                 }
18219:             }
18220:         } elsif (@okoffload) {
18221:             $changes{'offloadnow'} = 1;
18222:         }
18223:     } elsif (@okoffload) {
18224:         $changes{'offloadnow'} = 1;
18225:     }
18226:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
18227:     if ((keys(%changes) > 0) || ($savespares)) {
18228:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
18229:                                                  $dom);
18230:         if ($putresult eq 'ok') {
18231:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
18232:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
18233:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
18234:                 }
18235:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
18236:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
18237:                 }
18238:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
18239:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
18240:                 }
18241:             }
18242:             my $cachetime = 24*60*60;
18243:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18244:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
18245:             if (ref($lastactref) eq 'HASH') {
18246:                 $lastactref->{'domdefaults'} = 1;
18247:                 $lastactref->{'usersessions'} = 1;
18248:             }
18249:             if (keys(%changes) > 0) {
18250:                 my %lt = &usersession_titles();
18251:                 $resulttext = &mt('Changes made:').'<ul>';
18252:                 foreach my $prefix (@prefixes) {
18253:                     if (ref($changes{$prefix}) eq 'HASH') {
18254:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
18255:                         if ($prefix eq 'spares') {
18256:                             if (ref($changes{$prefix}) eq 'HASH') {
18257:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
18258:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
18259:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
18260:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
18261:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
18262:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
18263:                                         foreach my $type (@{$types{$prefix}}) {
18264:                                             if ($changes{$prefix}{$lonhost}{$type}) {
18265:                                                 my $offloadto = &mt('None');
18266:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
18267:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
18268:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
18269:                                                     }
18270:                                                 }
18271:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
18272:                                             }
18273:                                         }
18274:                                     }
18275:                                     $resulttext .= '</li>';
18276:                                 }
18277:                             }
18278:                         } else {
18279:                             foreach my $type (@{$types{$prefix}}) {
18280:                                 if (defined($changes{$prefix}{$type})) {
18281:                                     my ($newvalue,$notinuse);
18282:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
18283:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
18284:                                             if ($type eq 'version') {
18285:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
18286:                                             } else {
18287:                                                 if (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
18288:                                                     if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
18289:                                                         $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
18290:                                                     }
18291:                                                 } else {
18292:                                                     $notinuse = 1;
18293:                                                 }
18294:                                             }
18295:                                         }
18296:                                     }
18297:                                     if ($newvalue eq '') {
18298:                                         if ($type eq 'version') {
18299:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
18300:                                         } elsif ($notinuse) {
18301:                                             $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
18302:                                         } else {
18303:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
18304:                                         }
18305:                                     } else {
18306:                                         if ($type eq 'version') {
18307:                                             $newvalue .= ' '.&mt('(or later)');
18308:                                         }
18309:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
18310:                                     }
18311:                                 }
18312:                             }
18313:                         }
18314:                         $resulttext .= '</ul>';
18315:                     }
18316:                 }
18317:                 if ($changes{'offloadnow'}) {
18318:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
18319:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
18320:                             $resulttext .= '<li>'.&mt('Switch active users on next access, for server(s):').'<ul>';
18321:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
18322:                                 $resulttext .= '<li>'.$lonhost.'</li>';
18323:                             }
18324:                             $resulttext .= '</ul>';
18325:                         } else {
18326:                             $resulttext .= '<li>'.&mt('No servers now set to switch active users on next access.');
18327:                         }
18328:                     } else {
18329:                         $resulttext .= '<li>'.&mt('No servers now set to switch active users on next access.').'</li>';
18330:                     }
18331:                 }
18332:                 $resulttext .= '</ul>';
18333:             } else {
18334:                 $resulttext = $nochgmsg;
18335:             }
18336:         } else {
18337:             $resulttext = '<span class="LC_error">'.
18338:                           &mt('An error occurred: [_1]',$putresult).'</span>';
18339:         }
18340:     } else {
18341:         $resulttext = $nochgmsg;
18342:     }
18343:     return $resulttext;
18344: }
18345: 
18346: sub modify_ssl {
18347:     my ($dom,$lastactref,%domconfig) = @_;
18348:     my (%by_ip,%by_location,@intdoms,@instdoms);
18349:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
18350:     my @locations = sort(keys(%by_location));
18351:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
18352:     my (%defaultshash,%changes);
18353:     my $action = 'ssl';
18354:     my @prefixes = ('connto','connfrom','replication');
18355:     foreach my $prefix (@prefixes) {
18356:         $defaultshash{$action}{$prefix} = {};
18357:     }
18358:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18359:     my $resulttext;
18360:     my %iphost = &Apache::lonnet::get_iphost();
18361:     my @reptypes = ('certreq','nocertreq');
18362:     my @connecttypes = ('dom','intdom','other');
18363:     my %types = (
18364:                   connto      => \@connecttypes,
18365:                   connfrom    => \@connecttypes,
18366:                   replication => \@reptypes,
18367:                 );
18368:     foreach my $prefix (sort(keys(%types))) {
18369:         foreach my $type (@{$types{$prefix}}) {
18370:             if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
18371:                 my $value = 'yes';
18372:                 if ($env{'form.'.$prefix.'_'.$type} =~ /^(no|req)$/) {
18373:                     $value = $env{'form.'.$prefix.'_'.$type};
18374:                 }
18375:                 if (ref($domconfig{$action}) eq 'HASH') {
18376:                     if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
18377:                         if ($domconfig{$action}{$prefix}{$type} ne '') {
18378:                             if ($value ne $domconfig{$action}{$prefix}{$type}) {
18379:                                 $changes{$prefix}{$type} = 1;
18380:                             }
18381:                             $defaultshash{$action}{$prefix}{$type} = $value;
18382:                         } else {
18383:                             $defaultshash{$action}{$prefix}{$type} = $value;
18384:                             $changes{$prefix}{$type} = 1;
18385:                         }
18386:                     } else {
18387:                         $defaultshash{$action}{$prefix}{$type} = $value;
18388:                         $changes{$prefix}{$type} = 1;
18389:                     }
18390:                 } else {
18391:                     $defaultshash{$action}{$prefix}{$type} = $value;
18392:                     $changes{$prefix}{$type} = 1;
18393:                 }
18394:                 if (($type eq 'dom') && (keys(%servers) == 1)) {
18395:                     delete($changes{$prefix}{$type});
18396:                 } elsif (($type eq 'intdom') && (@instdoms == 1)) {
18397:                     delete($changes{$prefix}{$type});
18398:                 } elsif (($type eq 'other') && (keys(%by_location) == 0)) { 
18399:                     delete($changes{$prefix}{$type});
18400:                 }
18401:             } elsif ($prefix eq 'replication') {
18402:                 if (@locations > 0) {
18403:                     my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
18404:                     my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
18405:                     my @okvals;
18406:                     foreach my $val (@vals) {
18407:                         if ($val =~ /:/) {
18408:                             my @items = split(/:/,$val);
18409:                             foreach my $item (@items) {
18410:                                 if (ref($by_location{$item}) eq 'ARRAY') {
18411:                                     push(@okvals,$item);
18412:                                 }
18413:                             }
18414:                         } else {
18415:                             if (ref($by_location{$val}) eq 'ARRAY') {
18416:                                 push(@okvals,$val);
18417:                             }
18418:                         }
18419:                     }
18420:                     @okvals = sort(@okvals);
18421:                     if (ref($domconfig{$action}) eq 'HASH') {
18422:                         if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
18423:                             if (ref($domconfig{$action}{$prefix}{$type}) eq 'ARRAY') {
18424:                                 if ($inuse == 0) {
18425:                                     $changes{$prefix}{$type} = 1;
18426:                                 } else {
18427:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
18428:                                     my @changed = &Apache::loncommon::compare_arrays($domconfig{$action}{$prefix}{$type},$defaultshash{$action}{$prefix}{$type});
18429:                                     if (@changed > 0) {
18430:                                         $changes{$prefix}{$type} = 1;
18431:                                     }
18432:                                 }
18433:                             } else {
18434:                                 if ($inuse == 1) {
18435:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
18436:                                     $changes{$prefix}{$type} = 1;
18437:                                 }
18438:                             }
18439:                         } else {
18440:                             if ($inuse == 1) {
18441:                                 $defaultshash{$action}{$prefix}{$type} = \@okvals;
18442:                                 $changes{$prefix}{$type} = 1;
18443:                             }
18444:                         }
18445:                     } else {
18446:                         if ($inuse == 1) {
18447:                             $defaultshash{$action}{$prefix}{$type} = \@okvals;
18448:                             $changes{$prefix}{$type} = 1;
18449:                         }
18450:                     }
18451:                 }
18452:             }
18453:         }
18454:     }
18455:     if (keys(%changes)) {
18456:         foreach my $prefix (keys(%changes)) {
18457:             if (ref($changes{$prefix}) eq 'HASH') {
18458:                 if (scalar(keys(%{$changes{$prefix}})) == 0) {
18459:                     delete($changes{$prefix});
18460:                 }
18461:             } else {
18462:                 delete($changes{$prefix});
18463:             }
18464:         }
18465:     }
18466:     my $nochgmsg = &mt('No changes made to LON-CAPA SSL settings');
18467:     if (keys(%changes) > 0) {
18468:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
18469:                                                  $dom);
18470:         if ($putresult eq 'ok') {
18471:             if (ref($defaultshash{$action}) eq 'HASH') {
18472:                 if (ref($defaultshash{$action}{'replication'}) eq 'HASH') {
18473:                     $domdefaults{'replication'} = $defaultshash{$action}{'replication'};
18474:                 }
18475:                 if (ref($defaultshash{$action}{'connto'}) eq 'HASH') {
18476:                     $domdefaults{'connto'} = $defaultshash{$action}{'connto'};
18477:                 }
18478:                 if (ref($defaultshash{$action}{'connfrom'}) eq 'HASH') {
18479:                     $domdefaults{'connfrom'} = $defaultshash{$action}{'connfrom'};
18480:                 }
18481:             }
18482:             my $cachetime = 24*60*60;
18483:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18484:             if (ref($lastactref) eq 'HASH') {
18485:                 $lastactref->{'domdefaults'} = 1;
18486:             }
18487:             if (keys(%changes) > 0) {
18488:                 my %titles = &ssl_titles();
18489:                 $resulttext = &mt('Changes made:').'<ul>';
18490:                 foreach my $prefix (@prefixes) {
18491:                     if (ref($changes{$prefix}) eq 'HASH') {
18492:                         $resulttext .= '<li>'.$titles{$prefix}.'<ul>';
18493:                         foreach my $type (@{$types{$prefix}}) {
18494:                             if (defined($changes{$prefix}{$type})) {
18495:                                 my ($newvalue,$notinuse);
18496:                                 if (ref($defaultshash{$action}) eq 'HASH') {
18497:                                     if (ref($defaultshash{$action}{$prefix})) {
18498:                                         if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
18499:                                             $newvalue = $titles{$defaultshash{$action}{$prefix}{$type}};
18500:                                         } else {
18501:                                             if (ref($defaultshash{$action}{$prefix}{$type}) eq 'ARRAY') {
18502:                                                 if (@{$defaultshash{$action}{$prefix}{$type}} > 0) {
18503:                                                     $newvalue = join(', ',@{$defaultshash{$action}{$prefix}{$type}});
18504:                                                 }
18505:                                             } else {
18506:                                                 $notinuse = 1;
18507:                                             }
18508:                                         }
18509:                                     }
18510:                                     if ($notinuse) {
18511:                                         $resulttext .= '<li>'.&mt('[_1] set to: not in use',$titles{$type}).'</li>';
18512:                                     } elsif ($newvalue eq '') {
18513:                                         $resulttext .= '<li>'.&mt('[_1] set to: none',$titles{$type}).'</li>';
18514:                                     } else {
18515:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$titles{$type},$newvalue).'</li>';
18516:                                     }
18517:                                 }
18518:                             }
18519:                         }
18520:                         $resulttext .= '</ul>';
18521:                     }
18522:                 }
18523:             } else {
18524:                 $resulttext = $nochgmsg;
18525:             }
18526:         } else {
18527:             $resulttext = '<span class="LC_error">'.
18528:                           &mt('An error occurred: [_1]',$putresult).'</span>';
18529:         }
18530:     } else {
18531:         $resulttext = $nochgmsg;
18532:     }
18533:     return $resulttext;
18534: }
18535: 
18536: sub modify_trust {
18537:     my ($dom,$lastactref,%domconfig) = @_;
18538:     my (%by_ip,%by_location,@intdoms,@instdoms);
18539:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
18540:     my @locations = sort(keys(%by_location));
18541:     my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
18542:     my @types = ('exc','inc');
18543:     my (%defaultshash,%changes);
18544:     foreach my $prefix (@prefixes) {
18545:         $defaultshash{'trust'}{$prefix} = {};
18546:     }
18547:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18548:     my $resulttext;
18549:     foreach my $prefix (@prefixes) {
18550:         foreach my $type (@types) {
18551:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
18552:             my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
18553:             my @okvals;
18554:             foreach my $val (@vals) {
18555:                 if ($val =~ /:/) {
18556:                     my @items = split(/:/,$val);
18557:                     foreach my $item (@items) {
18558:                         if (ref($by_location{$item}) eq 'ARRAY') {
18559:                             push(@okvals,$item);
18560:                         }
18561:                     }
18562:                 } else {
18563:                     if (ref($by_location{$val}) eq 'ARRAY') {
18564:                         push(@okvals,$val);
18565:                     }
18566:                 }
18567:             }
18568:             @okvals = sort(@okvals);
18569:             if (ref($domconfig{'trust'}) eq 'HASH') {
18570:                 if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
18571:                     if (ref($domconfig{'trust'}{$prefix}{$type}) eq 'ARRAY') {
18572:                         if ($inuse == 0) {
18573:                             $changes{$prefix}{$type} = 1;
18574:                         } else {
18575:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
18576:                             my @changed = &Apache::loncommon::compare_arrays($domconfig{'trust'}{$prefix}{$type},$defaultshash{'trust'}{$prefix}{$type});
18577:                             if (@changed > 0) {
18578:                                 $changes{$prefix}{$type} = 1;
18579:                             }
18580:                         }
18581:                     } else {
18582:                         if ($inuse == 1) {
18583:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
18584:                             $changes{$prefix}{$type} = 1;
18585:                         }
18586:                     }
18587:                 } else {
18588:                     if ($inuse == 1) {
18589:                         $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
18590:                         $changes{$prefix}{$type} = 1;
18591:                     }
18592:                 }
18593:             } else {
18594:                 if ($inuse == 1) {
18595:                     $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
18596:                     $changes{$prefix}{$type} = 1;
18597:                 }
18598:             }
18599:         }
18600:     }
18601:     my $nochgmsg = &mt('No changes made to trust settings.');
18602:     if (keys(%changes) > 0) {
18603:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
18604:                                                  $dom);
18605:         if ($putresult eq 'ok') {
18606:             if (ref($defaultshash{'trust'}) eq 'HASH') {
18607:                 foreach my $prefix (@prefixes) {
18608:                     if (ref($defaultshash{'trust'}{$prefix}) eq 'HASH') {
18609:                         $domdefaults{'trust'.$prefix} = $defaultshash{'trust'}{$prefix};
18610:                     }
18611:                 }
18612:             }
18613:             my $cachetime = 24*60*60;
18614:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18615:             if (ref($lastactref) eq 'HASH') {
18616:                 $lastactref->{'domdefaults'} = 1;
18617:             }
18618:             if (keys(%changes) > 0) {
18619:                 my %lt = &trust_titles();
18620:                 $resulttext = &mt('Changes made:').'<ul>';
18621:                 foreach my $prefix (@prefixes) {
18622:                     if (ref($changes{$prefix}) eq 'HASH') {
18623:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
18624:                         foreach my $type (@types) {
18625:                             if (defined($changes{$prefix}{$type})) {
18626:                                 my ($newvalue,$notinuse);
18627:                                 if (ref($defaultshash{'trust'}) eq 'HASH') {
18628:                                     if (ref($defaultshash{'trust'}{$prefix})) {
18629:                                         if (ref($defaultshash{'trust'}{$prefix}{$type}) eq 'ARRAY') {
18630:                                             if (@{$defaultshash{'trust'}{$prefix}{$type}} > 0) {
18631:                                                 $newvalue = join(', ',@{$defaultshash{'trust'}{$prefix}{$type}});
18632:                                             }
18633:                                         } else {
18634:                                             $notinuse = 1;
18635:                                         }
18636:                                     }
18637:                                 }
18638:                                 if ($notinuse) {
18639:                                     $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
18640:                                 } elsif ($newvalue eq '') {
18641:                                     $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
18642:                                 } else {
18643:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
18644:                                 }
18645:                             }
18646:                         }
18647:                         $resulttext .= '</ul>';
18648:                     }
18649:                 }
18650:                 $resulttext .= '</ul>';
18651:             } else {
18652:                 $resulttext = $nochgmsg;
18653:             }
18654:         } else {
18655:             $resulttext = '<span class="LC_error">'.
18656:                           &mt('An error occurred: [_1]',$putresult).'</span>';
18657:         }
18658:     } else {
18659:         $resulttext = $nochgmsg;
18660:     }
18661:     return $resulttext;
18662: }
18663: 
18664: sub modify_loadbalancing {
18665:     my ($dom,%domconfig) = @_;
18666:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
18667:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
18668:     my ($othertitle,$usertypes,$types) =
18669:         &Apache::loncommon::sorted_inst_types($dom);
18670:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
18671:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
18672:     my @sparestypes = ('primary','default');
18673:     my %typetitles = &sparestype_titles();
18674:     my $resulttext;
18675:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
18676:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
18677:         %existing = %{$domconfig{'loadbalancing'}};
18678:     }
18679:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
18680:                               \%currtargets,\%currrules,\%currcookies);
18681:     my ($saveloadbalancing,%defaultshash,%changes);
18682:     my ($alltypes,$othertypes,$titles) =
18683:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
18684:     my %ruletitles = &offloadtype_text();
18685:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
18686:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
18687:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
18688:         if ($balancer eq '') {
18689:             next;
18690:         }
18691:         if (!exists($servers{$balancer})) {
18692:             if (exists($currbalancer{$balancer})) {
18693:                 push(@{$changes{'delete'}},$balancer);
18694:             }
18695:             next;
18696:         }
18697:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
18698:             push(@{$changes{'delete'}},$balancer);
18699:             next;
18700:         }
18701:         if (!exists($currbalancer{$balancer})) {
18702:             push(@{$changes{'add'}},$balancer);
18703:         }
18704:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
18705:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
18706:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
18707:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
18708:             $saveloadbalancing = 1;
18709:         }
18710:         foreach my $sparetype (@sparestypes) {
18711:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
18712:             my @offloadto;
18713:             foreach my $target (@targets) {
18714:                 if (($servers{$target}) && ($target ne $balancer)) {
18715:                     if ($sparetype eq 'default') {
18716:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
18717:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
18718:                         }
18719:                     }
18720:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
18721:                         push(@offloadto,$target);
18722:                     }
18723:                 }
18724:             }
18725:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
18726:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
18727:                     push(@offloadto,$balancer);
18728:                 }
18729:             }
18730:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
18731:         }
18732:         if ($env{'form.loadbalancing_cookie_'.$i}) {
18733:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
18734:             if (exists($currbalancer{$balancer})) { 
18735:                 unless ($currcookies{$balancer}) {
18736:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
18737:                 }
18738:             }
18739:         } elsif (exists($currbalancer{$balancer})) {
18740:             if ($currcookies{$balancer}) {
18741:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
18742:             }
18743:         }
18744:         if (ref($currtargets{$balancer}) eq 'HASH') {
18745:             foreach my $sparetype (@sparestypes) {
18746:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
18747:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
18748:                     if (@targetdiffs > 0) {
18749:                         $changes{'curr'}{$balancer}{'targets'} = 1;
18750:                     }
18751:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
18752:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
18753:                         $changes{'curr'}{$balancer}{'targets'} = 1;
18754:                     }
18755:                 }
18756:             }
18757:         } else {
18758:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
18759:                 foreach my $sparetype (@sparestypes) {
18760:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
18761:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
18762:                             $changes{'curr'}{$balancer}{'targets'} = 1;
18763:                         }
18764:                     }
18765:                 }
18766:             }
18767:         }
18768:         my $ishomedom;
18769:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
18770:             $ishomedom = 1;
18771:         }
18772:         if (ref($alltypes) eq 'ARRAY') {
18773:             foreach my $type (@{$alltypes}) {
18774:                 my $rule;
18775:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
18776:                          (!$ishomedom)) {
18777:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
18778:                 }
18779:                 if ($rule eq 'specific') {
18780:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
18781:                     if (exists($servers{$specifiedhost})) {
18782:                         $rule = $specifiedhost;
18783:                     }
18784:                 }
18785:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
18786:                 if (ref($currrules{$balancer}) eq 'HASH') {
18787:                     if ($rule ne $currrules{$balancer}{$type}) {
18788:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
18789:                     }
18790:                 } elsif ($rule ne '') {
18791:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
18792:                 }
18793:             }
18794:         }
18795:     }
18796:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
18797:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
18798:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
18799:             $defaultshash{'loadbalancing'} = {};
18800:         }
18801:         my $putresult = &Apache::lonnet::put_dom('configuration',
18802:                                                  \%defaultshash,$dom);
18803:         if ($putresult eq 'ok') {
18804:             if (keys(%changes) > 0) {
18805:                 my %toupdate;
18806:                 if (ref($changes{'delete'}) eq 'ARRAY') {
18807:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
18808:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
18809:                         $toupdate{$balancer} = 1;
18810:                     }
18811:                 }
18812:                 if (ref($changes{'add'}) eq 'ARRAY') {
18813:                     foreach my $balancer (sort(@{$changes{'add'}})) {
18814:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
18815:                         $toupdate{$balancer} = 1;
18816:                     }
18817:                 }
18818:                 if (ref($changes{'curr'}) eq 'HASH') {
18819:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
18820:                         $toupdate{$balancer} = 1;
18821:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
18822:                             if ($changes{'curr'}{$balancer}{'targets'}) {
18823:                                 my %offloadstr;
18824:                                 foreach my $sparetype (@sparestypes) {
18825:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
18826:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
18827:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
18828:                                         }
18829:                                     }
18830:                                 }
18831:                                 if (keys(%offloadstr) == 0) {
18832:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
18833:                                 } else {
18834:                                     my $showoffload;
18835:                                     foreach my $sparetype (@sparestypes) {
18836:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
18837:                                         if (defined($offloadstr{$sparetype})) {
18838:                                             $showoffload .= $offloadstr{$sparetype};
18839:                                         } else {
18840:                                             $showoffload .= &mt('None');
18841:                                         }
18842:                                         $showoffload .= ('&nbsp;'x3);
18843:                                     }
18844:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
18845:                                 }
18846:                             }
18847:                         }
18848:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
18849:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
18850:                                 foreach my $type (@{$alltypes}) {
18851:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
18852:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
18853:                                         my $balancetext;
18854:                                         if ($rule eq '') {
18855:                                             $balancetext =  $ruletitles{'default'};
18856:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
18857:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
18858:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
18859:                                                 foreach my $sparetype (@sparestypes) {
18860:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
18861:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
18862:                                                     }
18863:                                                 }
18864:                                                 foreach my $item (@{$alltypes}) {
18865:                                                     next if ($item =~  /^_LC_ipchange/);
18866:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
18867:                                                     if ($hasrule eq 'homeserver') {
18868:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
18869:                                                     } else {
18870:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
18871:                                                             if ($servers{$hasrule}) {
18872:                                                                 $toupdate{$hasrule} = 1;
18873:                                                             }
18874:                                                         }
18875:                                                     }
18876:                                                 }
18877:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
18878:                                                     $balancetext =  $ruletitles{$rule};
18879:                                                 } else {
18880:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
18881:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
18882:                                                     if ($receiver) {
18883:                                                         $toupdate{$receiver};
18884:                                                     }
18885:                                                 }
18886:                                             } else {
18887:                                                 $balancetext =  $ruletitles{$rule};
18888:                                             }
18889:                                         } else {
18890:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
18891:                                         }
18892:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
18893:                                     }
18894:                                 }
18895:                             }
18896:                         }
18897:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
18898:                             $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
18899:                                                       $balancer).'</li>'; 
18900:                         }
18901:                         if (keys(%toupdate)) {
18902:                             my %thismachine;
18903:                             my $updatedhere;
18904:                             my $cachetime = 60*60*24;
18905:                             map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
18906:                             foreach my $lonhost (keys(%toupdate)) {
18907:                                 if ($thismachine{$lonhost}) {
18908:                                     unless ($updatedhere) {
18909:                                         &Apache::lonnet::do_cache_new('loadbalancing',$dom,
18910:                                                                       $defaultshash{'loadbalancing'},
18911:                                                                       $cachetime);
18912:                                         $updatedhere = 1;
18913:                                     }
18914:                                 } else {
18915:                                     my $cachekey = &escape('loadbalancing').':'.&escape($dom);
18916:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
18917:                                 }
18918:                             }
18919:                         }
18920:                     }
18921:                 }
18922:                 if ($resulttext ne '') {
18923:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
18924:                 } else {
18925:                     $resulttext = $nochgmsg;
18926:                 }
18927:             } else {
18928:                 $resulttext = $nochgmsg;
18929:             }
18930:         } else {
18931:             $resulttext = '<span class="LC_error">'.
18932:                           &mt('An error occurred: [_1]',$putresult).'</span>';
18933:         }
18934:     } else {
18935:         $resulttext = $nochgmsg;
18936:     }
18937:     return $resulttext;
18938: }
18939: 
18940: sub recurse_check {
18941:     my ($chkcats,$categories,$depth,$name) = @_;
18942:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
18943:         my $chg = 0;
18944:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
18945:             my $category = $chkcats->[$depth]{$name}[$j];
18946:             my $item;
18947:             if ($category eq '') {
18948:                 $chg ++;
18949:             } else {
18950:                 my $deeper = $depth + 1;
18951:                 $item = &escape($category).':'.&escape($name).':'.$depth;
18952:                 if ($chg) {
18953:                     $categories->{$item} -= $chg;
18954:                 }
18955:                 &recurse_check($chkcats,$categories,$deeper,$category);
18956:                 $deeper --;
18957:             }
18958:         }
18959:     }
18960:     return;
18961: }
18962: 
18963: sub recurse_cat_deletes {
18964:     my ($item,$coursecategories,$deletions) = @_;
18965:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
18966:     my $subdepth = $depth + 1;
18967:     if (ref($coursecategories) eq 'HASH') {
18968:         foreach my $subitem (keys(%{$coursecategories})) {
18969:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
18970:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
18971:                 delete($coursecategories->{$subitem});
18972:                 $deletions->{$subitem} = 1;
18973:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
18974:             }
18975:         }
18976:     }
18977:     return;
18978: }
18979: 
18980: sub active_dc_picker {
18981:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
18982:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
18983:     my @domcoord = keys(%domcoords);
18984:     if (keys(%currhash)) {
18985:         foreach my $dc (keys(%currhash)) {
18986:             unless (exists($domcoords{$dc})) {
18987:                 push(@domcoord,$dc);
18988:             }
18989:         }
18990:     }
18991:     @domcoord = sort(@domcoord);
18992:     my $numdcs = scalar(@domcoord);
18993:     my $rows = 0;
18994:     my $table;
18995:     if ($numdcs > 1) {
18996:         $table = '<table>';
18997:         for (my $i=0; $i<@domcoord; $i++) {
18998:             my $rem = $i%($numinrow);
18999:             if ($rem == 0) {
19000:                 if ($i > 0) {
19001:                     $table .= '</tr>';
19002:                 }
19003:                 $table .= '<tr>';
19004:                 $rows ++;
19005:             }
19006:             my $check = '';
19007:             if ($inputtype eq 'radio') {
19008:                 if (keys(%currhash) == 0) {
19009:                     if (!$i) {
19010:                         $check = ' checked="checked"';
19011:                     }
19012:                 } elsif (exists($currhash{$domcoord[$i]})) {
19013:                     $check = ' checked="checked"';
19014:                 }
19015:             } else {
19016:                 if (exists($currhash{$domcoord[$i]})) {
19017:                     $check = ' checked="checked"';
19018:                 }
19019:             }
19020:             if ($i == @domcoord - 1) {
19021:                 my $colsleft = $numinrow - $rem;
19022:                 if ($colsleft > 1) {
19023:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
19024:                 } else {
19025:                     $table .= '<td class="LC_left_item">';
19026:                 }
19027:             } else {
19028:                 $table .= '<td class="LC_left_item">';
19029:             }
19030:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
19031:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
19032:             $table .= '<span class="LC_nobreak"><label>'.
19033:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
19034:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
19035:             if ($user ne $dcname.':'.$dcdom) {
19036:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
19037:             }
19038:             $table .= '</label></span></td>';
19039:         }
19040:         $table .= '</tr></table>';
19041:     } elsif ($numdcs == 1) {
19042:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
19043:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
19044:         if ($inputtype eq 'radio') {
19045:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
19046:             if ($user ne $dcname.':'.$dcdom) {
19047:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
19048:             }
19049:         } else {
19050:             my $check;
19051:             if (exists($currhash{$domcoord[0]})) {
19052:                 $check = ' checked="checked"';
19053:             }
19054:             $table = '<span class="LC_nobreak"><label>'.
19055:                      '<input type="checkbox" name="'.$name.'" '.
19056:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
19057:             if ($user ne $dcname.':'.$dcdom) {
19058:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
19059:             }
19060:             $table .= '</label></span>';
19061:             $rows ++;
19062:         }
19063:     }
19064:     return ($numdcs,$table,$rows);
19065: }
19066: 
19067: sub usersession_titles {
19068:     return &Apache::lonlocal::texthash(
19069:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
19070:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
19071:                spares => 'Servers offloaded to, when busy',
19072:                version => 'LON-CAPA version requirement',
19073:                excludedomain => 'Allow all, but exclude specific domains',
19074:                includedomain => 'Deny all, but include specific domains',
19075:                primary => 'Primary (checked first)',
19076:                default => 'Default',
19077:            );
19078: }
19079: 
19080: sub id_for_thisdom {
19081:     my (%servers) = @_;
19082:     my %altids;
19083:     foreach my $server (keys(%servers)) {
19084:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
19085:         if ($serverhome ne $server) {
19086:             $altids{$serverhome} = $server;
19087:         }
19088:     }
19089:     return %altids;
19090: }
19091: 
19092: sub count_servers {
19093:     my ($currbalancer,%servers) = @_;
19094:     my (@spares,$numspares);
19095:     foreach my $lonhost (sort(keys(%servers))) {
19096:         next if ($currbalancer eq $lonhost);
19097:         push(@spares,$lonhost);
19098:     }
19099:     if ($currbalancer) {
19100:         $numspares = scalar(@spares);
19101:     } else {
19102:         $numspares = scalar(@spares) - 1;
19103:     }
19104:     return ($numspares,@spares);
19105: }
19106: 
19107: sub lonbalance_targets_js {
19108:     my ($dom,$types,$servers,$settings) = @_;
19109:     my $select = &mt('Select');
19110:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
19111:     if (ref($servers) eq 'HASH') {
19112:         $alltargets = join("','",sort(keys(%{$servers})));
19113:         my @homedoms;
19114:         foreach my $server (sort(keys(%{$servers}))) {
19115:             if (&Apache::lonnet::host_domain($server) eq $dom) {
19116:                 push(@homedoms,'1');
19117:             } else {
19118:                 push(@homedoms,'0');
19119:             }
19120:         }
19121:         $allishome = join("','",@homedoms);
19122:     }
19123:     if (ref($types) eq 'ARRAY') {
19124:         if (@{$types} > 0) {
19125:             @alltypes = @{$types};
19126:         }
19127:     }
19128:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
19129:     $allinsttypes = join("','",@alltypes);
19130:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
19131:     if (ref($settings) eq 'HASH') {
19132:         %existing = %{$settings};
19133:     }
19134:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
19135:                               \%currtargets,\%currrules,\%currcookies);
19136:     my $balancers = join("','",sort(keys(%currbalancer)));
19137:     return <<"END";
19138: 
19139: <script type="text/javascript">
19140: // <![CDATA[
19141: 
19142: currBalancers = new Array('$balancers');
19143: 
19144: function toggleTargets(balnum) {
19145:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
19146:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
19147:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
19148:     var prevbalancer = prevhostitem.value;
19149:     var baltotal = document.getElementById('loadbalancing_total').value;
19150:     prevhostitem.value = balancer;
19151:     if (prevbalancer != '') {
19152:         var prevIdx = currBalancers.indexOf(prevbalancer);
19153:         if (prevIdx != -1) {
19154:             currBalancers.splice(prevIdx,1);
19155:         }
19156:     }
19157:     if (balancer == '') {
19158:         hideSpares(balnum);
19159:     } else {
19160:         var currIdx = currBalancers.indexOf(balancer);
19161:         if (currIdx == -1) {
19162:             currBalancers.push(balancer);
19163:         }
19164:         var homedoms = new Array('$allishome');
19165:         var ishomedom = homedoms[lonhostitem.selectedIndex];
19166:         showSpares(balancer,ishomedom,balnum);
19167:     }
19168:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
19169:     return;
19170: }
19171: 
19172: function showSpares(balancer,ishomedom,balnum) {
19173:     var alltargets = new Array('$alltargets');
19174:     var insttypes = new Array('$allinsttypes');
19175:     var offloadtypes = new Array('primary','default');
19176: 
19177:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
19178:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
19179:  
19180:     for (var i=0; i<offloadtypes.length; i++) {
19181:         var count = 0;
19182:         for (var j=0; j<alltargets.length; j++) {
19183:             if (alltargets[j] != balancer) {
19184:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
19185:                 item.value = alltargets[j];
19186:                 item.style.textAlign='left';
19187:                 item.style.textFace='normal';
19188:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
19189:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
19190:                     item.disabled = '';
19191:                 } else {
19192:                     item.disabled = 'disabled';
19193:                     item.checked = false;
19194:                 }
19195:                 count ++;
19196:             }
19197:         }
19198:     }
19199:     for (var k=0; k<insttypes.length; k++) {
19200:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
19201:             if (ishomedom == 1) {
19202:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
19203:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
19204:             } else {
19205:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
19206:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
19207:             }
19208:         } else {
19209:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
19210:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
19211:         }
19212:         if ((insttypes[k] != '_LC_external') && 
19213:             ((insttypes[k] != '_LC_internetdom') ||
19214:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
19215:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
19216:             item.options.length = 0;
19217:             item.options[0] = new Option("","",true,true);
19218:             var idx = 0;
19219:             for (var m=0; m<alltargets.length; m++) {
19220:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
19221:                     idx ++;
19222:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
19223:                 }
19224:             }
19225:         }
19226:     }
19227:     return;
19228: }
19229: 
19230: function hideSpares(balnum) {
19231:     var alltargets = new Array('$alltargets');
19232:     var insttypes = new Array('$allinsttypes');
19233:     var offloadtypes = new Array('primary','default');
19234: 
19235:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
19236:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
19237: 
19238:     var total = alltargets.length - 1;
19239:     for (var i=0; i<offloadtypes; i++) {
19240:         for (var j=0; j<total; j++) {
19241:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
19242:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
19243:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
19244:         }
19245:     }
19246:     for (var k=0; k<insttypes.length; k++) {
19247:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
19248:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
19249:         if (insttypes[k] != '_LC_external') {
19250:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
19251:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
19252:         }
19253:     }
19254:     return;
19255: }
19256: 
19257: function checkOffloads(item,balnum,type) {
19258:     var alltargets = new Array('$alltargets');
19259:     var offloadtypes = new Array('primary','default');
19260:     if (item.checked) {
19261:         var total = alltargets.length - 1;
19262:         var other;
19263:         if (type == offloadtypes[0]) {
19264:             other = offloadtypes[1];
19265:         } else {
19266:             other = offloadtypes[0];
19267:         }
19268:         for (var i=0; i<total; i++) {
19269:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
19270:             if (server == item.value) {
19271:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
19272:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
19273:                 }
19274:             }
19275:         }
19276:     }
19277:     return;
19278: }
19279: 
19280: function singleServerToggle(balnum,type) {
19281:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
19282:     if (offloadtoSelIdx == 0) {
19283:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
19284:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
19285: 
19286:     } else {
19287:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
19288:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
19289:     }
19290:     return;
19291: }
19292: 
19293: function balanceruleChange(formname,balnum,type) {
19294:     if (type == '_LC_external') {
19295:         return;
19296:     }
19297:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
19298:     for (var i=0; i<typesRules.length; i++) {
19299:         if (formname.elements[typesRules[i]].checked) {
19300:             if (formname.elements[typesRules[i]].value != 'specific') {
19301:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
19302:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
19303:             } else {
19304:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
19305:             }
19306:         }
19307:     }
19308:     return;
19309: }
19310: 
19311: function balancerDeleteChange(balnum) {
19312:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
19313:     var baltotal = document.getElementById('loadbalancing_total').value;
19314:     var addtarget;
19315:     var removetarget;
19316:     var action = 'delete';
19317:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
19318:         var lonhost = hostitem.value;
19319:         var currIdx = currBalancers.indexOf(lonhost);
19320:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
19321:             if (currIdx != -1) {
19322:                 currBalancers.splice(currIdx,1);
19323:             }
19324:             addtarget = lonhost;
19325:         } else {
19326:             if (currIdx == -1) {
19327:                 currBalancers.push(lonhost);
19328:             }
19329:             removetarget = lonhost;
19330:             action = 'undelete';
19331:         }
19332:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
19333:     }
19334:     return;
19335: }
19336: 
19337: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
19338:     if (baltotal > 1) {
19339:         var offloadtypes = new Array('primary','default');
19340:         var alltargets = new Array('$alltargets');
19341:         var insttypes = new Array('$allinsttypes');
19342:         for (var i=0; i<baltotal; i++) {
19343:             if (i != balnum) {
19344:                 for (var j=0; j<offloadtypes.length; j++) {
19345:                     var total = alltargets.length - 1;
19346:                     for (var k=0; k<total; k++) {
19347:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
19348:                         var server = serveritem.value;
19349:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
19350:                             if (server == addtarget) {
19351:                                 serveritem.disabled = '';
19352:                             }
19353:                         }
19354:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
19355:                             if (server == removetarget) {
19356:                                 serveritem.disabled = 'disabled';
19357:                                 serveritem.checked = false;
19358:                             }
19359:                         }
19360:                     }
19361:                 }
19362:                 for (var j=0; j<insttypes.length; j++) {
19363:                     if (insttypes[j] != '_LC_external') {
19364:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
19365:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
19366:                             var currSel = singleserver.selectedIndex;
19367:                             var currVal = singleserver.options[currSel].value;
19368:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
19369:                                 var numoptions = singleserver.options.length;
19370:                                 var needsnew = 1;
19371:                                 for (var k=0; k<numoptions; k++) {
19372:                                     if (singleserver.options[k] == addtarget) {
19373:                                         needsnew = 0;
19374:                                         break;
19375:                                     }
19376:                                 }
19377:                                 if (needsnew == 1) {
19378:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
19379:                                 }
19380:                             }
19381:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
19382:                                 singleserver.options.length = 0;
19383:                                 if ((currVal) && (currVal != removetarget)) {
19384:                                     singleserver.options[0] = new Option("","",false,false);
19385:                                 } else {
19386:                                     singleserver.options[0] = new Option("","",true,true);
19387:                                 }
19388:                                 var idx = 0;
19389:                                 for (var m=0; m<alltargets.length; m++) {
19390:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
19391:                                         idx ++;
19392:                                         if (currVal == alltargets[m]) {
19393:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
19394:                                         } else {
19395:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
19396:                                         }
19397:                                     }
19398:                                 }
19399:                             }
19400:                         }
19401:                     }
19402:                 }
19403:             }
19404:         }
19405:     }
19406:     return;
19407: }
19408: 
19409: // ]]>
19410: </script>
19411: 
19412: END
19413: }
19414: 
19415: sub new_spares_js {
19416:     my @sparestypes = ('primary','default');
19417:     my $types = join("','",@sparestypes);
19418:     my $select = &mt('Select');
19419:     return <<"END";
19420: 
19421: <script type="text/javascript">
19422: // <![CDATA[
19423: 
19424: function updateNewSpares(formname,lonhost) {
19425:     var types = new Array('$types');
19426:     var include = new Array();
19427:     var exclude = new Array();
19428:     for (var i=0; i<types.length; i++) {
19429:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
19430:         for (var j=0; j<spareboxes.length; j++) {
19431:             if (formname.elements[spareboxes[j]].checked) {
19432:                 exclude.push(formname.elements[spareboxes[j]].value);
19433:             } else {
19434:                 include.push(formname.elements[spareboxes[j]].value);
19435:             }
19436:         }
19437:     }
19438:     for (var i=0; i<types.length; i++) {
19439:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
19440:         var selIdx = newSpare.selectedIndex;
19441:         var currnew = newSpare.options[selIdx].value;
19442:         var okSpares = new Array();
19443:         for (var j=0; j<newSpare.options.length; j++) {
19444:             var possible = newSpare.options[j].value;
19445:             if (possible != '') {
19446:                 if (exclude.indexOf(possible) == -1) {
19447:                     okSpares.push(possible);
19448:                 } else {
19449:                     if (currnew == possible) {
19450:                         selIdx = 0;
19451:                     }
19452:                 }
19453:             }
19454:         }
19455:         for (var k=0; k<include.length; k++) {
19456:             if (okSpares.indexOf(include[k]) == -1) {
19457:                 okSpares.push(include[k]);
19458:             }
19459:         }
19460:         okSpares.sort();
19461:         newSpare.options.length = 0;
19462:         if (selIdx == 0) {
19463:             newSpare.options[0] = new Option("$select","",true,true);
19464:         } else {
19465:             newSpare.options[0] = new Option("$select","",false,false);
19466:         }
19467:         for (var m=0; m<okSpares.length; m++) {
19468:             var idx = m+1;
19469:             var selThis = 0;
19470:             if (selIdx != 0) {
19471:                 if (okSpares[m] == currnew) {
19472:                     selThis = 1;
19473:                 }
19474:             }
19475:             if (selThis == 1) {
19476:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
19477:             } else {
19478:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
19479:             }
19480:         }
19481:     }
19482:     return;
19483: }
19484: 
19485: function checkNewSpares(lonhost,type) {
19486:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
19487:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
19488:     if (chosen != '') { 
19489:         var othertype;
19490:         var othernewSpare;
19491:         if (type == 'primary') {
19492:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
19493:         }
19494:         if (type == 'default') {
19495:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
19496:         }
19497:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
19498:             othernewSpare.selectedIndex = 0;
19499:         }
19500:     }
19501:     return;
19502: }
19503: 
19504: // ]]>
19505: </script>
19506: 
19507: END
19508: 
19509: }
19510: 
19511: sub common_domprefs_js {
19512:     return <<"END";
19513: 
19514: <script type="text/javascript">
19515: // <![CDATA[
19516: 
19517: function getIndicesByName(formname,item) {
19518:     var group = new Array();
19519:     for (var i=0;i<formname.elements.length;i++) {
19520:         if (formname.elements[i].name == item) {
19521:             group.push(formname.elements[i].id);
19522:         }
19523:     }
19524:     return group;
19525: }
19526: 
19527: // ]]>
19528: </script>
19529: 
19530: END
19531: 
19532: }
19533: 
19534: sub recaptcha_js {
19535:     my %lt = &captcha_phrases();
19536:     return <<"END";
19537: 
19538: <script type="text/javascript">
19539: // <![CDATA[
19540: 
19541: function updateCaptcha(caller,context) {
19542:     var privitem;
19543:     var pubitem;
19544:     var privtext;
19545:     var pubtext;
19546:     var versionitem;
19547:     var versiontext;
19548:     if (document.getElementById(context+'_recaptchapub')) {
19549:         pubitem = document.getElementById(context+'_recaptchapub');
19550:     } else {
19551:         return;
19552:     }
19553:     if (document.getElementById(context+'_recaptchapriv')) {
19554:         privitem = document.getElementById(context+'_recaptchapriv');
19555:     } else {
19556:         return;
19557:     }
19558:     if (document.getElementById(context+'_recaptchapubtxt')) {
19559:         pubtext = document.getElementById(context+'_recaptchapubtxt');
19560:     } else {
19561:         return;
19562:     }
19563:     if (document.getElementById(context+'_recaptchaprivtxt')) {
19564:         privtext = document.getElementById(context+'_recaptchaprivtxt');
19565:     } else {
19566:         return;
19567:     }
19568:     if (document.getElementById(context+'_recaptchaversion')) {
19569:         versionitem = document.getElementById(context+'_recaptchaversion');
19570:     } else {
19571:         return;
19572:     }
19573:     if (document.getElementById(context+'_recaptchavertxt')) {
19574:         versiontext = document.getElementById(context+'_recaptchavertxt');
19575:     } else {
19576:         return;
19577:     }
19578:     if (caller.checked) {
19579:         if (caller.value == 'recaptcha') {
19580:             pubitem.type = 'text';
19581:             privitem.type = 'text';
19582:             pubitem.size = '40';
19583:             privitem.size = '40';
19584:             pubtext.innerHTML = "$lt{'pub'}";
19585:             privtext.innerHTML = "$lt{'priv'}";
19586:             versionitem.type = 'text';
19587:             versionitem.size = '3';
19588:             versiontext.innerHTML = "$lt{'ver'}";
19589:         } else {
19590:             pubitem.type = 'hidden';
19591:             privitem.type = 'hidden';
19592:             versionitem.type = 'hidden';
19593:             pubtext.innerHTML = '';
19594:             privtext.innerHTML = '';
19595:             versiontext.innerHTML = '';
19596:         }
19597:     }
19598:     return;
19599: }
19600: 
19601: // ]]>
19602: </script>
19603: 
19604: END
19605: 
19606: }
19607: 
19608: sub toggle_display_js {
19609:     return <<"END";
19610: 
19611: <script type="text/javascript">
19612: // <![CDATA[
19613: 
19614: function toggleDisplay(domForm,caller) {
19615:     if (document.getElementById(caller)) {
19616:         var divitem = document.getElementById(caller);
19617:         var optionsElement = domForm.coursecredits;
19618:         var checkval = 1;
19619:         var dispval = 'block';
19620:         var selfcreateRegExp = /^cancreate_emailverified/;
19621:         if (caller == 'emailoptions') {
19622:             optionsElement = domForm.cancreate_email; 
19623:         }
19624:         if (caller == 'studentsubmission') {
19625:             optionsElement = domForm.postsubmit;
19626:         }
19627:         if (caller == 'cloneinstcode') {
19628:             optionsElement = domForm.canclone;
19629:             checkval = 'instcode';
19630:         }
19631:         if (selfcreateRegExp.test(caller)) {
19632:             optionsElement = domForm.elements[caller];
19633:             checkval = 'other';
19634:             dispval = 'inline'
19635:         }
19636:         if (optionsElement.length) {
19637:             var currval;
19638:             for (var i=0; i<optionsElement.length; i++) {
19639:                 if (optionsElement[i].checked) {
19640:                    currval = optionsElement[i].value;
19641:                 }
19642:             }
19643:             if (currval == checkval) {
19644:                 divitem.style.display = dispval;
19645:             } else {
19646:                 divitem.style.display = 'none';
19647:             }
19648:         }
19649:     }
19650:     return;
19651: }
19652: 
19653: // ]]>
19654: </script>
19655: 
19656: END
19657: 
19658: }
19659: 
19660: sub captcha_phrases {
19661:     return &Apache::lonlocal::texthash (
19662:                  priv => 'Private key',
19663:                  pub  => 'Public key',
19664:                  original  => 'original (CAPTCHA)',
19665:                  recaptcha => 'successor (ReCAPTCHA)',
19666:                  notused   => 'unused',
19667:                  ver => 'ReCAPTCHA version (1 or 2)',
19668:     );
19669: }
19670: 
19671: sub devalidate_remote_domconfs {
19672:     my ($dom,$cachekeys) = @_;
19673:     return unless (ref($cachekeys) eq 'HASH');
19674:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
19675:     my %thismachine;
19676:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
19677:     my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
19678:                       'directorysrch','passwdconf');
19679:     if (keys(%servers)) {
19680:         foreach my $server (keys(%servers)) {
19681:             next if ($thismachine{$server});
19682:             my @cached;
19683:             foreach my $name (@posscached) {
19684:                 if ($cachekeys->{$name}) {
19685:                     push(@cached,&escape($name).':'.&escape($dom));
19686:                 }
19687:             }
19688:             if (@cached) {
19689:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
19690:             }
19691:         }
19692:     }
19693:     return;
19694: }
19695: 
19696: 1;

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