File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.273: download - view: text, annotated - select for diffs
Mon Jun 6 17:40:47 2016 UTC (8 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754. Make LON-CAPA an LTI Tool Consumer (LTI 1.1).
  - Domain cofiguration to determine whether context_label, context_title,
    and launch_presentation_document_target LTI parameters can be configured
    for each instance of use of LTI Tool in a course.

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.273 2016/06/06 17:40:47 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: # /home/httpd/html/adm/gpl.txt
   24: #
   25: # http://www.lon-capa.org/
   26: #
   27: #
   28: ###############################################################
   29: ##############################################################
   30: 
   31: =pod
   32: 
   33: =head1 NAME
   34: 
   35: Apache::domainprefs.pm
   36: 
   37: =head1 SYNOPSIS
   38: 
   39: Handles configuration of a LON-CAPA domain.  
   40: 
   41: This is part of the LearningOnline Network with CAPA project
   42: described at http://www.lon-capa.org.
   43: 
   44: 
   45: =head1 OVERVIEW
   46: 
   47: Each institution using LON-CAPA will typically have a single domain designated 
   48: for use by individuals affiliated with the institution.  Accordingly, each domain
   49: may define a default set of logos and a color scheme which can be used to "brand"
   50: the LON-CAPA instance. In addition, an institution will typically have a language
   51: and timezone which are used for the majority of courses.
   52: 
   53: LON-CAPA provides a mechanism to display and modify these defaults, as well as a 
   54: host of other domain-wide settings which determine the types of functionality
   55: available to users and courses in the domain.
   56: 
   57: There is also a mechanism to configure cataloging of courses in the domain, and
   58: controls on the operation of automated processes which govern such things as
   59: roster updates, user directory updates and processing of course requests.
   60: 
   61: The domain coordination manual which is built dynamically on install/update of 
   62: LON-CAPA from the relevant help items provides more information about domain 
   63: configuration.
   64: 
   65: Most of the domain settings are stored in the configuration.db GDBM file which is
   66: housed on the primary library server for the domain in /home/httpd/lonUsers/$dom,
   67: where $dom is the domain.  The configuration.db stores settings in a number of 
   68: frozen hashes of hashes.  In a few cases, domain information must be uploaded to
   69: the domain as files (e.g., image files for logos etc., or plain text files for
   70: bubblesheet formats).  In this case the domainprefs.pm must be running in a user
   71: session hosted on the primary library server in the domain, as these files are 
   72: stored in author space belonging to a special $dom-domainconfig user.   
   73: 
   74: domainprefs.pm in combination with lonconfigsettings.pm will retrieve and display
   75: the current settings, and provides an interface to make modifications.
   76: 
   77: =head1 SUBROUTINES
   78: 
   79: =over
   80: 
   81: =item print_quotas()
   82: 
   83: Inputs: 4 
   84: 
   85: $dom,$settings,$rowtotal,$action.
   86: 
   87: $dom is the domain, $settings is a reference to a hash of current settings for
   88: the current context, $rowtotal is a reference to the scalar used to record the 
   89: number of rows displayed on the page, and $action is the context (quotas, 
   90: requestcourses or requestauthor).
   91: 
   92: The print_quotas routine was orginally created to display/store information
   93: about default quota sizes for portfolio spaces for the different types of 
   94: institutional affiliation in the domain (e.g., Faculty, Staff, Student etc.), 
   95: but is now also used to manage availability of user tools: 
   96: i.e., blogs, aboutme page, and portfolios, and the course request tool,
   97: used by course owners to request creation of a course, and to display/store
   98: default quota sizes for Authoring Spaces.
   99: 
  100: Outputs: 1
  101: 
  102: $datatable  - HTML containing form elements which allow settings to be changed. 
  103: 
  104: In the case of course requests, radio buttons are displayed for each institutional
  105: affiliate type (and also default, and _LC_adv) for each of the course types 
  106: (official, unofficial, community, textbook, and placement).  
  107: In each case the radio buttons allow the selection of one of four values:  
  108: 
  109: 0, approval, validate, autolimit=N (where N is blank, or a positive integer).
  110: which have the following effects:
  111: 
  112: 0
  113: 
  114: =over
  115: 
  116: - course requests are not allowed for this course types/affiliation
  117: 
  118: =back
  119: 
  120: approval 
  121: 
  122: =over 
  123: 
  124: - course requests must be approved by a Doman Coordinator in the 
  125: course's domain
  126: 
  127: =back
  128: 
  129: validate 
  130: 
  131: =over
  132: 
  133: - an institutional validation (e.g., check requestor is instructor
  134: of record) needs to be passed before the course will be created.  The required
  135: validation is in localenroll.pm on the primary library server for the course 
  136: domain.
  137: 
  138: =back
  139: 
  140: autolimit 
  141: 
  142: =over
  143:  
  144: - course requests will be processed automatically up to a limit of
  145: N requests for the course type for the particular requestor.
  146: If N is undefined, there is no limit to the number of course requests
  147: which a course owner may submit and have processed automatically. 
  148: 
  149: =back
  150: 
  151: =item modify_quotas() 
  152: 
  153: =back
  154: 
  155: =cut
  156: 
  157: package Apache::domainprefs;
  158: 
  159: use strict;
  160: use Apache::Constants qw(:common :http);
  161: use Apache::lonnet;
  162: use Apache::loncommon();
  163: use Apache::lonhtmlcommon();
  164: use Apache::lonlocal;
  165: use Apache::lonmsg();
  166: use Apache::lonconfigsettings;
  167: use Apache::lonuserutils();
  168: use Apache::loncoursequeueadmin();
  169: use LONCAPA qw(:DEFAULT :match);
  170: use LONCAPA::Enrollment;
  171: use LONCAPA::lonauthcgi();
  172: use File::Copy;
  173: use Locale::Language;
  174: use DateTime::TimeZone;
  175: use DateTime::Locale;
  176: use Time::HiRes qw( sleep );
  177: 
  178: my $registered_cleanup;
  179: my $modified_urls;
  180: 
  181: sub handler {
  182:     my $r=shift;
  183:     if ($r->header_only) {
  184:         &Apache::loncommon::content_type($r,'text/html');
  185:         $r->send_http_header;
  186:         return OK;
  187:     }
  188: 
  189:     my $context = 'domain';
  190:     my $dom = $env{'request.role.domain'};
  191:     my $domdesc = &Apache::lonnet::domain($dom,'description');
  192:     if (&Apache::lonnet::allowed('mau',$dom)) {
  193:         &Apache::loncommon::content_type($r,'text/html');
  194:         $r->send_http_header;
  195:     } else {
  196:         $env{'user.error.msg'}=
  197:         "/adm/domainprefs:mau:0:0:Cannot modify domain settings";
  198:         return HTTP_NOT_ACCEPTABLE;
  199:     }
  200: 
  201:     $registered_cleanup=0;
  202:     @{$modified_urls}=();
  203: 
  204:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  205:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  206:                                             ['phase','actions']);
  207:     my $phase = 'pickactions';
  208:     if ( exists($env{'form.phase'}) ) {
  209:         $phase = $env{'form.phase'};
  210:     }
  211:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
  212:     my %domconfig =
  213:       &Apache::lonnet::get_dom('configuration',['login','rolecolors',
  214:                 'quotas','autoenroll','autoupdate','autocreate',
  215:                 'directorysrch','usercreation','usermodification',
  216:                 'contacts','defaults','scantron','coursecategories',
  217:                 'serverstatuses','requestcourses','helpsettings',
  218:                 'coursedefaults','usersessions','loadbalancing',
  219:                 'requestauthor','selfenrollment','inststatus',
  220:                 'ltitools'],$dom);
  221:     my @prefs_order = ('rolecolors','login','defaults','quotas','autoenroll',
  222:                        'autoupdate','autocreate','directorysrch','contacts',
  223:                        'usercreation','selfcreation','usermodification','scantron',
  224:                        'requestcourses','requestauthor','coursecategories',
  225:                        'serverstatuses','helpsettings','coursedefaults',
  226:                        'ltitools','selfenrollment','usersessions');
  227:     my %existing;
  228:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  229:         %existing = %{$domconfig{'loadbalancing'}};
  230:     }
  231:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  232:         push(@prefs_order,'loadbalancing');
  233:     }
  234:     my %prefs = (
  235:         'rolecolors' =>
  236:                    { text => 'Default color schemes',
  237:                      help => 'Domain_Configuration_Color_Schemes',
  238:                      header => [{col1 => 'Student Settings',
  239:                                  col2 => '',},
  240:                                 {col1 => 'Coordinator Settings',
  241:                                  col2 => '',},
  242:                                 {col1 => 'Author Settings',
  243:                                  col2 => '',},
  244:                                 {col1 => 'Administrator Settings',
  245:                                  col2 => '',}],
  246:                       print => \&print_rolecolors,
  247:                       modify => \&modify_rolecolors,
  248:                     },
  249:         'login' =>
  250:                     { text => 'Log-in page options',
  251:                       help => 'Domain_Configuration_Login_Page',
  252:                       header => [{col1 => 'Log-in Page Items',
  253:                                   col2 => '',},
  254:                                  {col1 => 'Log-in Help',
  255:                                   col2 => 'Value'},
  256:                                  {col1 => 'Custom HTML in document head',
  257:                                   col2 => 'Value'}],
  258:                       print => \&print_login,
  259:                       modify => \&modify_login,
  260:                     },
  261:         'defaults' => 
  262:                     { text => 'Default authentication/language/timezone/portal/types',
  263:                       help => 'Domain_Configuration_LangTZAuth',
  264:                       header => [{col1 => 'Setting',
  265:                                   col2 => 'Value'},
  266:                                  {col1 => 'Institutional user types',
  267:                                   col2 => 'Assignable to e-mail usernames'}],
  268:                       print => \&print_defaults,
  269:                       modify => \&modify_defaults,
  270:                     },
  271:         'quotas' => 
  272:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  273:                       help => 'Domain_Configuration_Quotas',
  274:                       header => [{col1 => 'User affiliation',
  275:                                   col2 => 'Available tools',
  276:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  277:                       print => \&print_quotas,
  278:                       modify => \&modify_quotas,
  279:                     },
  280:         'autoenroll' =>
  281:                    { text => 'Auto-enrollment settings',
  282:                      help => 'Domain_Configuration_Auto_Enrollment',
  283:                      header => [{col1 => 'Configuration setting',
  284:                                  col2 => 'Value(s)'}],
  285:                      print => \&print_autoenroll,
  286:                      modify => \&modify_autoenroll,
  287:                    },
  288:         'autoupdate' => 
  289:                    { text => 'Auto-update settings',
  290:                      help => 'Domain_Configuration_Auto_Updates',
  291:                      header => [{col1 => 'Setting',
  292:                                  col2 => 'Value',},
  293:                                 {col1 => 'Setting',
  294:                                  col2 => 'Affiliation'},
  295:                                 {col1 => 'User population',
  296:                                  col2 => 'Updatable user data'}],
  297:                      print => \&print_autoupdate,
  298:                      modify => \&modify_autoupdate,
  299:                   },
  300:         'autocreate' => 
  301:                   { text => 'Auto-course creation settings',
  302:                      help => 'Domain_Configuration_Auto_Creation',
  303:                      header => [{col1 => 'Configuration Setting',
  304:                                  col2 => 'Value',}],
  305:                      print => \&print_autocreate,
  306:                      modify => \&modify_autocreate,
  307:                   },
  308:         'directorysrch' => 
  309:                   { text => 'Institutional directory searches',
  310:                     help => 'Domain_Configuration_InstDirectory_Search',
  311:                     header => [{col1 => 'Setting',
  312:                                 col2 => 'Value',}],
  313:                     print => \&print_directorysrch,
  314:                     modify => \&modify_directorysrch,
  315:                   },
  316:         'contacts' =>
  317:                   { text => 'Contact Information',
  318:                     help => 'Domain_Configuration_Contact_Info',
  319:                     header => [{col1 => 'Setting',
  320:                                 col2 => 'Value',}],
  321:                     print => \&print_contacts,
  322:                     modify => \&modify_contacts,
  323:                   },
  324:         'usercreation' => 
  325:                   { text => 'User creation',
  326:                     help => 'Domain_Configuration_User_Creation',
  327:                     header => [{col1 => 'Format rule type',
  328:                                 col2 => 'Format rules in force'},
  329:                                {col1 => 'User account creation',
  330:                                 col2 => 'Usernames which may be created',},
  331:                                {col1 => 'Context',
  332:                                 col2 => 'Assignable authentication types'}],
  333:                     print => \&print_usercreation,
  334:                     modify => \&modify_usercreation,
  335:                   },
  336:         'selfcreation' => 
  337:                   { text => 'Users self-creating accounts',
  338:                     help => 'Domain_Configuration_Self_Creation', 
  339:                     header => [{col1 => 'Self-creation with institutional username',
  340:                                 col2 => 'Enabled?'},
  341:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  342:                                 col2 => 'Information user can enter'},
  343:                                {col1 => 'Self-creation with e-mail as username',
  344:                                 col2 => 'Settings'}],
  345:                     print => \&print_selfcreation,
  346:                     modify => \&modify_selfcreation,
  347:                   },
  348:         'usermodification' =>
  349:                   { text => 'User modification',
  350:                     help => 'Domain_Configuration_User_Modification',
  351:                     header => [{col1 => 'Target user has role',
  352:                                 col2 => 'User information updatable in author context'},
  353:                                {col1 => 'Target user has role',
  354:                                 col2 => 'User information updatable in course context'}],
  355:                     print => \&print_usermodification,
  356:                     modify => \&modify_usermodification,
  357:                   },
  358:         'scantron' =>
  359:                   { text => 'Bubblesheet format file',
  360:                     help => 'Domain_Configuration_Scantron_Format',
  361:                     header => [ {col1 => 'Item',
  362:                                  col2 => '',
  363:                               }],
  364:                     print => \&print_scantron,
  365:                     modify => \&modify_scantron,
  366:                   },
  367:         'requestcourses' => 
  368:                  {text => 'Request creation of courses',
  369:                   help => 'Domain_Configuration_Request_Courses',
  370:                   header => [{col1 => 'User affiliation',
  371:                               col2 => 'Availability/Processing of requests',},
  372:                              {col1 => 'Setting',
  373:                               col2 => 'Value'},
  374:                              {col1 => 'Available textbooks',
  375:                               col2 => ''},
  376:                              {col1 => 'Available templates',
  377:                               col2 => ''},
  378:                              {col1 => 'Validation (not official courses)',
  379:                               col2 => 'Value'},],
  380:                   print => \&print_quotas,
  381:                   modify => \&modify_quotas,
  382:                  },
  383:         'requestauthor' =>
  384:                  {text => 'Request Authoring Space',
  385:                   help => 'Domain_Configuration_Request_Author',
  386:                   header => [{col1 => 'User affiliation',
  387:                               col2 => 'Availability/Processing of requests',},
  388:                              {col1 => 'Setting',
  389:                               col2 => 'Value'}],
  390:                   print => \&print_quotas,
  391:                   modify => \&modify_quotas,
  392:                  },
  393:         'coursecategories' =>
  394:                   { text => 'Cataloging of courses/communities',
  395:                     help => 'Domain_Configuration_Cataloging_Courses',
  396:                     header => [{col1 => 'Catalog type/availability',
  397:                                 col2 => '',},
  398:                                {col1 => 'Category settings for standard catalog',
  399:                                 col2 => '',},
  400:                                {col1 => 'Categories',
  401:                                 col2 => '',
  402:                                }],
  403:                     print => \&print_coursecategories,
  404:                     modify => \&modify_coursecategories,
  405:                   },
  406:         'serverstatuses' =>
  407:                  {text   => 'Access to server status pages',
  408:                   help   => 'Domain_Configuration_Server_Status',
  409:                   header => [{col1 => 'Status Page',
  410:                               col2 => 'Other named users',
  411:                               col3 => 'Specific IPs',
  412:                             }],
  413:                   print => \&print_serverstatuses,
  414:                   modify => \&modify_serverstatuses,
  415:                  },
  416:         'helpsettings' =>
  417:                  {text   => 'Help page settings',
  418:                   help   => 'Domain_Configuration_Help_Settings',
  419:                   header => [{col1 => 'Help Settings (logged-in users)',
  420:                               col2 => 'Value'}],
  421:                   print  => \&print_helpsettings,
  422:                   modify => \&modify_helpsettings,
  423:                  },
  424:         'coursedefaults' => 
  425:                  {text => 'Course/Community defaults',
  426:                   help => 'Domain_Configuration_Course_Defaults',
  427:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  428:                               col2 => 'Value',},
  429:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  430:                               col2 => 'Value',},],
  431:                   print => \&print_coursedefaults,
  432:                   modify => \&modify_coursedefaults,
  433:                  },
  434:         'selfenrollment' => 
  435:                  {text   => 'Self-enrollment in Course/Community',
  436:                   help   => 'Domain_Configuration_Selfenrollment',
  437:                   header => [{col1 => 'Configuration Rights',
  438:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  439:                              {col1 => 'Defaults',
  440:                               col2 => 'Value'},
  441:                              {col1 => 'Self-enrollment validation (optional)',
  442:                               col2 => 'Value'},],
  443:                   print => \&print_selfenrollment,
  444:                   modify => \&modify_selfenrollment,
  445:                  },
  446:         'privacy' => 
  447:                  {text   => 'User Privacy',
  448:                   help   => 'Domain_Configuration_User_Privacy',
  449:                   header => [{col1 => 'Setting',
  450:                               col2 => 'Value',}],
  451:                   print => \&print_privacy,
  452:                   modify => \&modify_privacy,
  453:                  },
  454:         'usersessions' =>
  455:                  {text  => 'User session hosting/offloading',
  456:                   help  => 'Domain_Configuration_User_Sessions',
  457:                   header => [{col1 => 'Domain server',
  458:                               col2 => 'Servers to offload sessions to when busy'},
  459:                              {col1 => 'Hosting of users from other domains',
  460:                               col2 => 'Rules'},
  461:                              {col1 => "Hosting domain's own users elsewhere",
  462:                               col2 => 'Rules'}],
  463:                   print => \&print_usersessions,
  464:                   modify => \&modify_usersessions,
  465:                  },
  466:          'loadbalancing' =>
  467:                  {text  => 'Dedicated Load Balancer(s)',
  468:                   help  => 'Domain_Configuration_Load_Balancing',
  469:                   header => [{col1 => 'Balancers',
  470:                               col2 => 'Default destinations',
  471:                               col3 => 'User affiliation',
  472:                               col4 => 'Overrides'},
  473:                             ],
  474:                   print => \&print_loadbalancing,
  475:                   modify => \&modify_loadbalancing,
  476:                  },
  477:          'ltitools' => 
  478:                  {text => 'External Tools (LTI)',
  479:                   help => 'Domain_configuration_LTI_Tools',
  480:                   header => [{col1 => 'Setting',
  481:                               col2 => 'Value',}],
  482:                   print => \&print_ltitools,
  483:                   modify => \&modify_ltitools,
  484:                  },
  485:  
  486:     );
  487:     if (keys(%servers) > 1) {
  488:         $prefs{'login'}  = { text   => 'Log-in page options',
  489:                              help   => 'Domain_Configuration_Login_Page',
  490:                             header => [{col1 => 'Log-in Service',
  491:                                         col2 => 'Server Setting',},
  492:                                        {col1 => 'Log-in Page Items',
  493:                                         col2 => ''},
  494:                                        {col1 => 'Log-in Help',
  495:                                         col2 => 'Value'},
  496:                                        {col1 => 'Custom HTML in document head',
  497:                                         col2 => 'Value'}],
  498:                             print => \&print_login,
  499:                             modify => \&modify_login,
  500:                            };
  501:     }
  502: 
  503:     my @roles = ('student','coordinator','author','admin');
  504:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  505:     &Apache::lonhtmlcommon::add_breadcrumb
  506:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  507:       text=>"Settings to display/modify"});
  508:     my $confname = $dom.'-domainconfig';
  509: 
  510:     if ($phase eq 'process') {
  511:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  512:                                                               \%prefs,\%domconfig,$confname,\@roles);
  513:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  514:             $r->rflush();
  515:             &devalidate_remote_domconfs($dom,$result);
  516:         }
  517:     } elsif ($phase eq 'display') {
  518:         my $js = &recaptcha_js().
  519:                  &toggle_display_js();
  520:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  521:             my ($othertitle,$usertypes,$types) =
  522:                 &Apache::loncommon::sorted_inst_types($dom);
  523:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  524:                                           $domconfig{'loadbalancing'}).
  525:                    &new_spares_js().
  526:                    &common_domprefs_js().
  527:                    &Apache::loncommon::javascript_array_indexof();
  528:         }
  529:         if (grep(/^requestcourses$/,@actions)) {
  530:             my $javascript_validations;
  531:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  532:             $js .= <<END;
  533: <script type="text/javascript">
  534: $javascript_validations
  535: </script>
  536: $coursebrowserjs
  537: END
  538:         }
  539:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  540:     } else {
  541: # check if domconfig user exists for the domain.
  542:         my $servadm = $r->dir_config('lonAdmEMail');
  543:         my ($configuserok,$author_ok,$switchserver) =
  544:             &config_check($dom,$confname,$servadm);
  545:         unless ($configuserok eq 'ok') {
  546:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  547:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  548:                           $confname).
  549:                       '<br />'
  550:             );
  551:             if ($switchserver) {
  552:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  553:                           '<br />'.
  554:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  555:                           '<br />'.
  556:                           &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).
  557:                           '<br />'.
  558:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  559:                 );
  560:             } else {
  561:                 $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.').
  562:                           '<br />'.
  563:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  564:                 );
  565:             }
  566:             $r->print(&Apache::loncommon::end_page());
  567:             return OK;
  568:         }
  569:         if (keys(%domconfig) == 0) {
  570:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  571:             my @ids=&Apache::lonnet::current_machine_ids();
  572:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  573:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  574:                 my @loginimages = ('img','logo','domlogo','login');
  575:                 my $custom_img_count = 0;
  576:                 foreach my $img (@loginimages) {
  577:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  578:                         $custom_img_count ++;
  579:                     }
  580:                 }
  581:                 foreach my $role (@roles) {
  582:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  583:                         $custom_img_count ++;
  584:                     }
  585:                 }
  586:                 if ($custom_img_count > 0) {
  587:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  588:                     my $switch_server = &check_switchserver($dom,$confname);
  589:                     $r->print(
  590:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  591:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  592:     &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 />'.
  593:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  594:                     if ($switch_server) {
  595:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  596:                     }
  597:                     $r->print(&Apache::loncommon::end_page());
  598:                     return OK;
  599:                 }
  600:             }
  601:         }
  602:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  603:     }
  604:     return OK;
  605: }
  606: 
  607: sub process_changes {
  608:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  609:     my %domconfig;
  610:     if (ref($values) eq 'HASH') {
  611:         %domconfig = %{$values};
  612:     }
  613:     my $output;
  614:     if ($action eq 'login') {
  615:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  616:     } elsif ($action eq 'rolecolors') {
  617:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  618:                                      $lastactref,%domconfig);
  619:     } elsif ($action eq 'quotas') {
  620:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  621:     } elsif ($action eq 'autoenroll') {
  622:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  623:     } elsif ($action eq 'autoupdate') {
  624:         $output = &modify_autoupdate($dom,%domconfig);
  625:     } elsif ($action eq 'autocreate') {
  626:         $output = &modify_autocreate($dom,%domconfig);
  627:     } elsif ($action eq 'directorysrch') {
  628:         $output = &modify_directorysrch($dom,%domconfig);
  629:     } elsif ($action eq 'usercreation') {
  630:         $output = &modify_usercreation($dom,%domconfig);
  631:     } elsif ($action eq 'selfcreation') {
  632:         $output = &modify_selfcreation($dom,%domconfig);
  633:     } elsif ($action eq 'usermodification') {
  634:         $output = &modify_usermodification($dom,%domconfig);
  635:     } elsif ($action eq 'contacts') {
  636:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  637:     } elsif ($action eq 'defaults') {
  638:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  639:     } elsif ($action eq 'scantron') {
  640:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  641:     } elsif ($action eq 'coursecategories') {
  642:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  643:     } elsif ($action eq 'serverstatuses') {
  644:         $output = &modify_serverstatuses($dom,%domconfig);
  645:     } elsif ($action eq 'requestcourses') {
  646:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  647:     } elsif ($action eq 'requestauthor') {
  648:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  649:     } elsif ($action eq 'helpsettings') {
  650:         $output = &modify_helpsettings($r,$dom,$confname,%domconfig);
  651:     } elsif ($action eq 'coursedefaults') {
  652:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  653:     } elsif ($action eq 'selfenrollment') {
  654:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  655:     } elsif ($action eq 'usersessions') {
  656:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  657:     } elsif ($action eq 'loadbalancing') {
  658:         $output = &modify_loadbalancing($dom,%domconfig);
  659:     } elsif ($action eq 'ltitools') {
  660:         $output = &modify_ltitools($r,$dom,$action,$lastactref,%domconfig);
  661:     }
  662:     return $output;
  663: }
  664: 
  665: sub print_config_box {
  666:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  667:     my $rowtotal = 0;
  668:     my $output;
  669:     if ($action eq 'coursecategories') {
  670:         $output = &coursecategories_javascript($settings);
  671:     } elsif ($action eq 'defaults') {
  672:         $output = &defaults_javascript($settings); 
  673:     }
  674:     $output .=
  675:          '<table class="LC_nested_outer">
  676:           <tr>
  677:            <th align="left" valign="middle"><span class="LC_nobreak">'.
  678:            &mt($item->{text}).'&nbsp;'.
  679:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  680:           '</tr>';
  681:     $rowtotal ++;
  682:     my $numheaders = 1;
  683:     if (ref($item->{'header'}) eq 'ARRAY') {
  684:         $numheaders = scalar(@{$item->{'header'}});
  685:     }
  686:     if ($numheaders > 1) {
  687:         my $colspan = '';
  688:         my $rightcolspan = '';
  689:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  690:             (($action eq 'login') && ($numheaders < 4))) {
  691:             $colspan = ' colspan="2"';
  692:         }
  693:         if ($action eq 'usersessions') {
  694:             $rightcolspan = ' colspan="3"'; 
  695:         }
  696:         $output .= '
  697:           <tr>
  698:            <td>
  699:             <table class="LC_nested">
  700:              <tr class="LC_info_row">
  701:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  702:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  703:              </tr>';
  704:         $rowtotal ++;
  705:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  706:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  707:             ($action eq 'selfenrollment') || ($action eq 'usersessions')) {
  708:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  709:         } elsif ($action eq 'coursecategories') {
  710:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  711:         } elsif ($action eq 'login') {
  712:             if ($numheaders == 4) {
  713:                 $colspan = ' colspan="2"';
  714:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  715:             } else {
  716:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  717:             }
  718:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  719:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  720:         } elsif ($action eq 'rolecolors') {
  721:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  722:         }
  723:         $output .= '
  724:            </table>
  725:           </td>
  726:          </tr>
  727:          <tr>
  728:            <td>
  729:             <table class="LC_nested">
  730:              <tr class="LC_info_row">
  731:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  732:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  733:              </tr>';
  734:             $rowtotal ++;
  735:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  736:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  737:             ($action eq 'usersessions') || ($action eq 'coursecategories')) {
  738:             if ($action eq 'coursecategories') {
  739:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  740:                 $colspan = ' colspan="2"';
  741:             } else {
  742:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  743:             }
  744:             $output .= '
  745:            </table>
  746:           </td>
  747:          </tr>
  748:          <tr>
  749:            <td>
  750:             <table class="LC_nested">
  751:              <tr class="LC_info_row">
  752:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  753:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  754:              </tr>'."\n";
  755:             if ($action eq 'coursecategories') {
  756:                 $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
  757:             } else {
  758:                 $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  759:             }
  760:             $rowtotal ++;
  761:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
  762:                   ($action eq 'defaults')) {
  763:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  764:         } elsif ($action eq 'login') {
  765:             if ($numheaders == 4) {
  766:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
  767:            </table>
  768:           </td>
  769:          </tr>
  770:          <tr>
  771:            <td>
  772:             <table class="LC_nested">
  773:              <tr class="LC_info_row">
  774:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  775:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
  776:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  777:                 $rowtotal ++;
  778:             } else {
  779:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  780:             }
  781:             $output .= '
  782:            </table>
  783:           </td>
  784:          </tr>
  785:          <tr>
  786:            <td>
  787:             <table class="LC_nested">
  788:              <tr class="LC_info_row">';
  789:             if ($numheaders == 4) {
  790:                 $output .= '
  791:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  792:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  793:              </tr>';
  794:             } else {
  795:                 $output .= '
  796:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  797:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  798:              </tr>';
  799:             }
  800:             $rowtotal ++;
  801:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal);
  802:         } elsif ($action eq 'requestcourses') {
  803:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
  804:             $rowtotal ++;
  805:             $output .= &print_studentcode($settings,\$rowtotal).'
  806:            </table>
  807:           </td>
  808:          </tr>
  809:          <tr>
  810:            <td>
  811:             <table class="LC_nested">
  812:              <tr class="LC_info_row">
  813:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  814:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
  815:                        &textbookcourses_javascript($settings).
  816:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
  817:             </table>
  818:            </td>
  819:           </tr>
  820:          <tr>
  821:            <td>
  822:             <table class="LC_nested">
  823:              <tr class="LC_info_row">
  824:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  825:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
  826:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
  827:             </table>
  828:            </td>
  829:           </tr>
  830:           <tr>
  831:            <td>
  832:             <table class="LC_nested">
  833:              <tr class="LC_info_row">
  834:               <td class="LC_left_item"'.$colspan.' valign="top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
  835:               <td class="LC_right_item" valign="top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
  836:              </tr>'.
  837:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
  838:         } elsif ($action eq 'requestauthor') {
  839:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
  840:             $rowtotal ++;
  841:         } elsif ($action eq 'rolecolors') {
  842:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
  843:            </table>
  844:           </td>
  845:          </tr>
  846:          <tr>
  847:            <td>
  848:             <table class="LC_nested">
  849:              <tr class="LC_info_row">
  850:               <td class="LC_left_item"'.$colspan.' valign="top">'.
  851:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
  852:               <td class="LC_right_item" valign="top">'.
  853:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
  854:              </tr>'.
  855:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
  856:            </table>
  857:           </td>
  858:          </tr>
  859:          <tr>
  860:            <td>
  861:             <table class="LC_nested">
  862:              <tr class="LC_info_row">
  863:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  864:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  865:              </tr>'.
  866:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
  867:             $rowtotal += 2;
  868:         }
  869:     } else {
  870:         $output .= '
  871:           <tr>
  872:            <td>
  873:             <table class="LC_nested">
  874:              <tr class="LC_info_row">';
  875:         if (($action eq 'login') || ($action eq 'directorysrch')) {
  876:             $output .= '  
  877:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
  878:         } elsif ($action eq 'serverstatuses') {
  879:             $output .= '
  880:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).
  881:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
  882: 
  883:         } else {
  884:             $output .= '
  885:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
  886:         }
  887:         if (defined($item->{'header'}->[0]->{'col3'})) {
  888:             $output .= '<td class="LC_left_item" valign="top">'.
  889:                        &mt($item->{'header'}->[0]->{'col2'});
  890:             if ($action eq 'serverstatuses') {
  891:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
  892:             } 
  893:         } else {
  894:             $output .= '<td class="LC_right_item" valign="top">'.
  895:                        &mt($item->{'header'}->[0]->{'col2'});
  896:         }
  897:         $output .= '</td>';
  898:         if ($item->{'header'}->[0]->{'col3'}) {
  899:             if (defined($item->{'header'}->[0]->{'col4'})) {
  900:                 $output .= '<td class="LC_left_item" valign="top">'.
  901:                             &mt($item->{'header'}->[0]->{'col3'});
  902:             } else {
  903:                 $output .= '<td class="LC_right_item" valign="top">'.
  904:                            &mt($item->{'header'}->[0]->{'col3'});
  905:             }
  906:             if ($action eq 'serverstatuses') {
  907:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
  908:             }
  909:             $output .= '</td>';
  910:         }
  911:         if ($item->{'header'}->[0]->{'col4'}) {
  912:             $output .= '<td class="LC_right_item" valign="top">'.
  913:                        &mt($item->{'header'}->[0]->{'col4'});
  914:         }
  915:         $output .= '</tr>';
  916:         $rowtotal ++;
  917:         if ($action eq 'quotas') {
  918:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  919:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || ($action eq 'directorysrch') ||
  920:                  ($action eq 'contacts') || ($action eq 'serverstatuses') || ($action eq 'loadbalancing') ||
  921:                  ($action eq 'ltitools')) {
  922:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
  923:         } elsif ($action eq 'scantron') {
  924:             $output .= &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
  925:         } elsif ($action eq 'helpsettings') {
  926:             $output .= &print_helpsettings($dom,$confname,$settings,\$rowtotal);
  927:         }
  928:     }
  929:     $output .= '
  930:    </table>
  931:   </td>
  932:  </tr>
  933: </table><br />';
  934:     return ($output,$rowtotal);
  935: }
  936: 
  937: sub print_login {
  938:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
  939:     my ($css_class,$datatable);
  940:     my %choices = &login_choices();
  941: 
  942:     if ($caller eq 'service') {
  943:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
  944:         my $choice = $choices{'disallowlogin'};
  945:         $css_class = ' class="LC_odd_row"';
  946:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
  947:                       '<td align="right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
  948:                       '<th>'.$choices{'server'}.'</th>'.
  949:                       '<th>'.$choices{'serverpath'}.'</th>'.
  950:                       '<th>'.$choices{'custompath'}.'</th>'.
  951:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
  952:         my %disallowed;
  953:         if (ref($settings) eq 'HASH') {
  954:             if (ref($settings->{'loginvia'}) eq 'HASH') {
  955:                %disallowed = %{$settings->{'loginvia'}};
  956:             }
  957:         }
  958:         foreach my $lonhost (sort(keys(%servers))) {
  959:             my $direct = 'selected="selected"';
  960:             if (ref($disallowed{$lonhost}) eq 'HASH') {
  961:                 if ($disallowed{$lonhost}{'server'} ne '') {
  962:                     $direct = '';
  963:                 }
  964:             }
  965:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
  966:                           '<td><select name="'.$lonhost.'_server">'.
  967:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
  968:                           '</option>';
  969:             foreach my $hostid (sort(keys(%servers))) {
  970:                 next if ($servers{$hostid} eq $servers{$lonhost});
  971:                 my $selected = '';
  972:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
  973:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
  974:                         $selected = 'selected="selected"';
  975:                     }
  976:                 }
  977:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
  978:                               $servers{$hostid}.'</option>';
  979:             }
  980:             $datatable .= '</select></td>'.
  981:                           '<td><select name="'.$lonhost.'_serverpath">';
  982:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
  983:                 my $pathname = $path;
  984:                 if ($path eq 'custom') {
  985:                     $pathname = &mt('Custom Path').' ->';
  986:                 }
  987:                 my $selected = '';
  988:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
  989:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
  990:                         $selected = 'selected="selected"';
  991:                     }
  992:                 } elsif ($path eq '') {
  993:                     $selected = 'selected="selected"';
  994:                 }
  995:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
  996:             }
  997:             $datatable .= '</select></td>';
  998:             my ($custom,$exempt);
  999:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1000:                 $custom = $disallowed{$lonhost}{'custompath'};
 1001:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1002:             }
 1003:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1004:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1005:                           '</tr>';
 1006:         }
 1007:         $datatable .= '</table></td></tr>';
 1008:         return $datatable;
 1009:     } elsif ($caller eq 'page') {
 1010:         my %defaultchecked = ( 
 1011:                                'coursecatalog' => 'on',
 1012:                                'helpdesk'      => 'on',
 1013:                                'adminmail'     => 'off',
 1014:                                'newuser'       => 'off',
 1015:                              );
 1016:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1017:         my (%checkedon,%checkedoff);
 1018:         foreach my $item (@toggles) {
 1019:             if ($defaultchecked{$item} eq 'on') { 
 1020:                 $checkedon{$item} = ' checked="checked" ';
 1021:                 $checkedoff{$item} = ' ';
 1022:             } elsif ($defaultchecked{$item} eq 'off') {
 1023:                 $checkedoff{$item} = ' checked="checked" ';
 1024:                 $checkedon{$item} = ' ';
 1025:             }
 1026:         }
 1027:         my @images = ('img','logo','domlogo','login');
 1028:         my @logintext = ('textcol','bgcol');
 1029:         my @bgs = ('pgbg','mainbg','sidebg');
 1030:         my @links = ('link','alink','vlink');
 1031:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1032:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1033:         my (%is_custom,%designs);
 1034:         my %defaults = (
 1035:                        font => $defaultdesign{'login.font'},
 1036:                        );
 1037:         foreach my $item (@images) {
 1038:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1039:             $defaults{'showlogo'}{$item} = 1;
 1040:         }
 1041:         foreach my $item (@bgs) {
 1042:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1043:         }
 1044:         foreach my $item (@logintext) {
 1045:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1046:         }
 1047:         foreach my $item (@links) {
 1048:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1049:         }
 1050:         if (ref($settings) eq 'HASH') {
 1051:             foreach my $item (@toggles) {
 1052:                 if ($settings->{$item} eq '1') {
 1053:                     $checkedon{$item} =  ' checked="checked" ';
 1054:                     $checkedoff{$item} = ' ';
 1055:                 } elsif ($settings->{$item} eq '0') {
 1056:                     $checkedoff{$item} =  ' checked="checked" ';
 1057:                     $checkedon{$item} = ' ';
 1058:                 }
 1059:             }
 1060:             foreach my $item (@images) {
 1061:                 if (defined($settings->{$item})) {
 1062:                     $designs{$item} = $settings->{$item};
 1063:                     $is_custom{$item} = 1;
 1064:                 }
 1065:                 if (defined($settings->{'showlogo'}{$item})) {
 1066:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1067:                 }
 1068:             }
 1069:             foreach my $item (@logintext) {
 1070:                 if ($settings->{$item} ne '') {
 1071:                     $designs{'logintext'}{$item} = $settings->{$item};
 1072:                     $is_custom{$item} = 1;
 1073:                 }
 1074:             }
 1075:             if ($settings->{'font'} ne '') {
 1076:                 $designs{'font'} = $settings->{'font'};
 1077:                 $is_custom{'font'} = 1;
 1078:             }
 1079:             foreach my $item (@bgs) {
 1080:                 if ($settings->{$item} ne '') {
 1081:                     $designs{'bgs'}{$item} = $settings->{$item};
 1082:                     $is_custom{$item} = 1;
 1083:                 }
 1084:             }
 1085:             foreach my $item (@links) {
 1086:                 if ($settings->{$item} ne '') {
 1087:                     $designs{'links'}{$item} = $settings->{$item};
 1088:                     $is_custom{$item} = 1;
 1089:                 }
 1090:             }
 1091:         } else {
 1092:             if ($designhash{$dom.'.login.font'} ne '') {
 1093:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1094:                 $is_custom{'font'} = 1;
 1095:             }
 1096:             foreach my $item (@images) {
 1097:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1098:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1099:                     $is_custom{$item} = 1;
 1100:                 }
 1101:             }
 1102:             foreach my $item (@bgs) {
 1103:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1104:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1105:                     $is_custom{$item} = 1;
 1106:                 }
 1107:             }
 1108:             foreach my $item (@links) {
 1109:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1110:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1111:                     $is_custom{$item} = 1;
 1112:                 }
 1113:             }
 1114:         }
 1115:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1116:                                                       logo => 'Institution Logo',
 1117:                                                       domlogo => 'Domain Logo',
 1118:                                                       login => 'Login box');
 1119:         my $itemcount = 1;
 1120:         foreach my $item (@toggles) {
 1121:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1122:             $datatable .=  
 1123:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1124:                 '</td><td>'.
 1125:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1126:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1127:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1128:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1129:                 '</tr>';
 1130:             $itemcount ++;
 1131:         }
 1132:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1133:         $datatable .= '</tr></table></td></tr>';
 1134:     } elsif ($caller eq 'help') {
 1135:         my ($defaulturl,$defaulttype,%url,%type,%lt,%langchoices);
 1136:         my $switchserver = &check_switchserver($dom,$confname);
 1137:         my $itemcount = 1;
 1138:         $defaulturl = '/adm/loginproblems.html';
 1139:         $defaulttype = 'default';
 1140:         %lt = &Apache::lonlocal::texthash (
 1141:                      del     => 'Delete?',
 1142:                      rep     => 'Replace:',
 1143:                      upl     => 'Upload:',
 1144:                      default => 'Default',
 1145:                      custom  => 'Custom',
 1146:                                              );
 1147:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1148:         my @currlangs;
 1149:         if (ref($settings) eq 'HASH') {
 1150:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1151:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1152:                     next if ($settings->{'helpurl'}{$key} eq '');
 1153:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1154:                     $type{$key} = 'custom';
 1155:                     unless ($key eq 'nolang') {
 1156:                         push(@currlangs,$key);
 1157:                     }
 1158:                 }
 1159:             } elsif ($settings->{'helpurl'} ne '') {
 1160:                 $type{'nolang'} = 'custom';
 1161:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1162:             }
 1163:         }
 1164:         foreach my $lang ('nolang',sort(@currlangs)) {
 1165:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1166:             $datatable .= '<tr'.$css_class.'>';
 1167:             if ($url{$lang} eq '') {
 1168:                 $url{$lang} = $defaulturl;
 1169:             }
 1170:             if ($type{$lang} eq '') {
 1171:                 $type{$lang} = $defaulttype;
 1172:             }
 1173:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1174:             if ($lang eq 'nolang') {
 1175:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1176:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1177:             } else {
 1178:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1179:                                   $langchoices{$lang},
 1180:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1181:             }
 1182:             $datatable .= '</span></td>'."\n".
 1183:                           '<td class="LC_left_item">';
 1184:             if ($type{$lang} eq 'custom') {
 1185:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1186:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1187:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1188:             } else {
 1189:                 $datatable .= $lt{'upl'};
 1190:             }
 1191:             $datatable .='<br />';
 1192:             if ($switchserver) {
 1193:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1194:             } else {
 1195:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1196:             }
 1197:             $datatable .= '</td></tr>';
 1198:             $itemcount ++;
 1199:         }
 1200:         my @addlangs;
 1201:         foreach my $lang (sort(keys(%langchoices))) {
 1202:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1203:             push(@addlangs,$lang);
 1204:         }
 1205:         if (@addlangs > 0) {
 1206:             my %toadd;
 1207:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1208:             $toadd{''} = &mt('Select');
 1209:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1210:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1211:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1212:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1213:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1214:             if ($switchserver) {
 1215:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1216:             } else {
 1217:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1218:             }
 1219:             $datatable .= '</td></tr>';
 1220:             $itemcount ++;
 1221:         }
 1222:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1223:     } elsif ($caller eq 'headtag') {
 1224:         my %domservers = &Apache::lonnet::get_servers($dom);
 1225:         my $choice = $choices{'headtag'};
 1226:         $css_class = ' class="LC_odd_row"';
 1227:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1228:                       '<td align="left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1229:                       '<th>'.$choices{'current'}.'</th>'.
 1230:                       '<th>'.$choices{'action'}.'</th>'.
 1231:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1232:         my (%currurls,%currexempt);
 1233:         if (ref($settings) eq 'HASH') {
 1234:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1235:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1236:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1237:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1238:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1239:                     }
 1240:                 }
 1241:             }
 1242:         }
 1243:         my %lt = &Apache::lonlocal::texthash(
 1244:                                                del  => 'Delete?',
 1245:                                                rep  => 'Replace:',
 1246:                                                upl  => 'Upload:',
 1247:                                                curr => 'View contents',
 1248:                                                none => 'None',
 1249:         );
 1250:         my $switchserver = &check_switchserver($dom,$confname);
 1251:         foreach my $lonhost (sort(keys(%domservers))) {
 1252:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1253:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1254:             if ($currurls{$lonhost}) {
 1255:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1256:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1257:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1258:                               '">'.$lt{'curr'}.'</a></td>'.
 1259:                               '<td><span class="LC_nobreak"><label>'.
 1260:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1261:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1262:             } else {
 1263:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1264:             }
 1265:             $datatable .='<br />';
 1266:             if ($switchserver) {
 1267:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1268:             } else {
 1269:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1270:             }
 1271:             $datatable .= '</td><td><input type="textbox" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1272:         }
 1273:         $datatable .= '</table></td></tr>';
 1274:     }
 1275:     return $datatable;
 1276: }
 1277: 
 1278: sub login_choices {
 1279:     my %choices =
 1280:         &Apache::lonlocal::texthash (
 1281:             coursecatalog => 'Display Course/Community Catalog link?',
 1282:             adminmail     => "Display Administrator's E-mail Address?",
 1283:             helpdesk      => 'Display "Contact Helpdesk" link',
 1284:             disallowlogin => "Login page requests redirected",
 1285:             hostid        => "Server",
 1286:             server        => "Redirect to:",
 1287:             serverpath    => "Path",
 1288:             custompath    => "Custom", 
 1289:             exempt        => "Exempt IP(s)",
 1290:             directlogin   => "No redirect",
 1291:             newuser       => "Link to create a user account",
 1292:             img           => "Header",
 1293:             logo          => "Main Logo",
 1294:             domlogo       => "Domain Logo",
 1295:             login         => "Log-in Header", 
 1296:             textcol       => "Text color",
 1297:             bgcol         => "Box color",
 1298:             bgs           => "Background colors",
 1299:             links         => "Link colors",
 1300:             font          => "Font color",
 1301:             pgbg          => "Header",
 1302:             mainbg        => "Page",
 1303:             sidebg        => "Login box",
 1304:             link          => "Link",
 1305:             alink         => "Active link",
 1306:             vlink         => "Visited link",
 1307:             headtag       => "Custom markup",
 1308:             action        => "Action",
 1309:             current       => "Current",
 1310:         );
 1311:     return %choices;
 1312: }
 1313: 
 1314: sub print_rolecolors {
 1315:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1316:     my %choices = &color_font_choices();
 1317:     my @bgs = ('pgbg','tabbg','sidebg');
 1318:     my @links = ('link','alink','vlink');
 1319:     my @images = ('img');
 1320:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1321:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1322:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1323:     my (%is_custom,%designs);
 1324:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1325:     if (ref($settings) eq 'HASH') {
 1326:         if (ref($settings->{$role}) eq 'HASH') {
 1327:             if ($settings->{$role}->{'img'} ne '') {
 1328:                 $designs{'img'} = $settings->{$role}->{'img'};
 1329:                 $is_custom{'img'} = 1;
 1330:             }
 1331:             if ($settings->{$role}->{'font'} ne '') {
 1332:                 $designs{'font'} = $settings->{$role}->{'font'};
 1333:                 $is_custom{'font'} = 1;
 1334:             }
 1335:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1336:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1337:                 $is_custom{'fontmenu'} = 1;
 1338:             }
 1339:             foreach my $item (@bgs) {
 1340:                 if ($settings->{$role}->{$item} ne '') {
 1341:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1342:                     $is_custom{$item} = 1;
 1343:                 }
 1344:             }
 1345:             foreach my $item (@links) {
 1346:                 if ($settings->{$role}->{$item} ne '') {
 1347:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1348:                     $is_custom{$item} = 1;
 1349:                 }
 1350:             }
 1351:         }
 1352:     } else {
 1353:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1354:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1355:             $is_custom{'img'} = 1;
 1356:         }
 1357:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1358:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1359:             $is_custom{'fontmenu'} = 1; 
 1360:         }
 1361:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1362:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1363:             $is_custom{'font'} = 1;
 1364:         }
 1365:         foreach my $item (@bgs) {
 1366:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1367:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1368:                 $is_custom{$item} = 1;
 1369:             
 1370:             }
 1371:         }
 1372:         foreach my $item (@links) {
 1373:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1374:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1375:                 $is_custom{$item} = 1;
 1376:             }
 1377:         }
 1378:     }
 1379:     my $itemcount = 1;
 1380:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 1381:     $datatable .= '</tr></table></td></tr>';
 1382:     return $datatable;
 1383: }
 1384: 
 1385: sub role_defaults {
 1386:     my ($role,$bgs,$links,$images,$logintext) = @_;
 1387:     my %defaults;
 1388:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 1389:         return %defaults;
 1390:     }
 1391:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1392:     if ($role eq 'login') {
 1393:         %defaults = (
 1394:                        font => $defaultdesign{$role.'.font'},
 1395:                     );
 1396:         if (ref($logintext) eq 'ARRAY') {
 1397:             foreach my $item (@{$logintext}) {
 1398:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 1399:             }
 1400:         }
 1401:         foreach my $item (@{$images}) {
 1402:             $defaults{'showlogo'}{$item} = 1;
 1403:         }
 1404:     } else {
 1405:         %defaults = (
 1406:                        img => $defaultdesign{$role.'.img'},
 1407:                        font => $defaultdesign{$role.'.font'},
 1408:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 1409:                     );
 1410:     }
 1411:     foreach my $item (@{$bgs}) {
 1412:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 1413:     }
 1414:     foreach my $item (@{$links}) {
 1415:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 1416:     }
 1417:     foreach my $item (@{$images}) {
 1418:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 1419:     }
 1420:     return %defaults;
 1421: }
 1422: 
 1423: sub display_color_options {
 1424:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 1425:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 1426:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1427:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1428:     my $datatable = '<tr'.$css_class.'>'.
 1429:         '<td>'.$choices->{'font'}.'</td>';
 1430:     if (!$is_custom->{'font'}) {
 1431:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span id="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 1432:     } else {
 1433:         $datatable .= '<td>&nbsp;</td>';
 1434:     }
 1435:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 1436: 
 1437:     $datatable .= '<td><span class="LC_nobreak">'.
 1438:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 1439:                   ' value="'.$current_color.'" />&nbsp;'.
 1440:                   '&nbsp;</td></tr>';
 1441:     unless ($role eq 'login') { 
 1442:         $datatable .= '<tr'.$css_class.'>'.
 1443:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 1444:         if (!$is_custom->{'fontmenu'}) {
 1445:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span id="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 1446:         } else {
 1447:             $datatable .= '<td>&nbsp;</td>';
 1448:         }
 1449: 	$current_color = $designs->{'fontmenu'} ?
 1450: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 1451:         $datatable .= '<td><span class="LC_nobreak">'.
 1452:                       '<input class="colorchooser" type="text" size="10" name="'
 1453: 		      .$role.'_fontmenu"'.
 1454:                       ' value="'.$current_color.'" />&nbsp;'.
 1455:                       '&nbsp;</td></tr>';
 1456:     }
 1457:     my $switchserver = &check_switchserver($dom,$confname);
 1458:     foreach my $img (@{$images}) {
 1459: 	$itemcount ++;
 1460:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1461:         $datatable .= '<tr'.$css_class.'>'.
 1462:                       '<td>'.$choices->{$img};
 1463:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors);
 1464:         if ($role eq 'login') {
 1465:             if ($img eq 'login') {
 1466:                 $login_hdr_pick =
 1467:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 1468:                 $logincolors =
 1469:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 1470:                                        $designs,$defaults);
 1471:             } elsif ($img ne 'domlogo') {
 1472:                 $datatable.= &logo_display_options($img,$defaults,$designs);
 1473:             }
 1474:         }
 1475:         $datatable .= '</td>';
 1476:         if ($designs->{$img} ne '') {
 1477:             $imgfile = $designs->{$img};
 1478: 	    $img_import = ($imgfile =~ m{^/adm/});
 1479:         } else {
 1480:             $imgfile = $defaults->{$img};
 1481:         }
 1482:         if ($imgfile) {
 1483:             my ($showfile,$fullsize);
 1484:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 1485:                 my $urldir = $1;
 1486:                 my $filename = $2;
 1487:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 1488:                 if (@info) {
 1489:                     my $thumbfile = 'tn-'.$filename;
 1490:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 1491:                     if (@thumb) {
 1492:                         $showfile = $urldir.'/'.$thumbfile;
 1493:                     } else {
 1494:                         $showfile = $imgfile;
 1495:                     }
 1496:                 } else {
 1497:                     $showfile = '';
 1498:                 }
 1499:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 1500:                 $showfile = $imgfile;
 1501:                 my $imgdir = $1;
 1502:                 my $filename = $2;
 1503:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 1504:                     $showfile = "/$imgdir/tn-".$filename;
 1505:                 } else {
 1506:                     my $input = $londocroot.$imgfile;
 1507:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 1508:                     if (!-e $output) {
 1509:                         my ($width,$height) = &thumb_dimensions();
 1510:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 1511:                         if ($fullwidth ne '' && $fullheight ne '') {
 1512:                             if ($fullwidth > $width && $fullheight > $height) { 
 1513:                                 my $size = $width.'x'.$height;
 1514:                                 system("convert -sample $size $input $output");
 1515:                                 $showfile = "/$imgdir/tn-".$filename;
 1516:                             }
 1517:                         }
 1518:                     }
 1519:                 }
 1520:             }
 1521:             if ($showfile) {
 1522:                 if ($showfile =~ m{^/(adm|res)/}) {
 1523:                     if ($showfile =~ m{^/res/}) {
 1524:                         my $local_showfile =
 1525:                             &Apache::lonnet::filelocation('',$showfile);
 1526:                         &Apache::lonnet::repcopy($local_showfile);
 1527:                     }
 1528:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 1529:                 }
 1530:                 if ($imgfile) {
 1531:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 1532:                         if ($imgfile =~ m{^/res/}) {
 1533:                             my $local_imgfile =
 1534:                                 &Apache::lonnet::filelocation('',$imgfile);
 1535:                             &Apache::lonnet::repcopy($local_imgfile);
 1536:                         }
 1537:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 1538:                     } else {
 1539:                         $fullsize = $imgfile;
 1540:                     }
 1541:                 }
 1542:                 $datatable .= '<td>';
 1543:                 if ($img eq 'login') {
 1544:                     $datatable .= $login_hdr_pick;
 1545:                 } 
 1546:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 1547:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 1548:             } else {
 1549:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1550:                               &mt('Upload:').'<br />';
 1551:             }
 1552:         } else {
 1553:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1554:                           &mt('Upload:').'<br />';
 1555:         }
 1556:         if ($switchserver) {
 1557:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1558:         } else {
 1559:             if ($img ne 'login') { # suppress file selection for Log-in header
 1560:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 1561:             }
 1562:         }
 1563:         $datatable .= '</td></tr>';
 1564:     }
 1565:     $itemcount ++;
 1566:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1567:     $datatable .= '<tr'.$css_class.'>'.
 1568:                   '<td>'.$choices->{'bgs'}.'</td>';
 1569:     my $bgs_def;
 1570:     foreach my $item (@{$bgs}) {
 1571:         if (!$is_custom->{$item}) {
 1572:             $bgs_def .= '<td><span class="LC_nobreak">'.$choices->{$item}.'</span>&nbsp;<span id="css_default_'.$role.'_'.$item.'" style="background-color: '.$defaults->{'bgs'}{$item}.';">&nbsp;&nbsp;&nbsp;</span><br />'.$defaults->{'bgs'}{$item}.'</td>';
 1573:         }
 1574:     }
 1575:     if ($bgs_def) {
 1576:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 1577:     } else {
 1578:         $datatable .= '<td>&nbsp;</td>';
 1579:     }
 1580:     $datatable .= '<td class="LC_right_item">'.
 1581:                   '<table border="0"><tr>';
 1582: 
 1583:     foreach my $item (@{$bgs}) {
 1584:         $datatable .= '<td align="center">'.$choices->{$item};
 1585: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 1586:         if ($designs->{'bgs'}{$item}) {
 1587:             $datatable .= '&nbsp;';
 1588:         }
 1589:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 1590:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 1591:     }
 1592:     $datatable .= '</tr></table></td></tr>';
 1593:     $itemcount ++;
 1594:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1595:     $datatable .= '<tr'.$css_class.'>'.
 1596:                   '<td>'.$choices->{'links'}.'</td>';
 1597:     my $links_def;
 1598:     foreach my $item (@{$links}) {
 1599:         if (!$is_custom->{$item}) {
 1600:             $links_def .= '<td>'.$choices->{$item}.'<br /><span id="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 1601:         }
 1602:     }
 1603:     if ($links_def) {
 1604:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 1605:     } else {
 1606:         $datatable .= '<td>&nbsp;</td>';
 1607:     }
 1608:     $datatable .= '<td class="LC_right_item">'.
 1609:                   '<table border="0"><tr>';
 1610:     foreach my $item (@{$links}) {
 1611: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 1612:         $datatable .= '<td align="center">'.$choices->{$item}."\n";
 1613:         if ($designs->{'links'}{$item}) {
 1614:             $datatable.='&nbsp;';
 1615:         }
 1616:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 1617:                       '" /></td>';
 1618:     }
 1619:     $$rowtotal += $itemcount;
 1620:     return $datatable;
 1621: }
 1622: 
 1623: sub logo_display_options {
 1624:     my ($img,$defaults,$designs) = @_;
 1625:     my $checkedon;
 1626:     if (ref($defaults) eq 'HASH') {
 1627:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 1628:             if ($defaults->{'showlogo'}{$img}) {
 1629:                 $checkedon = 'checked="checked" ';     
 1630:             }
 1631:         } 
 1632:     }
 1633:     if (ref($designs) eq 'HASH') {
 1634:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 1635:             if (defined($designs->{'showlogo'}{$img})) {
 1636:                 if ($designs->{'showlogo'}{$img} == 0) {
 1637:                     $checkedon = '';
 1638:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 1639:                     $checkedon = 'checked="checked" ';
 1640:                 }
 1641:             }
 1642:         }
 1643:     }
 1644:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 1645:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 1646:            &mt('show').'</label>'."\n";
 1647: }
 1648: 
 1649: sub login_header_options  {
 1650:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 1651:     my $output = '';
 1652:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 1653:         $output .= &mt('Text default(s):').'<br />';
 1654:         if (!$is_custom->{'textcol'}) {
 1655:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 1656:                        '&nbsp;&nbsp;&nbsp;';
 1657:         }
 1658:         if (!$is_custom->{'bgcol'}) {
 1659:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 1660:                        '<span id="css_'.$role.'_font" style="background-color: '.
 1661:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 1662:         }
 1663:         $output .= '<br />';
 1664:     }
 1665:     $output .='<br />';
 1666:     return $output;
 1667: }
 1668: 
 1669: sub login_text_colors {
 1670:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 1671:     my $color_menu = '<table border="0"><tr>';
 1672:     foreach my $item (@{$logintext}) {
 1673:         $color_menu .= '<td align="center">'.$choices->{$item};
 1674:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 1675:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 1676:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 1677:     }
 1678:     $color_menu .= '</tr></table><br />';
 1679:     return $color_menu;
 1680: }
 1681: 
 1682: sub image_changes {
 1683:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 1684:     my $output;
 1685:     if ($img eq 'login') {
 1686:             # suppress image for Log-in header
 1687:     } elsif (!$is_custom) {
 1688:         if ($img ne 'domlogo') {
 1689:             $output .= &mt('Default image:').'<br />';
 1690:         } else {
 1691:             $output .= &mt('Default in use:').'<br />';
 1692:         }
 1693:     }
 1694:     if ($img eq 'login') { # suppress image for Log-in header
 1695:         $output .= '<td>'.$logincolors;
 1696:     } else {
 1697:         if ($img_import) {
 1698:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 1699:         }
 1700:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 1701:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 1702:         if ($is_custom) {
 1703:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 1704:                        '<input type="checkbox" name="'.
 1705:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 1706:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 1707:         } else {
 1708:             $output .= '<td valign="middle">'.$logincolors.&mt('Upload:').'<br />';
 1709:         }
 1710:     }
 1711:     return $output;
 1712: }
 1713: 
 1714: sub print_quotas {
 1715:     my ($dom,$settings,$rowtotal,$action) = @_;
 1716:     my $context;
 1717:     if ($action eq 'quotas') {
 1718:         $context = 'tools';
 1719:     } else {
 1720:         $context = $action;
 1721:     }
 1722:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 1723:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 1724:     my $typecount = 0;
 1725:     my ($css_class,%titles);
 1726:     if ($context eq 'requestcourses') {
 1727:         @usertools = ('official','unofficial','community','textbook','placement');
 1728:         @options =('norequest','approval','validate','autolimit');
 1729:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 1730:         %titles = &courserequest_titles();
 1731:     } elsif ($context eq 'requestauthor') {
 1732:         @usertools = ('author');
 1733:         @options = ('norequest','approval','automatic');
 1734:         %titles = &authorrequest_titles();
 1735:     } else {
 1736:         @usertools = ('aboutme','blog','webdav','portfolio');
 1737:         %titles = &tool_titles();
 1738:     }
 1739:     if (ref($types) eq 'ARRAY') {
 1740:         foreach my $type (@{$types}) {
 1741:             my ($currdefquota,$currauthorquota);
 1742:             unless (($context eq 'requestcourses') ||
 1743:                     ($context eq 'requestauthor')) {
 1744:                 if (ref($settings) eq 'HASH') {
 1745:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 1746:                         $currdefquota = $settings->{defaultquota}->{$type};
 1747:                     } else {
 1748:                         $currdefquota = $settings->{$type};
 1749:                     }
 1750:                     if (ref($settings->{authorquota}) eq 'HASH') {
 1751:                         $currauthorquota = $settings->{authorquota}->{$type};
 1752:                     }
 1753:                 }
 1754:             }
 1755:             if (defined($usertypes->{$type})) {
 1756:                 $typecount ++;
 1757:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 1758:                 $datatable .= '<tr'.$css_class.'>'.
 1759:                               '<td>'.$usertypes->{$type}.'</td>'.
 1760:                               '<td class="LC_left_item">';
 1761:                 if ($context eq 'requestcourses') {
 1762:                     $datatable .= '<table><tr>';
 1763:                 }
 1764:                 my %cell;  
 1765:                 foreach my $item (@usertools) {
 1766:                     if ($context eq 'requestcourses') {
 1767:                         my ($curroption,$currlimit);
 1768:                         if (ref($settings) eq 'HASH') {
 1769:                             if (ref($settings->{$item}) eq 'HASH') {
 1770:                                 $curroption = $settings->{$item}->{$type};
 1771:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 1772:                                     $currlimit = $1; 
 1773:                                 }
 1774:                             }
 1775:                         }
 1776:                         if (!$curroption) {
 1777:                             $curroption = 'norequest';
 1778:                         }
 1779:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 1780:                         foreach my $option (@options) {
 1781:                             my $val = $option;
 1782:                             if ($option eq 'norequest') {
 1783:                                 $val = 0;  
 1784:                             }
 1785:                             if ($option eq 'validate') {
 1786:                                 my $canvalidate = 0;
 1787:                                 if (ref($validations{$item}) eq 'HASH') { 
 1788:                                     if ($validations{$item}{$type}) {
 1789:                                         $canvalidate = 1;
 1790:                                     }
 1791:                                 }
 1792:                                 next if (!$canvalidate);
 1793:                             }
 1794:                             my $checked = '';
 1795:                             if ($option eq $curroption) {
 1796:                                 $checked = ' checked="checked"';
 1797:                             } elsif ($option eq 'autolimit') {
 1798:                                 if ($curroption =~ /^autolimit/) {
 1799:                                     $checked = ' checked="checked"';
 1800:                                 }                       
 1801:                             } 
 1802:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 1803:                                   '<input type="radio" name="crsreq_'.$item.
 1804:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 1805:                                   $titles{$option}.'</label>';
 1806:                             if ($option eq 'autolimit') {
 1807:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 1808:                                                 $item.'_limit_'.$type.'" size="1" '.
 1809:                                                 'value="'.$currlimit.'" />';
 1810:                             }
 1811:                             $cell{$item} .= '</span> ';
 1812:                             if ($option eq 'autolimit') {
 1813:                                 $cell{$item} .= $titles{'unlimited'};
 1814:                             }
 1815:                         }
 1816:                     } elsif ($context eq 'requestauthor') {
 1817:                         my $curroption;
 1818:                         if (ref($settings) eq 'HASH') {
 1819:                             $curroption = $settings->{$type};
 1820:                         }
 1821:                         if (!$curroption) {
 1822:                             $curroption = 'norequest';
 1823:                         }
 1824:                         foreach my $option (@options) {
 1825:                             my $val = $option;
 1826:                             if ($option eq 'norequest') {
 1827:                                 $val = 0;
 1828:                             }
 1829:                             my $checked = '';
 1830:                             if ($option eq $curroption) {
 1831:                                 $checked = ' checked="checked"';
 1832:                             }
 1833:                             $datatable .= '<span class="LC_nobreak"><label>'.
 1834:                                   '<input type="radio" name="authorreq_'.$type.
 1835:                                   '" value="'.$val.'"'.$checked.' />'.
 1836:                                   $titles{$option}.'</label></span>&nbsp; ';
 1837:                         }
 1838:                     } else {
 1839:                         my $checked = 'checked="checked" ';
 1840:                         if (ref($settings) eq 'HASH') {
 1841:                             if (ref($settings->{$item}) eq 'HASH') {
 1842:                                 if ($settings->{$item}->{$type} == 0) {
 1843:                                     $checked = '';
 1844:                                 } elsif ($settings->{$item}->{$type} == 1) {
 1845:                                     $checked =  'checked="checked" ';
 1846:                                 }
 1847:                             }
 1848:                         }
 1849:                         $datatable .= '<span class="LC_nobreak"><label>'.
 1850:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 1851:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 1852:                                       '</label></span>&nbsp; ';
 1853:                     }
 1854:                 }
 1855:                 if ($context eq 'requestcourses') {
 1856:                     $datatable .= '</tr><tr>';
 1857:                     foreach my $item (@usertools) {
 1858:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 1859:                     }
 1860:                     $datatable .= '</tr></table>';
 1861:                 }
 1862:                 $datatable .= '</td>';
 1863:                 unless (($context eq 'requestcourses') ||
 1864:                         ($context eq 'requestauthor')) {
 1865:                     $datatable .= 
 1866:                               '<td class="LC_right_item">'.
 1867:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 1868:                               '<input type="text" name="quota_'.$type.
 1869:                               '" value="'.$currdefquota.
 1870:                               '" size="5" /></span>'.('&nbsp;' x 2).
 1871:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 1872:                               '<input type="text" name="authorquota_'.$type.
 1873:                               '" value="'.$currauthorquota.
 1874:                               '" size="5" /></span></td>';
 1875:                 }
 1876:                 $datatable .= '</tr>';
 1877:             }
 1878:         }
 1879:     }
 1880:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 1881:         $defaultquota = '20';
 1882:         $authorquota = '500';
 1883:         if (ref($settings) eq 'HASH') {
 1884:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 1885:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 1886:             } elsif (defined($settings->{'default'})) {
 1887:                 $defaultquota = $settings->{'default'};
 1888:             }
 1889:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 1890:                 $authorquota = $settings->{'authorquota'}->{'default'};
 1891:             }
 1892:         }
 1893:     }
 1894:     $typecount ++;
 1895:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 1896:     $datatable .= '<tr'.$css_class.'>'.
 1897:                   '<td>'.$othertitle.'</td>'.
 1898:                   '<td class="LC_left_item">';
 1899:     if ($context eq 'requestcourses') {
 1900:         $datatable .= '<table><tr>';
 1901:     }
 1902:     my %defcell;
 1903:     foreach my $item (@usertools) {
 1904:         if ($context eq 'requestcourses') {
 1905:             my ($curroption,$currlimit);
 1906:             if (ref($settings) eq 'HASH') {
 1907:                 if (ref($settings->{$item}) eq 'HASH') {
 1908:                     $curroption = $settings->{$item}->{'default'};
 1909:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 1910:                         $currlimit = $1;
 1911:                     }
 1912:                 }
 1913:             }
 1914:             if (!$curroption) {
 1915:                 $curroption = 'norequest';
 1916:             }
 1917:             $datatable .= '<th>'.$titles{$item}.'</th>';
 1918:             foreach my $option (@options) {
 1919:                 my $val = $option;
 1920:                 if ($option eq 'norequest') {
 1921:                     $val = 0;
 1922:                 }
 1923:                 if ($option eq 'validate') {
 1924:                     my $canvalidate = 0;
 1925:                     if (ref($validations{$item}) eq 'HASH') {
 1926:                         if ($validations{$item}{'default'}) {
 1927:                             $canvalidate = 1;
 1928:                         }
 1929:                     }
 1930:                     next if (!$canvalidate);
 1931:                 }
 1932:                 my $checked = '';
 1933:                 if ($option eq $curroption) {
 1934:                     $checked = ' checked="checked"';
 1935:                 } elsif ($option eq 'autolimit') {
 1936:                     if ($curroption =~ /^autolimit/) {
 1937:                         $checked = ' checked="checked"';
 1938:                     }
 1939:                 }
 1940:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 1941:                                   '<input type="radio" name="crsreq_'.$item.
 1942:                                   '_default" value="'.$val.'"'.$checked.' />'.
 1943:                                   $titles{$option}.'</label>';
 1944:                 if ($option eq 'autolimit') {
 1945:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 1946:                                        $item.'_limit_default" size="1" '.
 1947:                                        'value="'.$currlimit.'" />';
 1948:                 }
 1949:                 $defcell{$item} .= '</span> ';
 1950:                 if ($option eq 'autolimit') {
 1951:                     $defcell{$item} .= $titles{'unlimited'};
 1952:                 }
 1953:             }
 1954:         } elsif ($context eq 'requestauthor') {
 1955:             my $curroption;
 1956:             if (ref($settings) eq 'HASH') {
 1957:                 $curroption = $settings->{'default'};
 1958:             }
 1959:             if (!$curroption) {
 1960:                 $curroption = 'norequest';
 1961:             }
 1962:             foreach my $option (@options) {
 1963:                 my $val = $option;
 1964:                 if ($option eq 'norequest') {
 1965:                     $val = 0;
 1966:                 }
 1967:                 my $checked = '';
 1968:                 if ($option eq $curroption) {
 1969:                     $checked = ' checked="checked"';
 1970:                 }
 1971:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1972:                               '<input type="radio" name="authorreq_default"'.
 1973:                               ' value="'.$val.'"'.$checked.' />'.
 1974:                               $titles{$option}.'</label></span>&nbsp; ';
 1975:             }
 1976:         } else {
 1977:             my $checked = 'checked="checked" ';
 1978:             if (ref($settings) eq 'HASH') {
 1979:                 if (ref($settings->{$item}) eq 'HASH') {
 1980:                     if ($settings->{$item}->{'default'} == 0) {
 1981:                         $checked = '';
 1982:                     } elsif ($settings->{$item}->{'default'} == 1) {
 1983:                         $checked = 'checked="checked" ';
 1984:                     }
 1985:                 }
 1986:             }
 1987:             $datatable .= '<span class="LC_nobreak"><label>'.
 1988:                           '<input type="checkbox" name="'.$context.'_'.$item.
 1989:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 1990:                           '</label></span>&nbsp; ';
 1991:         }
 1992:     }
 1993:     if ($context eq 'requestcourses') {
 1994:         $datatable .= '</tr><tr>';
 1995:         foreach my $item (@usertools) {
 1996:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 1997:         }
 1998:         $datatable .= '</tr></table>';
 1999:     }
 2000:     $datatable .= '</td>';
 2001:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2002:         $datatable .= '<td class="LC_right_item">'.
 2003:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2004:                       '<input type="text" name="defaultquota" value="'.
 2005:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2006:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2007:                       '<input type="text" name="authorquota" value="'.
 2008:                       $authorquota.'" size="5" /></span></td>';
 2009:     }
 2010:     $datatable .= '</tr>';
 2011:     $typecount ++;
 2012:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2013:     $datatable .= '<tr'.$css_class.'>'.
 2014:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2015:     if ($context eq 'requestcourses') {
 2016:         $datatable .= &mt('(overrides affiliation, if set)').
 2017:                       '</td>'.
 2018:                       '<td class="LC_left_item">'.
 2019:                       '<table><tr>';
 2020:     } else {
 2021:         $datatable .= &mt('(overrides affiliation, if checked)').
 2022:                       '</td>'.
 2023:                       '<td class="LC_left_item" colspan="2">'.
 2024:                       '<br />';
 2025:     }
 2026:     my %advcell;
 2027:     foreach my $item (@usertools) {
 2028:         if ($context eq 'requestcourses') {
 2029:             my ($curroption,$currlimit);
 2030:             if (ref($settings) eq 'HASH') {
 2031:                 if (ref($settings->{$item}) eq 'HASH') {
 2032:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2033:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2034:                         $currlimit = $1;
 2035:                     }
 2036:                 }
 2037:             }
 2038:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2039:             my $checked = '';
 2040:             if ($curroption eq '') {
 2041:                 $checked = ' checked="checked"';
 2042:             }
 2043:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2044:                                '<input type="radio" name="crsreq_'.$item.
 2045:                                '__LC_adv" value=""'.$checked.' />'.
 2046:                                &mt('No override set').'</label></span>&nbsp; ';
 2047:             foreach my $option (@options) {
 2048:                 my $val = $option;
 2049:                 if ($option eq 'norequest') {
 2050:                     $val = 0;
 2051:                 }
 2052:                 if ($option eq 'validate') {
 2053:                     my $canvalidate = 0;
 2054:                     if (ref($validations{$item}) eq 'HASH') {
 2055:                         if ($validations{$item}{'_LC_adv'}) {
 2056:                             $canvalidate = 1;
 2057:                         }
 2058:                     }
 2059:                     next if (!$canvalidate);
 2060:                 }
 2061:                 my $checked = '';
 2062:                 if ($val eq $curroption) {
 2063:                     $checked = ' checked="checked"';
 2064:                 } elsif ($option eq 'autolimit') {
 2065:                     if ($curroption =~ /^autolimit/) {
 2066:                         $checked = ' checked="checked"';
 2067:                     }
 2068:                 }
 2069:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2070:                                   '<input type="radio" name="crsreq_'.$item.
 2071:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2072:                                   $titles{$option}.'</label>';
 2073:                 if ($option eq 'autolimit') {
 2074:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2075:                                        $item.'_limit__LC_adv" size="1" '.
 2076:                                        'value="'.$currlimit.'" />';
 2077:                 }
 2078:                 $advcell{$item} .= '</span> ';
 2079:                 if ($option eq 'autolimit') {
 2080:                     $advcell{$item} .= $titles{'unlimited'};
 2081:                 }
 2082:             }
 2083:         } elsif ($context eq 'requestauthor') {
 2084:             my $curroption;
 2085:             if (ref($settings) eq 'HASH') {
 2086:                 $curroption = $settings->{'_LC_adv'};
 2087:             }
 2088:             my $checked = '';
 2089:             if ($curroption eq '') {
 2090:                 $checked = ' checked="checked"';
 2091:             }
 2092:             $datatable .= '<span class="LC_nobreak"><label>'.
 2093:                           '<input type="radio" name="authorreq__LC_adv"'.
 2094:                           ' value=""'.$checked.' />'.
 2095:                           &mt('No override set').'</label></span>&nbsp; ';
 2096:             foreach my $option (@options) {
 2097:                 my $val = $option;
 2098:                 if ($option eq 'norequest') {
 2099:                     $val = 0;
 2100:                 }
 2101:                 my $checked = '';
 2102:                 if ($val eq $curroption) {
 2103:                     $checked = ' checked="checked"';
 2104:                 }
 2105:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2106:                               '<input type="radio" name="authorreq__LC_adv"'.
 2107:                               ' value="'.$val.'"'.$checked.' />'.
 2108:                               $titles{$option}.'</label></span>&nbsp; ';
 2109:             }
 2110:         } else {
 2111:             my $checked = 'checked="checked" ';
 2112:             if (ref($settings) eq 'HASH') {
 2113:                 if (ref($settings->{$item}) eq 'HASH') {
 2114:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2115:                         $checked = '';
 2116:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2117:                         $checked = 'checked="checked" ';
 2118:                     }
 2119:                 }
 2120:             }
 2121:             $datatable .= '<span class="LC_nobreak"><label>'.
 2122:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2123:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2124:                           '</label></span>&nbsp; ';
 2125:         }
 2126:     }
 2127:     if ($context eq 'requestcourses') {
 2128:         $datatable .= '</tr><tr>';
 2129:         foreach my $item (@usertools) {
 2130:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2131:         }
 2132:         $datatable .= '</tr></table>';
 2133:     }
 2134:     $datatable .= '</td></tr>';
 2135:     $$rowtotal += $typecount;
 2136:     return $datatable;
 2137: }
 2138: 
 2139: sub print_requestmail {
 2140:     my ($dom,$action,$settings,$rowtotal) = @_;
 2141:     my ($now,$datatable,%currapp);
 2142:     $now = time;
 2143:     if (ref($settings) eq 'HASH') {
 2144:         if (ref($settings->{'notify'}) eq 'HASH') {
 2145:             if ($settings->{'notify'}{'approval'} ne '') {
 2146:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2147:             }
 2148:         }
 2149:     }
 2150:     my $numinrow = 2;
 2151:     my $css_class;
 2152:     $css_class = ($$rowtotal%2? ' class="LC_odd_row"':'');
 2153:     my $text;
 2154:     if ($action eq 'requestcourses') {
 2155:         $text = &mt('Receive notification of course requests requiring approval');
 2156:     } elsif ($action eq 'requestauthor') {
 2157:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2158:     } else {
 2159:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2160:     }
 2161:     $datatable = '<tr'.$css_class.'>'.
 2162:                  ' <td>'.$text.'</td>'.
 2163:                  ' <td class="LC_left_item">';
 2164:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2165:                                                  $action.'notifyapproval',%currapp);
 2166:     if ($numdc > 0) {
 2167:         $datatable .= $table;
 2168:     } else {
 2169:         $datatable .= &mt('There are no active Domain Coordinators');
 2170:     }
 2171:     $datatable .='</td></tr>';
 2172:     return $datatable;
 2173: }
 2174: 
 2175: sub print_studentcode {
 2176:     my ($settings,$rowtotal) = @_;
 2177:     my $rownum = 0; 
 2178:     my ($output,%current);
 2179:     my @crstypes = ('official','unofficial','community','textbook','placement');
 2180:     if (ref($settings) eq 'HASH') {
 2181:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2182:             foreach my $type (@crstypes) {
 2183:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2184:             }
 2185:         }
 2186:     }
 2187:     $output .= '<tr>'.
 2188:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2189:                '<td class="LC_left_item">';
 2190:     foreach my $type (@crstypes) {
 2191:         my $check = ' ';
 2192:         if ($current{$type}) {
 2193:             $check = ' checked="checked" ';
 2194:         }
 2195:         $output .= '<span class="LC_nobreak"><label>'.
 2196:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2197:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2198:     }
 2199:     $output .= '</td></tr>';
 2200:     $$rowtotal ++;
 2201:     return $output;
 2202: }
 2203: 
 2204: sub print_textbookcourses {
 2205:     my ($dom,$type,$settings,$rowtotal) = @_;
 2206:     my $rownum = 0;
 2207:     my $css_class;
 2208:     my $itemcount = 1;
 2209:     my $maxnum = 0;
 2210:     my $bookshash;
 2211:     if (ref($settings) eq 'HASH') {
 2212:         $bookshash = $settings->{$type};
 2213:     }
 2214:     my %ordered;
 2215:     if (ref($bookshash) eq 'HASH') {
 2216:         foreach my $item (keys(%{$bookshash})) {
 2217:             if (ref($bookshash->{$item}) eq 'HASH') {
 2218:                 my $num = $bookshash->{$item}{'order'};
 2219:                 $ordered{$num} = $item;
 2220:             }
 2221:         }
 2222:     }
 2223:     my $confname = $dom.'-domainconfig';
 2224:     my $switchserver = &check_switchserver($dom,$confname);
 2225:     my $maxnum = scalar(keys(%ordered));
 2226:     my $datatable;
 2227:     if (keys(%ordered)) {
 2228:         my @items = sort { $a <=> $b } keys(%ordered);
 2229:         for (my $i=0; $i<@items; $i++) {
 2230:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2231:             my $key = $ordered{$items[$i]};
 2232:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2233:             my $coursetitle = $coursehash{'description'};
 2234:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2235:             if (ref($bookshash->{$key}) eq 'HASH') {
 2236:                 $subject = $bookshash->{$key}->{'subject'};
 2237:                 $title = $bookshash->{$key}->{'title'};
 2238:                 if ($type eq 'textbooks') {
 2239:                     $publisher = $bookshash->{$key}->{'publisher'};
 2240:                     $author = $bookshash->{$key}->{'author'};
 2241:                     $image = $bookshash->{$key}->{'image'};
 2242:                     if ($image ne '') {
 2243:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2244:                         my $imagethumb = "$path/tn-".$imagefile;
 2245:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2246:                     }
 2247:                 }
 2248:             }
 2249:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2250:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2251:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2252:             for (my $k=0; $k<=$maxnum; $k++) {
 2253:                 my $vpos = $k+1;
 2254:                 my $selstr;
 2255:                 if ($k == $i) {
 2256:                     $selstr = ' selected="selected" ';
 2257:                 }
 2258:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2259:             }
 2260:             $datatable .= '</select>'.('&nbsp;'x2).
 2261:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2262:                 &mt('Delete?').'</label></span></td>'.
 2263:                 '<td colspan="2">'.
 2264:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2265:                 ('&nbsp;'x2).
 2266:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2267:             if ($type eq 'textbooks') {
 2268:                 $datatable .= ('&nbsp;'x2).
 2269:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2270:                               ('&nbsp;'x2).
 2271:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2272:                               ('&nbsp;'x2).
 2273:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2274:                 if ($image) {
 2275:                     $datatable .= $imgsrc.
 2276:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2277:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2278:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2279:                 }
 2280:                 if ($switchserver) {
 2281:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2282:                 } else {
 2283:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2284:                 }
 2285:             }
 2286:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2287:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2288:                           $coursetitle.'</span></td></tr>'."\n";
 2289:             $itemcount ++;
 2290:         }
 2291:     }
 2292:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2293:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2294:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2295:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2296:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2297:     for (my $k=0; $k<$maxnum+1; $k++) {
 2298:         my $vpos = $k+1;
 2299:         my $selstr;
 2300:         if ($k == $maxnum) {
 2301:             $selstr = ' selected="selected" ';
 2302:         }
 2303:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2304:     }
 2305:     $datatable .= '</select>&nbsp;'."\n".
 2306:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</td>'."\n".
 2307:                   '<td colspan="2">'.
 2308:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2309:                   ('&nbsp;'x2).
 2310:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2311:                   ('&nbsp;'x2);
 2312:     if ($type eq 'textbooks') {
 2313:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2314:                       ('&nbsp;'x2).
 2315:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2316:                       ('&nbsp;'x2).
 2317:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2318:         if ($switchserver) {
 2319:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2320:         } else {
 2321:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2322:         }
 2323:     }
 2324:     $datatable .= '</span>'."\n".
 2325:                   '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2326:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2327:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2328:                   &Apache::loncommon::selectcourse_link
 2329:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course');
 2330:                   '</span></td>'."\n".
 2331:                   '</tr>'."\n";
 2332:     $itemcount ++;
 2333:     return $datatable;
 2334: }
 2335: 
 2336: sub textbookcourses_javascript {
 2337:     my ($settings) = @_;
 2338:     return unless(ref($settings) eq 'HASH');
 2339:     my (%ordered,%total,%jstext);
 2340:     foreach my $type ('textbooks','templates') {
 2341:         $total{$type} = 0;
 2342:         if (ref($settings->{$type}) eq 'HASH') {
 2343:             foreach my $item (keys(%{$settings->{$type}})) {
 2344:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2345:                     my $num = $settings->{$type}->{$item}{'order'};
 2346:                     $ordered{$type}{$num} = $item;
 2347:                 }
 2348:             }
 2349:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2350:         }
 2351:         my @jsarray = ();
 2352:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 2353:             push(@jsarray,$ordered{$type}{$item});
 2354:         }
 2355:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 2356:     }
 2357:     return <<"ENDSCRIPT";
 2358: <script type="text/javascript">
 2359: // <![CDATA[
 2360: function reorderBooks(form,item,caller) {
 2361:     var changedVal;
 2362: $jstext{'textbooks'};
 2363: $jstext{'templates'};
 2364:     var newpos;
 2365:     var maxh;
 2366:     if (caller == 'textbooks') {  
 2367:         newpos = 'textbooks_addbook_pos';
 2368:         maxh = 1 + $total{'textbooks'};
 2369:     } else {
 2370:         newpos = 'templates_addbook_pos';
 2371:         maxh = 1 + $total{'templates'};
 2372:     }
 2373:     var current = new Array;
 2374:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2375:     if (item == newpos) {
 2376:         changedVal = newitemVal;
 2377:     } else {
 2378:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2379:         current[newitemVal] = newpos;
 2380:     }
 2381:     if (caller == 'textbooks') {
 2382:         for (var i=0; i<textbooks.length; i++) {
 2383:             var elementName = 'textbooks_'+textbooks[i];
 2384:             if (elementName != item) {
 2385:                 if (form.elements[elementName]) {
 2386:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2387:                     current[currVal] = elementName;
 2388:                 }
 2389:             }
 2390:         }
 2391:     }
 2392:     if (caller == 'templates') {
 2393:         for (var i=0; i<templates.length; i++) {
 2394:             var elementName = 'templates_'+templates[i];
 2395:             if (elementName != item) {
 2396:                 if (form.elements[elementName]) {
 2397:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2398:                     current[currVal] = elementName;
 2399:                 }
 2400:             }
 2401:         }
 2402:     }
 2403:     var oldVal;
 2404:     for (var j=0; j<maxh; j++) {
 2405:         if (current[j] == undefined) {
 2406:             oldVal = j;
 2407:         }
 2408:     }
 2409:     if (oldVal < changedVal) {
 2410:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2411:            var elementName = current[k];
 2412:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2413:         }
 2414:     } else {
 2415:         for (var k=changedVal; k<oldVal; k++) {
 2416:             var elementName = current[k];
 2417:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2418:         }
 2419:     }
 2420:     return;
 2421: }
 2422: 
 2423: // ]]>
 2424: </script>
 2425: 
 2426: ENDSCRIPT
 2427: }
 2428: 
 2429: sub ltitools_javascript {
 2430:     my ($settings) = @_;
 2431:     return unless(ref($settings) eq 'HASH');
 2432:     my (%ordered,$total,%jstext);
 2433:     $total = 0;
 2434:     foreach my $item (keys(%{$settings})) {
 2435:         if (ref($settings->{$item}) eq 'HASH') {
 2436:             my $num = $settings->{$item}{'order'};
 2437:             $ordered{$num} = $item;
 2438:         }
 2439:     }
 2440:     $total = scalar(keys(%{$settings}));
 2441:     my @jsarray = ();
 2442:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 2443:         push(@jsarray,$ordered{$item});
 2444:     }
 2445:     my $jstext = '    var ltitools = Array('."'".join("','",@jsarray)."'".');'."\n";
 2446:     return <<"ENDSCRIPT";
 2447: <script type="text/javascript">
 2448: // <![CDATA[
 2449: function reorderLTI(form,item) {
 2450:     var changedVal;
 2451: $jstext
 2452:     var newpos = 'ltitools_add_pos';
 2453:     var maxh = 1 + $total;
 2454:     var current = new Array;
 2455:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2456:     if (item == newpos) {
 2457:         changedVal = newitemVal;
 2458:     } else {
 2459:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2460:         current[newitemVal] = newpos;
 2461:     }
 2462:     for (var i=0; i<ltitools.length; i++) {
 2463:         var elementName = 'ltitools_'+ltitools[i];
 2464:         if (elementName != item) {
 2465:             if (form.elements[elementName]) {
 2466:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2467:                 current[currVal] = elementName;
 2468:             }
 2469:         }
 2470:     }
 2471:     var oldVal;
 2472:     for (var j=0; j<maxh; j++) {
 2473:         if (current[j] == undefined) {
 2474:             oldVal = j;
 2475:         }
 2476:     }
 2477:     if (oldVal < changedVal) {
 2478:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2479:            var elementName = current[k];
 2480:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2481:         }
 2482:     } else {
 2483:         for (var k=changedVal; k<oldVal; k++) {
 2484:             var elementName = current[k];
 2485:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2486:         }
 2487:     }
 2488:     return;
 2489: }
 2490: 
 2491: // ]]>
 2492: </script>
 2493: 
 2494: ENDSCRIPT
 2495: }
 2496: 
 2497: sub print_autoenroll {
 2498:     my ($dom,$settings,$rowtotal) = @_;
 2499:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 2500:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff);
 2501:     if (ref($settings) eq 'HASH') {
 2502:         if (exists($settings->{'run'})) {
 2503:             if ($settings->{'run'} eq '0') {
 2504:                 $runoff = ' checked="checked" ';
 2505:                 $runon = ' ';
 2506:             } else {
 2507:                 $runon = ' checked="checked" ';
 2508:                 $runoff = ' ';
 2509:             }
 2510:         } else {
 2511:             if ($autorun) {
 2512:                 $runon = ' checked="checked" ';
 2513:                 $runoff = ' ';
 2514:             } else {
 2515:                 $runoff = ' checked="checked" ';
 2516:                 $runon = ' ';
 2517:             }
 2518:         }
 2519:         if (exists($settings->{'co-owners'})) {
 2520:             if ($settings->{'co-owners'} eq '0') {
 2521:                 $coownersoff = ' checked="checked" ';
 2522:                 $coownerson = ' ';
 2523:             } else {
 2524:                 $coownerson = ' checked="checked" ';
 2525:                 $coownersoff = ' ';
 2526:             }
 2527:         } else {
 2528:             $coownersoff = ' checked="checked" ';
 2529:             $coownerson = ' ';
 2530:         }
 2531:         if (exists($settings->{'sender_domain'})) {
 2532:             $defdom = $settings->{'sender_domain'};
 2533:         }
 2534:     } else {
 2535:         if ($autorun) {
 2536:             $runon = ' checked="checked" ';
 2537:             $runoff = ' ';
 2538:         } else {
 2539:             $runoff = ' checked="checked" ';
 2540:             $runon = ' ';
 2541:         }
 2542:     }
 2543:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 2544:     my $notif_sender;
 2545:     if (ref($settings) eq 'HASH') {
 2546:         $notif_sender = $settings->{'sender_uname'};
 2547:     }
 2548:     my $datatable='<tr class="LC_odd_row">'.
 2549:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 2550:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2551:                   '<input type="radio" name="autoenroll_run"'.
 2552:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2553:                   '<label><input type="radio" name="autoenroll_run"'.
 2554:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 2555:                   '</tr><tr>'.
 2556:                   '<td>'.&mt('Notification messages - sender').
 2557:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 2558:                   &mt('username').':&nbsp;'.
 2559:                   '<input type="text" name="sender_uname" value="'.
 2560:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 2561:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 2562:                   '<tr class="LC_odd_row">'.
 2563:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 2564:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2565:                   '<input type="radio" name="autoassign_coowners"'.
 2566:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2567:                   '<label><input type="radio" name="autoassign_coowners"'.
 2568:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 2569:                   '</tr>';
 2570:     $$rowtotal += 3;
 2571:     return $datatable;
 2572: }
 2573: 
 2574: sub print_autoupdate {
 2575:     my ($position,$dom,$settings,$rowtotal) = @_;
 2576:     my $datatable;
 2577:     if ($position eq 'top') {
 2578:         my $updateon = ' ';
 2579:         my $updateoff = ' checked="checked" ';
 2580:         my $classlistson = ' ';
 2581:         my $classlistsoff = ' checked="checked" ';
 2582:         if (ref($settings) eq 'HASH') {
 2583:             if ($settings->{'run'} eq '1') {
 2584:                 $updateon = $updateoff;
 2585:                 $updateoff = ' ';
 2586:             }
 2587:             if ($settings->{'classlists'} eq '1') {
 2588:                 $classlistson = $classlistsoff;
 2589:                 $classlistsoff = ' ';
 2590:             }
 2591:         }
 2592:         my %title = (
 2593:                    run => 'Auto-update active?',
 2594:                    classlists => 'Update information in classlists?',
 2595:                     );
 2596:         $datatable = '<tr class="LC_odd_row">'. 
 2597:                   '<td>'.&mt($title{'run'}).'</td>'.
 2598:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2599:                   '<input type="radio" name="autoupdate_run"'.
 2600:                   $updateon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2601:                   '<label><input type="radio" name="autoupdate_run"'.
 2602:                   $updateoff.'value="0" />'.&mt('No').'</label></span></td>'.
 2603:                   '</tr><tr>'.
 2604:                   '<td>'.&mt($title{'classlists'}).'</td>'.
 2605:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 2606:                   '<label><input type="radio" name="classlists"'.
 2607:                   $classlistson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2608:                   '<label><input type="radio" name="classlists"'.
 2609:                   $classlistsoff.'value="0" />'.&mt('No').'</label></span></td>'.
 2610:                   '</tr>';
 2611:         $$rowtotal += 2;
 2612:     } elsif ($position eq 'middle') {
 2613:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2614:         my $numinrow = 3;
 2615:         my $locknamesettings;
 2616:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 2617:                                      $dom,$numinrow,$othertitle,
 2618:                                     'lockablenames');
 2619:         $$rowtotal ++;
 2620:     } else {
 2621:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2622:         my @fields = ('lastname','firstname','middlename','generation',
 2623:                       'permanentemail','id');
 2624:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 2625:         my $numrows = 0;
 2626:         if (ref($types) eq 'ARRAY') {
 2627:             if (@{$types} > 0) {
 2628:                 $datatable = 
 2629:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 2630:                                          \@fields,$types,\$numrows);
 2631:                     $$rowtotal += @{$types}; 
 2632:             }
 2633:         }
 2634:         $datatable .= 
 2635:             &usertype_update_row($settings,{'default' => $othertitle},
 2636:                                  \%fieldtitles,\@fields,['default'],
 2637:                                  \$numrows);
 2638:         $$rowtotal ++;     
 2639:     }
 2640:     return $datatable;
 2641: }
 2642: 
 2643: sub print_autocreate {
 2644:     my ($dom,$settings,$rowtotal) = @_;
 2645:     my (%createon,%createoff,%currhash);
 2646:     my @types = ('xml','req');
 2647:     if (ref($settings) eq 'HASH') {
 2648:         foreach my $item (@types) {
 2649:             $createoff{$item} = ' checked="checked" ';
 2650:             $createon{$item} = ' ';
 2651:             if (exists($settings->{$item})) {
 2652:                 if ($settings->{$item}) {
 2653:                     $createon{$item} = ' checked="checked" ';
 2654:                     $createoff{$item} = ' ';
 2655:                 }
 2656:             }
 2657:         }
 2658:         if ($settings->{'xmldc'} ne '') {
 2659:             $currhash{$settings->{'xmldc'}} = 1;
 2660:         }
 2661:     } else {
 2662:         foreach my $item (@types) {
 2663:             $createoff{$item} = ' checked="checked" ';
 2664:             $createon{$item} = ' ';
 2665:         }
 2666:     }
 2667:     $$rowtotal += 2;
 2668:     my $numinrow = 2;
 2669:     my $datatable='<tr class="LC_odd_row">'.
 2670:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 2671:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2672:                   '<input type="radio" name="autocreate_xml"'.
 2673:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2674:                   '<label><input type="radio" name="autocreate_xml"'.
 2675:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 2676:                   '</td></tr><tr>'.
 2677:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 2678:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2679:                   '<input type="radio" name="autocreate_req"'.
 2680:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2681:                   '<label><input type="radio" name="autocreate_req"'.
 2682:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 2683:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 2684:                                                    'autocreate_xmldc',%currhash);
 2685:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 2686:     if ($numdc > 1) {
 2687:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 2688:                       '</td><td class="LC_left_item">';
 2689:     } else {
 2690:         $datatable .= &mt('Course creation processed as:').
 2691:                       '</td><td class="LC_right_item">';
 2692:     }
 2693:     $datatable .= $dctable.'</td></tr>';
 2694:     $$rowtotal += $rows;
 2695:     return $datatable;
 2696: }
 2697: 
 2698: sub print_directorysrch {
 2699:     my ($dom,$settings,$rowtotal) = @_;
 2700:     my $srchon = ' ';
 2701:     my $srchoff = ' checked="checked" ';
 2702:     my ($exacton,$containson,$beginson);
 2703:     my $localon = ' ';
 2704:     my $localoff = ' checked="checked" ';
 2705:     if (ref($settings) eq 'HASH') {
 2706:         if ($settings->{'available'} eq '1') {
 2707:             $srchon = $srchoff;
 2708:             $srchoff = ' ';
 2709:         }
 2710:         if ($settings->{'localonly'} eq '1') {
 2711:             $localon = $localoff;
 2712:             $localoff = ' ';
 2713:         }
 2714:         if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 2715:             foreach my $type (@{$settings->{'searchtypes'}}) {
 2716:                 if ($type eq 'exact') {
 2717:                     $exacton = ' checked="checked" ';
 2718:                 } elsif ($type eq 'contains') {
 2719:                     $containson = ' checked="checked" ';
 2720:                 } elsif ($type eq 'begins') {
 2721:                     $beginson = ' checked="checked" ';
 2722:                 }
 2723:             }
 2724:         } else {
 2725:             if ($settings->{'searchtypes'} eq 'exact') {
 2726:                 $exacton = ' checked="checked" ';
 2727:             } elsif ($settings->{'searchtypes'} eq 'contains') {
 2728:                 $containson = ' checked="checked" ';
 2729:             } elsif ($settings->{'searchtypes'} eq 'specify') {
 2730:                 $exacton = ' checked="checked" ';
 2731:                 $containson = ' checked="checked" ';
 2732:             }
 2733:         }
 2734:     }
 2735:     my ($searchtitles,$titleorder) = &sorted_searchtitles();
 2736:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2737: 
 2738:     my $numinrow = 4;
 2739:     my $cansrchrow = 0;
 2740:     my $datatable='<tr class="LC_odd_row">'.
 2741:                   '<td colspan="2"><span class ="LC_nobreak">'.&mt('Directory search available?').'</span></td>'.
 2742:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2743:                   '<input type="radio" name="dirsrch_available"'.
 2744:                   $srchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2745:                   '<label><input type="radio" name="dirsrch_available"'.
 2746:                   $srchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 2747:                   '</tr><tr>'.
 2748:                   '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search?').'</span></td>'.
 2749:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2750:                   '<input type="radio" name="dirsrch_localonly"'.
 2751:                   $localoff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 2752:                   '<label><input type="radio" name="dirsrch_localonly"'.
 2753:                   $localon.' value="1" />'.&mt('No').'</label></span></td>'.
 2754:                   '</tr>';
 2755:     $$rowtotal += 2;
 2756:     if (ref($usertypes) eq 'HASH') {
 2757:         if (keys(%{$usertypes}) > 0) {
 2758:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 2759:                                          $numinrow,$othertitle,'cansearch');
 2760:             $cansrchrow = 1;
 2761:         }
 2762:     }
 2763:     if ($cansrchrow) {
 2764:         $$rowtotal ++;
 2765:         $datatable .= '<tr>';
 2766:     } else {
 2767:         $datatable .= '<tr class="LC_odd_row">';
 2768:     }
 2769:     $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 2770:                   '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 2771:     foreach my $title (@{$titleorder}) {
 2772:         if (defined($searchtitles->{$title})) {
 2773:             my $check = ' ';
 2774:             if (ref($settings) eq 'HASH') {
 2775:                 if (ref($settings->{'searchby'}) eq 'ARRAY') {
 2776:                     if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 2777:                         $check = ' checked="checked" ';
 2778:                     }
 2779:                 }
 2780:             }
 2781:             $datatable .= '<td class="LC_left_item">'.
 2782:                           '<span class="LC_nobreak"><label>'.
 2783:                           '<input type="checkbox" name="searchby" '.
 2784:                           'value="'.$title.'"'.$check.'/>'.
 2785:                           $searchtitles->{$title}.'</label></span></td>';
 2786:         }
 2787:     }
 2788:     $datatable .= '</tr></table></td></tr>';
 2789:     $$rowtotal ++;
 2790:     if ($cansrchrow) {
 2791:         $datatable .= '<tr class="LC_odd_row">';
 2792:     } else {
 2793:         $datatable .= '<tr>';
 2794:     }
 2795:     $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 2796:                   '<td class="LC_left_item" colspan="2">'.
 2797:                   '<span class="LC_nobreak"><label>'.
 2798:                   '<input type="checkbox" name="searchtypes" '.
 2799:                   $exacton.' value="exact" />'.&mt('Exact match').
 2800:                   '</label>&nbsp;'.
 2801:                   '<label><input type="checkbox" name="searchtypes" '.
 2802:                   $beginson.' value="begins" />'.&mt('Begins with').
 2803:                   '</label>&nbsp;'.
 2804:                   '<label><input type="checkbox" name="searchtypes" '.
 2805:                   $containson.' value="contains" />'.&mt('Contains').
 2806:                   '</label></span></td></tr>';
 2807:     $$rowtotal ++;
 2808:     return $datatable;
 2809: }
 2810: 
 2811: sub print_contacts {
 2812:     my ($dom,$settings,$rowtotal) = @_;
 2813:     my $datatable;
 2814:     my @contacts = ('adminemail','supportemail');
 2815:     my (%checked,%to,%otheremails,%bccemails);
 2816:     my @mailings = ('errormail','packagesmail','lonstatusmail','helpdeskmail',
 2817:                     'requestsmail','updatesmail','idconflictsmail');
 2818:     foreach my $type (@mailings) {
 2819:         $otheremails{$type} = '';
 2820:     }
 2821:     $bccemails{'helpdeskmail'} = '';
 2822:     if (ref($settings) eq 'HASH') {
 2823:         foreach my $item (@contacts) {
 2824:             if (exists($settings->{$item})) {
 2825:                 $to{$item} = $settings->{$item};
 2826:             }
 2827:         }
 2828:         foreach my $type (@mailings) {
 2829:             if (exists($settings->{$type})) {
 2830:                 if (ref($settings->{$type}) eq 'HASH') {
 2831:                     foreach my $item (@contacts) {
 2832:                         if ($settings->{$type}{$item}) {
 2833:                             $checked{$type}{$item} = ' checked="checked" ';
 2834:                         }
 2835:                     }
 2836:                     $otheremails{$type} = $settings->{$type}{'others'};
 2837:                     if ($type eq 'helpdeskmail') {
 2838:                         $bccemails{$type} = $settings->{$type}{'bcc'};
 2839:                     }
 2840:                 }
 2841:             } elsif ($type eq 'lonstatusmail') {
 2842:                 $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 2843:             }
 2844:         }
 2845:     } else {
 2846:         $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 2847:         $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 2848:         $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 2849:         $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 2850:         $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 2851:         $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" '; 
 2852:         $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 2853:         $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 2854:         $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 2855:     }
 2856:     my ($titles,$short_titles) = &contact_titles();
 2857:     my $rownum = 0;
 2858:     my $css_class;
 2859:     foreach my $item (@contacts) {
 2860:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 2861:         $datatable .= '<tr'.$css_class.'>'. 
 2862:                   '<td><span class="LC_nobreak">'.$titles->{$item}.
 2863:                   '</span></td><td class="LC_right_item">'.
 2864:                   '<input type="text" name="'.$item.'" value="'.
 2865:                   $to{$item}.'" /></td></tr>';
 2866:         $rownum ++;
 2867:     }
 2868:     foreach my $type (@mailings) {
 2869:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 2870:         $datatable .= '<tr'.$css_class.'>'.
 2871:                       '<td><span class="LC_nobreak">'.
 2872:                       $titles->{$type}.': </span></td>'.
 2873:                       '<td class="LC_left_item">'.
 2874:                       '<span class="LC_nobreak">';
 2875:         foreach my $item (@contacts) {
 2876:             $datatable .= '<label>'.
 2877:                           '<input type="checkbox" name="'.$type.'"'.
 2878:                           $checked{$type}{$item}.
 2879:                           ' value="'.$item.'" />'.$short_titles->{$item}.
 2880:                           '</label>&nbsp;';
 2881:         }
 2882:         $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 2883:                       '<input type="text" name="'.$type.'_others" '.
 2884:                       'value="'.$otheremails{$type}.'"  />';
 2885:         if ($type eq 'helpdeskmail') {
 2886:             $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 2887:                           '<input type="text" name="'.$type.'_bcc" '.
 2888:                           'value="'.$bccemails{$type}.'"  />';
 2889:         }
 2890:         $datatable .= '</td></tr>'."\n";
 2891:         $rownum ++;
 2892:     }
 2893:     my %choices;
 2894:     $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',
 2895:                                    &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 2896:                                    &mt('LON-CAPA core group - MSU'),600,500));
 2897:     $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 2898:                                     &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 2899:                                     &mt('LON-CAPA core group - MSU'),600,500));
 2900:     my @toggles = ('reporterrors','reportupdates');
 2901:     my %defaultchecked = ('reporterrors'  => 'on',
 2902:                           'reportupdates' => 'on');
 2903:     (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 2904:                                                \%choices,$rownum);
 2905:     $datatable .= $reports;
 2906:     $$rowtotal += $rownum;
 2907:     return $datatable;
 2908: }
 2909: 
 2910: sub print_helpsettings {
 2911:     my ($dom,$confname,$settings,$rowtotal) = @_;
 2912:     my ($datatable,$itemcount);
 2913:     $itemcount = 1;
 2914:     my (%choices,%defaultchecked,@toggles);
 2915:     $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 2916:                                  &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 2917:                                  &mt('LON-CAPA bug tracker'),600,500));
 2918:     %defaultchecked = ('submitbugs' => 'on');
 2919:     @toggles = ('submitbugs',);
 2920: 
 2921:     ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 2922:                                                  \%choices,$itemcount);
 2923:     return $datatable;
 2924: }
 2925: 
 2926: sub radiobutton_prefs {
 2927:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 2928:         $additional,$align) = @_;
 2929:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 2930:                    (ref($choices) eq 'HASH'));
 2931: 
 2932:     my (%checkedon,%checkedoff,$datatable,$css_class);
 2933: 
 2934:     foreach my $item (@{$toggles}) {
 2935:         if ($defaultchecked->{$item} eq 'on') {
 2936:             $checkedon{$item} = ' checked="checked" ';
 2937:             $checkedoff{$item} = ' ';
 2938:         } elsif ($defaultchecked->{$item} eq 'off') {
 2939:             $checkedoff{$item} = ' checked="checked" ';
 2940:             $checkedon{$item} = ' ';
 2941:         }
 2942:     }
 2943:     if (ref($settings) eq 'HASH') {
 2944:         foreach my $item (@{$toggles}) {
 2945:             if ($settings->{$item} eq '1') {
 2946:                 $checkedon{$item} =  ' checked="checked" ';
 2947:                 $checkedoff{$item} = ' ';
 2948:             } elsif ($settings->{$item} eq '0') {
 2949:                 $checkedoff{$item} =  ' checked="checked" ';
 2950:                 $checkedon{$item} = ' ';
 2951:             }
 2952:         }
 2953:     }
 2954:     if ($onclick) {
 2955:         $onclick = ' onclick="'.$onclick.'"';
 2956:     }
 2957:     foreach my $item (@{$toggles}) {
 2958:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2959:         $datatable .=
 2960:             '<tr'.$css_class.'><td valign="top">'.
 2961:             '<span class="LC_nobreak">'.$choices->{$item}.
 2962:             '</span></td>';
 2963:         if ($align eq 'left') {
 2964:             $datatable .= '<td class="LC_left_item">';
 2965:         } else {
 2966:             $datatable .= '<td class="LC_right_item">';
 2967:         }
 2968:         $datatable .= 
 2969:             '<span class="LC_nobreak">'.
 2970:             '<label><input type="radio" name="'.
 2971:             $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 2972:             '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 2973:             $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>'.
 2974:             '</span>'.$additional.
 2975:             '</td>'.
 2976:             '</tr>';
 2977:         $itemcount ++;
 2978:     }
 2979:     return ($datatable,$itemcount);
 2980: }
 2981: 
 2982: sub print_ltitools {
 2983:     my ($dom,$settings,$rowtotal) = @_;
 2984:     my $rownum = 0;
 2985:     my $css_class;
 2986:     my $itemcount = 1;
 2987:     my $maxnum = 0;
 2988:     my %ordered;
 2989:     if (ref($settings) eq 'HASH') {
 2990:         foreach my $item (keys(%{$settings})) {
 2991:             if (ref($settings->{$item}) eq 'HASH') {
 2992:                 my $num = $settings->{$item}{'order'};
 2993:                 $ordered{$num} = $item;
 2994:             }
 2995:         }
 2996:     }
 2997:     my $confname = $dom.'-domainconfig';
 2998:     my $switchserver = &check_switchserver($dom,$confname);
 2999:     my $maxnum = scalar(keys(%ordered));
 3000:     my $datatable = &ltitools_javascript($settings);
 3001:     my %lt = &ltitools_names();
 3002:     my @courseroles = ('cc','in','ta','ep','st');
 3003:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
 3004:     my @fields = ('fullname','firstname','lastname','email','user','roles');
 3005:     if (keys(%ordered)) {
 3006:         my @items = sort { $a <=> $b } keys(%ordered);
 3007:         for (my $i=0; $i<@items; $i++) {
 3008:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3009:             my $item = $ordered{$items[$i]};
 3010:             my ($title,$key,$secret,$url,$imgsrc,$version);
 3011:             if (ref($settings->{$item}) eq 'HASH') {
 3012:                 $title = $settings->{$item}->{'title'};
 3013:                 $url = $settings->{$item}->{'url'};
 3014:                 $key = $settings->{$item}->{'key'};
 3015:                 $secret = $settings->{$item}->{'secret'};
 3016:                 my $image = $settings->{$item}->{'image'};
 3017:                 if ($image ne '') {
 3018:                     $imgsrc = '<img src="'.$image.'" alt="'.&mt('Tool Provider icon').'" />';
 3019:                 }
 3020:             }
 3021:             my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'ltitools_".$item."'".');"';
 3022:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 3023:                          .'<select name="ltitools_'.$item.'"'.$chgstr.'>';
 3024:             for (my $k=0; $k<=$maxnum; $k++) {
 3025:                 my $vpos = $k+1;
 3026:                 my $selstr;
 3027:                 if ($k == $i) {
 3028:                     $selstr = ' selected="selected" ';
 3029:                 }
 3030:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 3031:             }
 3032:             $datatable .= '</select>'.('&nbsp;'x2).
 3033:                 '<label><input type="checkbox" name="ltitools_del" value="'.$item.'" />'.
 3034:                 &mt('Delete?').'</label></span></td>'.
 3035:                 '<td colspan="2">'.
 3036:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 3037:                 '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="30" name="ltitools_title_'.$i.'" value="'.$title.'" /></span> '.
 3038:                 ('&nbsp;'x2).
 3039:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_version_'.$i.'">'.
 3040:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 3041:                 ('&nbsp;'x2).
 3042:                 '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_msgtype_'.$i.'">'.
 3043:                 '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 3044:                 '<br /><br />'.
 3045:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="30" name="ltitools_url_'.$i.'"'.
 3046:                 ' value="'.$url.'" /></span>'.
 3047:                 ('&nbsp;'x2).
 3048:                 '<span class="LC_nobreak">'.$lt{'key'}.
 3049:                 '<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" /></span> '.
 3050:                 ('&nbsp;'x2).
 3051:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 3052:                 '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="'.$secret.'" />'.
 3053:                 '<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>'.
 3054:                 '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span>'.
 3055:                 '</fieldset>'.
 3056:                 '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 3057:                 '<span class="LC_nobreak">'.&mt('Display target:');
 3058:             my %currdisp;
 3059:             if (ref($settings->{$item}->{'display'}) eq 'HASH') {
 3060:                 if ($settings->{$item}->{'display'}->{'target'} eq 'window') {
 3061:                     $currdisp{'window'} = ' checked="checked"';
 3062:                 } else {
 3063:                     $currdisp{'iframe'} = ' checked="checked"';
 3064:                 }
 3065:                 if ($settings->{$item}->{'display'}->{'width'} =~ /^(\d+)$/) {
 3066:                     $currdisp{'width'} = $1;
 3067:                 }
 3068:                 if ($settings->{$item}->{'display'}->{'height'} =~ /^(\d+)$/) {
 3069:                      $currdisp{'height'} = $1;
 3070:                 }
 3071:             } else {
 3072:                 $currdisp{'iframe'} = ' checked="checked"';
 3073:             }
 3074:             foreach my $disp ('iframe','window') {
 3075:                 $datatable .= '<label><input type="radio" name="ltitools_target_'.$i.'" value="'.$disp.'"'.$currdisp{$disp}.' />'.
 3076:                               $lt{$disp}.'</label>'.('&nbsp;'x2);
 3077:             }
 3078:             $datatable .= ('&nbsp;'x4);
 3079:             foreach my $dimen ('width','height') {
 3080:                 $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 3081:                               '<input type="text" name="ltitools_'.$dimen.'_'.$i.'" size="5" value="'.$currdisp{$dimen}.'" /></label>'.
 3082:                               ('&nbsp;'x2);
 3083:             }
 3084:             $datatable .= '<br />';
 3085:             foreach my $extra ('passback','roster') {
 3086:                 my $checkedon = '';
 3087:                 my $checkedoff = ' checked="checked"';
 3088:                 if ($settings->{$item}->{$extra}) {
 3089:                     $checkedon = $checkedoff;
 3090:                     $checkedoff = '';
 3091:                 }
 3092:                 $datatable .= $lt{$extra}.'&nbsp;'.
 3093:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="1"'.$checkedon.' />'.
 3094:                               &mt('Yes').'</label>'.('&nbsp;'x2).
 3095:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="0"'.$checkedoff.' />'.
 3096:                               &mt('No').'</label>'.('&nbsp;'x4);
 3097:             }
 3098:             $datatable .= '<br /><br /><span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 3099:             if ($imgsrc) {
 3100:                 $datatable .= $imgsrc.
 3101:                               '<label><input type="checkbox" name="ltitools_image_del"'.
 3102:                               ' value="'.$item.'" />'.&mt('Delete?').'</label></span> '.
 3103:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 3104:             } else {
 3105:                 $datatable .= '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 3106:             }
 3107:             if ($switchserver) {
 3108:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 3109:             } else {
 3110:                 $datatable .= '<input type="file" name="ltitools_image_'.$i.'" value="" />';
 3111:             }
 3112:             $datatable .= '</span></fieldset>';
 3113:             my (%checkedfields,%rolemaps);
 3114:             if (ref($settings->{$item}) eq 'HASH') {
 3115:                 if (ref($settings->{$item}->{'fields'}) eq 'HASH') {
 3116:                     %checkedfields = %{$settings->{$item}->{'fields'}};
 3117:                 }
 3118:                 if (ref($settings->{$item}->{'roles'}) eq 'HASH') {
 3119:                     %rolemaps = %{$settings->{$item}->{'roles'}};
 3120:                     $checkedfields{'roles'} = 1;
 3121:                 }
 3122:             }
 3123:             $datatable .= '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 3124:                           '<span class="LC_nobreak">';
 3125:             foreach my $field (@fields) {
 3126:                 my $checked;
 3127:                 if ($checkedfields{$field}) {
 3128:                     $checked = ' checked="checked"';
 3129:                 }
 3130:                 $datatable .= '<label>'.
 3131:                               '<input type="checkbox" name="ltitools_fields_'.$i.'" value="'.$field.'"'.$checked.' />'.
 3132:                               $lt{$field}.'</label>'.('&nbsp;' x2);
 3133:             }
 3134:             $datatable .= '</span></fieldset>'.
 3135:                           '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 3136:             foreach my $role (@courseroles) {
 3137:                 my ($selected,$selectnone);
 3138:                 if (!$rolemaps{$role}) {
 3139:                     $selectnone = ' selected="selected"';
 3140:                 }
 3141:                 $datatable .= '<td align="center">'. 
 3142:                               &Apache::lonnet::plaintext($role,'Course').'<br />'.
 3143:                               '<select name="ltitools_roles_'.$role.'_'.$i.'">'.
 3144:                               '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 3145:                 foreach my $ltirole (@ltiroles) {
 3146:                     unless ($selectnone) {
 3147:                         if ($rolemaps{$role} eq $ltirole) {
 3148:                             $selected = ' selected="selected"';
 3149:                         } else {
 3150:                             $selected = '';
 3151:                         }
 3152:                     }
 3153:                     $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 3154:                 }
 3155:                 $datatable .= '</select></td>';
 3156:             }
 3157:             $datatable .= '</tr></table></fieldset>';
 3158:             my %courseconfig;
 3159:             if (ref($settings->{$item}) eq 'HASH') {
 3160:                 if (ref($settings->{$item}->{'crsconf'}) eq 'HASH') {
 3161:                     %courseconfig = %{$settings->{$item}->{'crsconf'}};
 3162:                 }
 3163:             }
 3164:             $datatable .= '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 3165:             foreach my $item ('label','title','target') {
 3166:                 my $checked;
 3167:                 if ($courseconfig{$item}) {
 3168:                     $checked = ' checked="checked"';
 3169:                 }
 3170:                 $datatable .= '<label>'.
 3171:                        '<input type="checkbox" name="ltitools_courseconfig_'.$i.'" value="'.$item.'"'.$checked.' />'.
 3172:                        $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 3173:             }
 3174:             $datatable .= '</span></fieldset>'.
 3175:                           '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 3176:                           '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>';
 3177:             if (ref($settings->{$item}->{'custom'}) eq 'HASH') {
 3178:                 my %custom = %{$settings->{$item}->{'custom'}};
 3179:                 if (keys(%custom) > 0) {
 3180:                     foreach my $key (sort(keys(%custom))) {
 3181:                         $datatable .= '<tr><td><span class="LC_nobreak">'.
 3182:                                       '<label><input type="checkbox" name="ltitools_customdel_'.$i.'" value="'.
 3183:                                       $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 3184:                                       '<td><input type="text" name="ltitools_customval_'.$key.'_'.$i.'"'.
 3185:                                       ' value="'.$custom{$key}.'" /></td></tr>';
 3186:                     }
 3187:                 }
 3188:             }
 3189:             $datatable .= '<tr><td><span class="LC_nobreak">'.
 3190:                           '<label><input type="checkbox" name="ltitools_customadd" value="'.$i.'" />'.
 3191:                           &mt('Add').'</label></span></td><td><input type="text" name="ltitools_custom_name_'.$i.'" />'.
 3192:                           '</td><td><input type="text" name="ltitools_custom_value_'.$i.'" /></td></tr>';
 3193:             $datatable .= '</table></fieldset></td></tr>'."\n";
 3194:             $itemcount ++;
 3195:         }
 3196:     }
 3197:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3198:     my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'ltitools_add_pos'".');"';
 3199:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 3200:                   '<input type="hidden" name="ltitools_maxnum" value="'.$maxnum.'" />'."\n".
 3201:                   '<select name="ltitools_add_pos"'.$chgstr.'>';
 3202:     for (my $k=0; $k<$maxnum+1; $k++) {
 3203:         my $vpos = $k+1;
 3204:         my $selstr;
 3205:         if ($k == $maxnum) {
 3206:             $selstr = ' selected="selected" ';
 3207:         }
 3208:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 3209:     }
 3210:     $datatable .= '</select>&nbsp;'."\n".
 3211:                   '<input type="checkbox" name="ltitools_add" value="1" />'.&mt('Add').'</td>'."\n".
 3212:                   '<td colspan="2">'.
 3213:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 3214:                   '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="30" name="ltitools_add_title" value="" /></span> '."\n".
 3215:                   ('&nbsp;'x2).
 3216:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_add_version">'.
 3217:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 3218:                   ('&nbsp;'x2).
 3219:                   '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_add_msgtype">'.
 3220:                   '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 3221:                   '<br />'.
 3222:                   '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="30" name="ltitools_add_url" value="" /></span> '."\n".
 3223:                   ('&nbsp;'x2).
 3224:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="ltitools_add_key" value="" /></span> '."\n".
 3225:                   ('&nbsp;'x2).
 3226:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="ltitools_add_secret" value="" />'.
 3227:                   '<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".
 3228:                   '</fieldset>'.
 3229:                   '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 3230:                   '<span class="LC_nobreak">'.&mt('Display target:');
 3231:     my %defaultdisp;
 3232:     $defaultdisp{'iframe'} = ' checked="checked"';
 3233:     foreach my $disp ('iframe','window') {
 3234:         $datatable .= '<label><input type="radio" name="ltitools_add_target" value="'.$disp.'"'.$defaultdisp{$disp}.' />'.
 3235:                       $lt{$disp}.'</label>'.('&nbsp;'x2);
 3236:     }
 3237:     $datatable .= ('&nbsp;'x4);
 3238:     foreach my $dimen ('width','height') {
 3239:         $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 3240:                       '<input type="text" name="ltitools_add_'.$dimen.'" size="5" /></label>'.
 3241:                       ('&nbsp;'x2);
 3242:     }
 3243:     $datatable .= '<br />';
 3244:     foreach my $extra ('passback','roster') {
 3245:         $datatable .= $lt{$extra}.'&nbsp;'.
 3246:                       '<label><input type="radio" name="ltitools_add_'.$extra.'" value="1" />'.
 3247:                       &mt('Yes').'</label>'.('&nbsp;'x2).
 3248:                       '<label><input type="radio" name="ltitools_add_'.$extra.'" value="0" checked="checked" />'.
 3249:                       &mt('No').'</label>'.('&nbsp;'x4);
 3250:     }
 3251:     $datatable .= '<br /><br /><span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;'.
 3252:                   '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 3253:     if ($switchserver) {
 3254:         $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 3255:     } else {
 3256:         $datatable .= '<input type="file" name="ltitools_add_image" value="" />';
 3257:     }
 3258:     $datatable .= '</span></fieldset>'.
 3259:                   '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 3260:                   '<span class="LC_nobreak">';
 3261:     foreach my $field (@fields) {
 3262:         $datatable .= '<label>'.
 3263:                       '<input type="checkbox" name="ltitools_add_fields" value="'.$field.'" />'.
 3264:                       $lt{$field}.'</label>'.('&nbsp;' x2);
 3265:     }
 3266:     $datatable .= '</span></fieldset>'.
 3267:                   '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 3268:     foreach my $role (@courseroles) {
 3269:         my ($checked,$checkednone);
 3270:         $datatable .= '<td align="center">'.
 3271:                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 3272:                       '<select name="ltitools_add_roles_'.$role.'">'.
 3273:                       '<option value="" selected="selected">'.&mt('Select').'</option>';
 3274:         foreach my $ltirole (@ltiroles) {
 3275:             $datatable .= '<option value="'.$ltirole.'">'.$ltirole.'</option>';
 3276:         }
 3277:         $datatable .= '</select></td>';
 3278:     }
 3279:     $datatable .= '</tr></table></fieldset>'.
 3280:                   '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 3281:     foreach my $item ('label','title','target') {
 3282:          $datatable .= '<label>'.
 3283:                        '<input type="checkbox" name="ltitools_courseconfig" value="'.$item.'" checked="checked" />'.
 3284:                        $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 3285:     }
 3286:     $datatable .= '</span></fieldset>'.
 3287:                   '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 3288:                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 3289:                   '<tr><td><span class="LC_nobreak">'.
 3290:                   '<label><input type="checkbox" name="ltitools_add_custom" value="1" />'.
 3291:                   &mt('Add').'</label></span></td><td><input type="text" name="ltitools_add_custom_name" />'.
 3292:                   '</td><td><input type="text" name="ltitools_add_custom_value" /></td></tr>'.
 3293:                   '</table></fieldset></td></tr>'."\n".
 3294:                   '</td>'."\n".
 3295:                   '</tr>'."\n";
 3296:     $itemcount ++;
 3297:     return $datatable;
 3298: }
 3299: 
 3300: sub ltitools_names {
 3301:     my %lt = &Apache::lonlocal::texthash(
 3302:                                           'title'     => 'Title',
 3303:                                           'version'   => 'Version',
 3304:                                           'msgtype'   => 'Message Type',
 3305:                                           'url'       => 'URL',
 3306:                                           'key'       => 'Key',
 3307:                                           'secret'    => 'Secret',
 3308:                                           'icon'      => 'Icon',   
 3309:                                           'user'      => 'Username:domain',
 3310:                                           'fullname'  => 'Full Name',
 3311:                                           'firstname' => 'First Name',
 3312:                                           'lastname'  => 'Last Name',
 3313:                                           'email'     => 'E-mail',
 3314:                                           'roles'     => 'Role',
 3315:                                           'window'    => 'Window/Tab',
 3316:                                           'iframe'    => 'iFrame',
 3317:                                           'height'    => 'Height',
 3318:                                           'width'     => 'Width',
 3319:                                           'passback'  => 'Tool can return grades:',
 3320:                                           'roster'    => 'Tool can retrieve roster:',
 3321:                                           'crstarget' => 'Display target',
 3322:                                           'crslabel'  => 'Course label',
 3323:                                           'crstitle'  => 'Course title', 
 3324:                                         );
 3325:     return %lt;
 3326: }
 3327: 
 3328: sub print_coursedefaults {
 3329:     my ($position,$dom,$settings,$rowtotal) = @_;
 3330:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 3331:     my $itemcount = 1;
 3332:     my %choices =  &Apache::lonlocal::texthash (
 3333:         canuse_pdfforms      => 'Course/Community users can create/upload PDF forms',
 3334:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 3335:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 3336:         coursecredits        => 'Credits can be specified for courses',
 3337:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 3338:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 3339:         postsubmit           => 'Disable submit button/keypress following student submission',
 3340:         canclone             => "People who may clone a course (besides course's owner and coordinators)",     
 3341:     );
 3342:     my %staticdefaults = (
 3343:                            anonsurvey_threshold => 10,
 3344:                            uploadquota          => 500,
 3345:                            postsubmit           => 60,
 3346:                          );
 3347:     if ($position eq 'top') {
 3348:         %defaultchecked = (
 3349:                             'canuse_pdfforms' => 'off',
 3350:                             'uselcmath'       => 'on',
 3351:                             'usejsme'         => 'on',
 3352:                             'canclone'        => 'none', 
 3353:                           );
 3354:         @toggles = ('canuse_pdfforms','uselcmath','usejsme');
 3355:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3356:                                                      \%choices,$itemcount);
 3357:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3358:         $datatable .=
 3359:             '<tr'.$css_class.'><td valign="top">'.
 3360:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 3361:             '</span></td><td class="LC_left_item">';
 3362:         my $currcanclone = 'none';
 3363:         my $onclick;
 3364:         my @cloneoptions = ('none','domain');
 3365:         my %clonetitles = (
 3366:                              none     => 'No additional course requesters',
 3367:                              domain   => "Any course requester in course's domain",
 3368:                              instcode => 'Course requests for official courses ...',
 3369:                           );
 3370:         my (%codedefaults,@code_order,@posscodes);
 3371:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 3372:                                                     \@code_order) eq 'ok') {
 3373:             if (@code_order > 0) {
 3374:                 push(@cloneoptions,'instcode');
 3375:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 3376:             }
 3377:         }
 3378:         if (ref($settings) eq 'HASH') {
 3379:             if ($settings->{'canclone'}) {
 3380:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 3381:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 3382:                         if (@code_order > 0) {
 3383:                             $currcanclone = 'instcode';
 3384:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 3385:                         }
 3386:                     }
 3387:                 } elsif ($settings->{'canclone'} eq 'domain') {
 3388:                     $currcanclone = $settings->{'canclone'};
 3389:                 }
 3390:             }
 3391:         } 
 3392:         foreach my $option (@cloneoptions) {
 3393:             my ($checked,$additional);
 3394:             if ($currcanclone eq $option) {
 3395:                 $checked = ' checked="checked"';
 3396:             }
 3397:             if ($option eq 'instcode') {
 3398:                 if (@code_order) {
 3399:                     my $show = 'none';
 3400:                     if ($checked) {
 3401:                         $show = 'block';
 3402:                     }
 3403:                     $additional = '<div id="cloneinstcode" style="display:'.$show.'" />'.
 3404:                                   &mt('Institutional codes for new and cloned course have identical:').
 3405:                                   '<br />';
 3406:                     foreach my $item (@code_order) {
 3407:                         my $codechk;
 3408:                         if ($checked) {
 3409:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 3410:                                 $codechk = ' checked="checked"';
 3411:                             }
 3412:                         }
 3413:                         $additional .= '<label>'.
 3414:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 3415:                                        $item.'</label>';
 3416:                     }
 3417:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 3418:                 }
 3419:             }
 3420:             $datatable .=
 3421:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 3422:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 3423:                 '</label>&nbsp;'.$additional.'</span><br />';
 3424:         }
 3425:         $datatable .= '</td>'.
 3426:                       '</tr>';
 3427:         $itemcount ++;
 3428:     } else {
 3429:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3430:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout);
 3431:         my $currusecredits = 0;
 3432:         my $postsubmitclient = 1;
 3433:         my @types = ('official','unofficial','community','textbook','placement');
 3434:         if (ref($settings) eq 'HASH') {
 3435:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 3436:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 3437:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 3438:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 3439:                 }
 3440:             }
 3441:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 3442:                 foreach my $type (@types) {
 3443:                     next if ($type eq 'community');
 3444:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 3445:                     if ($defcredits{$type} ne '') {
 3446:                         $currusecredits = 1;
 3447:                     }
 3448:                 }
 3449:             }
 3450:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 3451:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 3452:                     $postsubmitclient = 0;
 3453:                     foreach my $type (@types) {
 3454:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3455:                     }
 3456:                 } else {
 3457:                     foreach my $type (@types) {
 3458:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 3459:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 3460:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type}; 
 3461:                             } else {
 3462:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3463:                             }
 3464:                         } else {
 3465:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3466:                         }
 3467:                     }
 3468:                 }
 3469:             } else {
 3470:                 foreach my $type (@types) {
 3471:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3472:                 }
 3473:             }
 3474:         } else {
 3475:             foreach my $type (@types) {
 3476:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3477:             }
 3478:         }
 3479:         if (!$currdefresponder) {
 3480:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 3481:         } elsif ($currdefresponder < 1) {
 3482:             $currdefresponder = 1;
 3483:         }
 3484:         foreach my $type (@types) {
 3485:             if ($curruploadquota{$type} eq '') {
 3486:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 3487:             }
 3488:         }
 3489:         $datatable .=
 3490:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 3491:                 $choices{'anonsurvey_threshold'}.
 3492:                 '</span></td>'.
 3493:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 3494:                 '<input type="text" name="anonsurvey_threshold"'.
 3495:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 3496:                 '</td></tr>'."\n";
 3497:         $itemcount ++;
 3498:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3499:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 3500:                       $choices{'uploadquota'}.
 3501:                       '</span></td>'.
 3502:                       '<td align="right" class="LC_right_item">'.
 3503:                       '<table><tr>';
 3504:         foreach my $type (@types) {
 3505:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 3506:                            '<input type="text" name="uploadquota_'.$type.'"'.
 3507:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 3508:         }
 3509:         $datatable .= '</tr></table></td></tr>'."\n";
 3510:         $itemcount ++;
 3511:         my $onclick = "toggleDisplay(this.form,'credits');";
 3512:         my $display = 'none';
 3513:         if ($currusecredits) {
 3514:             $display = 'block';
 3515:         }
 3516:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 3517:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 3518:         foreach my $type (@types) {
 3519:             next if ($type eq 'community');
 3520:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 3521:                            '<input type="text" name="'.$type.'_credits"'.
 3522:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 3523:         }
 3524:         $additional .= '</tr></table></div>'."\n";
 3525:         %defaultchecked = ('coursecredits' => 'off');
 3526:         @toggles = ('coursecredits');
 3527:         my $current = {
 3528:                         'coursecredits' => $currusecredits,
 3529:                       };
 3530:         (my $table,$itemcount) =
 3531:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 3532:                                \%choices,$itemcount,$onclick,$additional,'left');
 3533:         $datatable .= $table;
 3534:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 3535:         my $display = 'none';
 3536:         if ($postsubmitclient) {
 3537:             $display = 'block';
 3538:         }
 3539:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 3540:                       &mt('Number of seconds submit is disabled').'<br />'.
 3541:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 3542:                       '<table><tr>';
 3543:         foreach my $type (@types) {
 3544:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 3545:                            '<input type="text" name="'.$type.'_timeout" value="'.
 3546:                            $deftimeout{$type}.'" size="5" /></td>';
 3547:         }
 3548:         $additional .= '</tr></table></div>'."\n";
 3549:         %defaultchecked = ('postsubmit' => 'on');
 3550:         @toggles = ('postsubmit');
 3551:         my $current = {
 3552:                         'postsubmit' => $postsubmitclient,
 3553:                       };
 3554:         ($table,$itemcount) =
 3555:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 3556:                                \%choices,$itemcount,$onclick,$additional,'left');
 3557:         $datatable .= $table;
 3558:     }
 3559:     $$rowtotal += $itemcount;
 3560:     return $datatable;
 3561: }
 3562: 
 3563: sub print_selfenrollment {
 3564:     my ($position,$dom,$settings,$rowtotal) = @_;
 3565:     my ($css_class,$datatable);
 3566:     my $itemcount = 1;
 3567:     my @types = ('official','unofficial','community','textbook','placement');
 3568:     if (($position eq 'top') || ($position eq 'middle')) {
 3569:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 3570:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 3571:         my @rows;
 3572:         my $key;
 3573:         if ($position eq 'top') {
 3574:             $key = 'admin'; 
 3575:             if (ref($rowsref) eq 'ARRAY') {
 3576:                 @rows = @{$rowsref};
 3577:             }
 3578:         } elsif ($position eq 'middle') {
 3579:             $key = 'default';
 3580:             @rows = ('types','registered','approval','limit');
 3581:         }
 3582:         foreach my $row (@rows) {
 3583:             if (defined($titlesref->{$row})) {
 3584:                 $itemcount ++;
 3585:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3586:                 $datatable .= '<tr'.$css_class.'>'.
 3587:                               '<td>'.$titlesref->{$row}.'</td>'.
 3588:                               '<td class="LC_left_item">'.
 3589:                               '<table><tr>';
 3590:                 my (%current,%currentcap);
 3591:                 if (ref($settings) eq 'HASH') {
 3592:                     if (ref($settings->{$key}) eq 'HASH') {
 3593:                         foreach my $type (@types) {
 3594:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 3595:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 3596:                             }
 3597:                             if (($row eq 'limit') && ($key eq 'default')) {
 3598:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 3599:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 3600:                                 }
 3601:                             }
 3602:                         }
 3603:                     }
 3604:                 }
 3605:                 my %roles = (
 3606:                              '0' => &Apache::lonnet::plaintext('dc'),
 3607:                             ); 
 3608:             
 3609:                 foreach my $type (@types) {
 3610:                     unless (($row eq 'registered') && ($key eq 'default')) {
 3611:                         $datatable .= '<th>'.&mt($type).'</th>';
 3612:                     }
 3613:                 }
 3614:                 unless (($row eq 'registered') && ($key eq 'default')) {
 3615:                     $datatable .= '</tr><tr>';
 3616:                 }
 3617:                 foreach my $type (@types) {
 3618:                     if ($type eq 'community') {
 3619:                         $roles{'1'} = &mt('Community personnel');
 3620:                     } else {
 3621:                         $roles{'1'} = &mt('Course personnel');
 3622:                     }
 3623:                     $datatable .= '<td style="vertical-align: top">';
 3624:                     if ($position eq 'top') {
 3625:                         my %checked;
 3626:                         if ($current{$type} eq '0') {
 3627:                             $checked{'0'} = ' checked="checked"';
 3628:                         } else {
 3629:                             $checked{'1'} = ' checked="checked"';
 3630:                         }
 3631:                         foreach my $role ('1','0') {
 3632:                             $datatable .= '<span class="LC_nobreak"><label>'.
 3633:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 3634:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 3635:                                           $roles{$role}.'</label></span> ';
 3636:                         }
 3637:                     } else {
 3638:                         if ($row eq 'types') {
 3639:                             my %checked;
 3640:                             if ($current{$type} =~ /^(all|dom)$/) {
 3641:                                 $checked{$1} = ' checked="checked"';
 3642:                             } else {
 3643:                                 $checked{''} = ' checked="checked"';
 3644:                             }
 3645:                             foreach my $val ('','dom','all') {
 3646:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 3647:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 3648:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 3649:                             }
 3650:                         } elsif ($row eq 'registered') {
 3651:                             my %checked;
 3652:                             if ($current{$type} eq '1') {
 3653:                                 $checked{'1'} = ' checked="checked"';
 3654:                             } else {
 3655:                                 $checked{'0'} = ' checked="checked"';
 3656:                             }
 3657:                             foreach my $val ('0','1') {
 3658:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 3659:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 3660:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 3661:                             }
 3662:                         } elsif ($row eq 'approval') {
 3663:                             my %checked;
 3664:                             if ($current{$type} =~ /^([12])$/) {
 3665:                                 $checked{$1} = ' checked="checked"';
 3666:                             } else {
 3667:                                 $checked{'0'} = ' checked="checked"';
 3668:                             }
 3669:                             for my $val (0..2) {
 3670:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 3671:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 3672:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 3673:                             }
 3674:                         } elsif ($row eq 'limit') {
 3675:                             my %checked;
 3676:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 3677:                                 $checked{$1} = ' checked="checked"';
 3678:                             } else {
 3679:                                 $checked{'none'} = ' checked="checked"';
 3680:                             }
 3681:                             my $cap;
 3682:                             if ($currentcap{$type} =~ /^\d+$/) {
 3683:                                 $cap = $currentcap{$type};
 3684:                             }
 3685:                             foreach my $val ('none','allstudents','selfenrolled') {
 3686:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 3687:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 3688:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 3689:                             }
 3690:                             $datatable .= '<br />'.
 3691:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 3692:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 3693:                                           '</span>'; 
 3694:                         }
 3695:                     }
 3696:                     $datatable .= '</td>';
 3697:                 }
 3698:                 $datatable .= '</tr>';
 3699:             }
 3700:             $datatable .= '</table></td></tr>';
 3701:         }
 3702:     } elsif ($position eq 'bottom') {
 3703:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 3704:     }
 3705:     $$rowtotal += $itemcount;
 3706:     return $datatable;
 3707: }
 3708: 
 3709: sub print_validation_rows {
 3710:     my ($caller,$dom,$settings,$rowtotal) = @_;
 3711:     my ($itemsref,$namesref,$fieldsref);
 3712:     if ($caller eq 'selfenroll') { 
 3713:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 3714:     } elsif ($caller eq 'requestcourses') {
 3715:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 3716:     }
 3717:     my %currvalidation;
 3718:     if (ref($settings) eq 'HASH') {
 3719:         if (ref($settings->{'validation'}) eq 'HASH') {
 3720:             %currvalidation = %{$settings->{'validation'}};
 3721:         }
 3722:     }
 3723:     my $datatable;
 3724:     my $itemcount = 0;
 3725:     foreach my $item (@{$itemsref}) {
 3726:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3727:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 3728:                       $namesref->{$item}.
 3729:                       '</span></td>'.
 3730:                       '<td class="LC_left_item">';
 3731:         if (($item eq 'url') || ($item eq 'button')) {
 3732:             $datatable .= '<span class="LC_nobreak">'.
 3733:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 3734:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 3735:         } elsif ($item eq 'fields') {
 3736:             my @currfields;
 3737:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 3738:                 @currfields = @{$currvalidation{$item}};
 3739:             }
 3740:             foreach my $field (@{$fieldsref}) {
 3741:                 my $check = '';
 3742:                 if (grep(/^\Q$field\E$/,@currfields)) {
 3743:                     $check = ' checked="checked"';
 3744:                 }
 3745:                 $datatable .= '<span class="LC_nobreak"><label>'.
 3746:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 3747:                               ' value="'.$field.'"'.$check.' />'.$field.
 3748:                               '</label></span> ';
 3749:             }
 3750:         } elsif ($item eq 'markup') {
 3751:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5" wrap="soft">'.
 3752:                            $currvalidation{$item}.
 3753:                               '</textarea>';
 3754:         }
 3755:         $datatable .= '</td></tr>'."\n";
 3756:         if (ref($rowtotal)) {
 3757:             $itemcount ++;
 3758:         }
 3759:     }
 3760:     if ($caller eq 'requestcourses') {
 3761:         my %currhash;
 3762:         if (ref($settings) eq 'HASH') {
 3763:             if (ref($settings->{'validation'}) eq 'HASH') {
 3764:                 if ($settings->{'validation'}{'dc'} ne '') {
 3765:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 3766:                 }
 3767:             }
 3768:         }
 3769:         my $numinrow = 2;
 3770:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 3771:                                                        'validationdc',%currhash);
 3772:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3773:         $datatable .= '</td></tr><tr'.$css_class.'><td>';
 3774:         if ($numdc > 1) {
 3775:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 3776:         } else {
 3777:             $datatable .=  &mt('Course creation processed as: ');
 3778:         }
 3779:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 3780:         $itemcount ++;
 3781:     }
 3782:     if (ref($rowtotal)) {
 3783:         $$rowtotal += $itemcount;
 3784:     }
 3785:     return $datatable;
 3786: }
 3787: 
 3788: sub print_usersessions {
 3789:     my ($position,$dom,$settings,$rowtotal) = @_;
 3790:     my ($css_class,$datatable,%checked,%choices);
 3791:     my (%by_ip,%by_location,@intdoms);
 3792:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
 3793: 
 3794:     my @alldoms = &Apache::lonnet::all_domains();
 3795:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 3796:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 3797:     my %altids = &id_for_thisdom(%servers);
 3798:     my $itemcount = 1;
 3799:     if ($position eq 'top') {
 3800:         if (keys(%serverhomes) > 1) {
 3801:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 3802:             my $curroffloadnow;
 3803:             if (ref($settings) eq 'HASH') {
 3804:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 3805:                     $curroffloadnow = $settings->{'offloadnow'};
 3806:                 }
 3807:             }
 3808:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,$curroffloadnow,$rowtotal);
 3809:         } else {
 3810:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 3811:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.');
 3812:         }
 3813:     } else {
 3814:         if (keys(%by_location) == 0) {
 3815:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 3816:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.');
 3817:         } else {
 3818:             my %lt = &usersession_titles();
 3819:             my $numinrow = 5;
 3820:             my $prefix;
 3821:             my @types;
 3822:             if ($position eq 'bottom') {
 3823:                 $prefix = 'remote';
 3824:                 @types = ('version','excludedomain','includedomain');
 3825:             } else {
 3826:                 $prefix = 'hosted';
 3827:                 @types = ('excludedomain','includedomain');
 3828:             }
 3829:             my (%current,%checkedon,%checkedoff);
 3830:             my @lcversions = &Apache::lonnet::all_loncaparevs();
 3831:             my @locations = sort(keys(%by_location));
 3832:             foreach my $type (@types) {
 3833:                 $checkedon{$type} = '';
 3834:                 $checkedoff{$type} = ' checked="checked"';
 3835:             }
 3836:             if (ref($settings) eq 'HASH') {
 3837:                 if (ref($settings->{$prefix}) eq 'HASH') {
 3838:                     foreach my $key (keys(%{$settings->{$prefix}})) {
 3839:                         $current{$key} = $settings->{$prefix}{$key};
 3840:                         if ($key eq 'version') {
 3841:                             if ($current{$key} ne '') {
 3842:                                 $checkedon{$key} = ' checked="checked"';
 3843:                                 $checkedoff{$key} = '';
 3844:                             }
 3845:                         } elsif (ref($current{$key}) eq 'ARRAY') {
 3846:                             $checkedon{$key} = ' checked="checked"';
 3847:                             $checkedoff{$key} = '';
 3848:                         }
 3849:                     }
 3850:                 }
 3851:             }
 3852:             foreach my $type (@types) {
 3853:                 next if ($type ne 'version' && !@locations);
 3854:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3855:                 $datatable .= '<tr'.$css_class.'>
 3856:                                <td><span class="LC_nobreak">'.$lt{$type}.'</span><br />
 3857:                                <span class="LC_nobreak">&nbsp;
 3858:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 3859:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 3860:                 if ($type eq 'version') {
 3861:                     my $selector = '<select name="'.$prefix.'_version">';
 3862:                     foreach my $version (@lcversions) {
 3863:                         my $selected = '';
 3864:                         if ($current{'version'} eq $version) {
 3865:                             $selected = ' selected="selected"';
 3866:                         }
 3867:                         $selector .= ' <option value="'.$version.'"'.
 3868:                                      $selected.'>'.$version.'</option>';
 3869:                     }
 3870:                     $selector .= '</select> ';
 3871:                     $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 3872:                 } else {
 3873:                     $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 3874:                                  'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 3875:                                  ' />'.('&nbsp;'x2).
 3876:                                  '<input type="button" value="'.&mt('uncheck all').'" '.
 3877:                                  'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 3878:                                  "\n".
 3879:                                  '</div><div><table>';
 3880:                     my $rem;
 3881:                     for (my $i=0; $i<@locations; $i++) {
 3882:                         my ($showloc,$value,$checkedtype);
 3883:                         if (ref($by_location{$locations[$i]}) eq 'ARRAY') {
 3884:                             my $ip = $by_location{$locations[$i]}->[0];
 3885:                             if (ref($by_ip{$ip}) eq 'ARRAY') {
 3886:                                  $value = join(':',@{$by_ip{$ip}});
 3887:                                 $showloc = join(', ',@{$by_ip{$ip}});
 3888:                                 if (ref($current{$type}) eq 'ARRAY') {
 3889:                                     foreach my $loc (@{$by_ip{$ip}}) {  
 3890:                                         if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 3891:                                             $checkedtype = ' checked="checked"';
 3892:                                             last;
 3893:                                         }
 3894:                                     }
 3895:                                 }
 3896:                             }
 3897:                         }
 3898:                         $rem = $i%($numinrow);
 3899:                         if ($rem == 0) {
 3900:                             if ($i > 0) {
 3901:                                 $datatable .= '</tr>';
 3902:                             }
 3903:                             $datatable .= '<tr>';
 3904:                         }
 3905:                         $datatable .= '<td class="LC_left_item">'.
 3906:                                       '<span class="LC_nobreak"><label>'.
 3907:                                       '<input type="checkbox" name="'.$prefix.'_'.$type.
 3908:                                       '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 3909:                                       '</label></span></td>';
 3910:                     }
 3911:                     $rem = @locations%($numinrow);
 3912:                     my $colsleft = $numinrow - $rem;
 3913:                     if ($colsleft > 1 ) {
 3914:                         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 3915:                                       '&nbsp;</td>';
 3916:                     } elsif ($colsleft == 1) {
 3917:                         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 3918:                     }
 3919:                     $datatable .= '</tr></table>';
 3920:                 }
 3921:                 $datatable .= '</td></tr>';
 3922:                 $itemcount ++;
 3923:             }
 3924:         }
 3925:     }
 3926:     $$rowtotal += $itemcount;
 3927:     return $datatable;
 3928: }
 3929: 
 3930: sub build_location_hashes {
 3931:     my ($intdoms,$by_ip,$by_location) = @_;
 3932:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 3933:                   (ref($by_location) eq 'HASH')); 
 3934:     my %iphost = &Apache::lonnet::get_iphost();
 3935:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 3936:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 3937:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 3938:         foreach my $id (@{$iphost{$primary_ip}}) {
 3939:             my $intdom = &Apache::lonnet::internet_dom($id);
 3940:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 3941:                 push(@{$intdoms},$intdom);
 3942:             }
 3943:         }
 3944:     }
 3945:     foreach my $ip (keys(%iphost)) {
 3946:         if (ref($iphost{$ip}) eq 'ARRAY') {
 3947:             foreach my $id (@{$iphost{$ip}}) {
 3948:                 my $location = &Apache::lonnet::internet_dom($id);
 3949:                 if ($location) {
 3950:                     next if (grep(/^\Q$location\E$/,@{$intdoms}));
 3951:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 3952:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 3953:                             push(@{$by_ip->{$ip}},$location);
 3954:                         }
 3955:                     } else {
 3956:                         $by_ip->{$ip} = [$location];
 3957:                     }
 3958:                 }
 3959:             }
 3960:         }
 3961:     }
 3962:     foreach my $ip (sort(keys(%{$by_ip}))) {
 3963:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 3964:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 3965:             my $first = $by_ip->{$ip}->[0];
 3966:             if (ref($by_location->{$first}) eq 'ARRAY') {
 3967:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 3968:                     push(@{$by_location->{$first}},$ip);
 3969:                 }
 3970:             } else {
 3971:                 $by_location->{$first} = [$ip];
 3972:             }
 3973:         }
 3974:     }
 3975:     return;
 3976: }
 3977: 
 3978: sub current_offloads_to {
 3979:     my ($dom,$settings,$servers) = @_;
 3980:     my (%spareid,%otherdomconfigs);
 3981:     if (ref($servers) eq 'HASH') {
 3982:         foreach my $lonhost (sort(keys(%{$servers}))) {
 3983:             my $gotspares;
 3984:             if (ref($settings) eq 'HASH') {
 3985:                 if (ref($settings->{'spares'}) eq 'HASH') {
 3986:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 3987:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 3988:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 3989:                         $gotspares = 1;
 3990:                     }
 3991:                 }
 3992:             }
 3993:             unless ($gotspares) {
 3994:                 my $gotspares;
 3995:                 my $serverhomeID =
 3996:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 3997:                 my $serverhomedom =
 3998:                     &Apache::lonnet::host_domain($serverhomeID);
 3999:                 if ($serverhomedom ne $dom) {
 4000:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 4001:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 4002:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 4003:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 4004:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 4005:                                 $gotspares = 1;
 4006:                             }
 4007:                         }
 4008:                     } else {
 4009:                         $otherdomconfigs{$serverhomedom} =
 4010:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 4011:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 4012:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 4013:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 4014:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 4015:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 4016:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 4017:                                         $gotspares = 1;
 4018:                                     }
 4019:                                 }
 4020:                             }
 4021:                         }
 4022:                     }
 4023:                 }
 4024:             }
 4025:             unless ($gotspares) {
 4026:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 4027:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 4028:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 4029:                } else {
 4030:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 4031:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 4032:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 4033:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 4034:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 4035:                     } else {
 4036:                         my %what = (
 4037:                              spareid => 1,
 4038:                         );
 4039:                         my ($result,$returnhash) = 
 4040:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 4041:                         if ($result eq 'ok') { 
 4042:                             if (ref($returnhash) eq 'HASH') {
 4043:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 4044:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 4045:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 4046:                                 }
 4047:                             }
 4048:                         }
 4049:                     }
 4050:                 }
 4051:             }
 4052:         }
 4053:     }
 4054:     return %spareid;
 4055: }
 4056: 
 4057: sub spares_row {
 4058:     my ($dom,$servers,$spareid,$serverhomes,$altids,$curroffloadnow,$rowtotal) = @_;
 4059:     my $css_class;
 4060:     my $numinrow = 4;
 4061:     my $itemcount = 1;
 4062:     my $datatable;
 4063:     my %typetitles = &sparestype_titles();
 4064:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 4065:         foreach my $server (sort(keys(%{$servers}))) {
 4066:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 4067:             my ($othercontrol,$serverdom);
 4068:             if ($serverhome ne $server) {
 4069:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 4070:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 4071:             } else {
 4072:                 $serverdom = &Apache::lonnet::host_domain($server);
 4073:                 if ($serverdom ne $dom) {
 4074:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 4075:                 }
 4076:             }
 4077:             next unless (ref($spareid->{$server}) eq 'HASH');
 4078:             my $checkednow;
 4079:             if (ref($curroffloadnow) eq 'HASH') {
 4080:                 if ($curroffloadnow->{$server}) {
 4081:                     $checkednow = ' checked="checked"';
 4082:                 }
 4083:             }
 4084:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4085:             $datatable .= '<tr'.$css_class.'>
 4086:                            <td rowspan="2">
 4087:                             <span class="LC_nobreak">'.
 4088:                           &mt('[_1] when busy, offloads to:'
 4089:                               ,'<b>'.$server.'</b>').'</span><br />'.
 4090:                           '<span class="LC_nobreak">'."\n". 
 4091:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 4092:                           '&nbsp;'.&mt('Switch active users on next access').'</label></span>'.
 4093:                           "\n";
 4094:             my (%current,%canselect);
 4095:             my @choices = 
 4096:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 4097:             foreach my $type ('primary','default') {
 4098:                 if (ref($spareid->{$server}) eq 'HASH') {
 4099:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 4100:                         my @spares = @{$spareid->{$server}{$type}};
 4101:                         if (@spares > 0) {
 4102:                             if ($othercontrol) {
 4103:                                 $current{$type} = join(', ',@spares);
 4104:                             } else {
 4105:                                 $current{$type} .= '<table>';
 4106:                                 my $numspares = scalar(@spares);
 4107:                                 for (my $i=0;  $i<@spares; $i++) {
 4108:                                     my $rem = $i%($numinrow);
 4109:                                     if ($rem == 0) {
 4110:                                         if ($i > 0) {
 4111:                                             $current{$type} .= '</tr>';
 4112:                                         }
 4113:                                         $current{$type} .= '<tr>';
 4114:                                     }
 4115:                                     $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;'.
 4116:                                                        $spareid->{$server}{$type}[$i].
 4117:                                                        '</label></td>'."\n";
 4118:                                 }
 4119:                                 my $rem = @spares%($numinrow);
 4120:                                 my $colsleft = $numinrow - $rem;
 4121:                                 if ($colsleft > 1 ) {
 4122:                                     $current{$type} .= '<td colspan="'.$colsleft.
 4123:                                                        '" class="LC_left_item">'.
 4124:                                                        '&nbsp;</td>';
 4125:                                 } elsif ($colsleft == 1) {
 4126:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 4127:                                 }
 4128:                                 $current{$type} .= '</tr></table>';
 4129:                             }
 4130:                         }
 4131:                     }
 4132:                     if ($current{$type} eq '') {
 4133:                         $current{$type} = &mt('None specified');
 4134:                     }
 4135:                     if ($othercontrol) {
 4136:                         if ($type eq 'primary') {
 4137:                             $canselect{$type} = $othercontrol;
 4138:                         }
 4139:                     } else {
 4140:                         $canselect{$type} = 
 4141:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 4142:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 4143:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 4144:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 4145:                         if (@choices > 0) {
 4146:                             foreach my $lonhost (@choices) {
 4147:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 4148:                             }
 4149:                         }
 4150:                         $canselect{$type} .= '</select>'."\n";
 4151:                     }
 4152:                 } else {
 4153:                     $current{$type} = &mt('Could not be determined');
 4154:                     if ($type eq 'primary') {
 4155:                         $canselect{$type} =  $othercontrol;
 4156:                     }
 4157:                 }
 4158:                 if ($type eq 'default') {
 4159:                     $datatable .= '<tr'.$css_class.'>';
 4160:                 }
 4161:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 4162:                               '<td>'.$current{$type}.'</td>'."\n".
 4163:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 4164:             }
 4165:             $itemcount ++;
 4166:         }
 4167:     }
 4168:     $$rowtotal += $itemcount;
 4169:     return $datatable;
 4170: }
 4171: 
 4172: sub possible_newspares {
 4173:     my ($server,$currspares,$serverhomes,$altids) = @_;
 4174:     my $serverhostname = &Apache::lonnet::hostname($server);
 4175:     my %excluded;
 4176:     if ($serverhostname ne '') {
 4177:         %excluded = (
 4178:                        $serverhostname => 1,
 4179:                     );
 4180:     }
 4181:     if (ref($currspares) eq 'HASH') {
 4182:         foreach my $type (keys(%{$currspares})) {
 4183:             if (ref($currspares->{$type}) eq 'ARRAY') {
 4184:                 if (@{$currspares->{$type}} > 0) {
 4185:                     foreach my $curr (@{$currspares->{$type}}) {
 4186:                         my $hostname = &Apache::lonnet::hostname($curr);
 4187:                         $excluded{$hostname} = 1;
 4188:                     }
 4189:                 }
 4190:             }
 4191:         }
 4192:     }
 4193:     my @choices;
 4194:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 4195:         if (keys(%{$serverhomes}) > 1) {
 4196:             foreach my $name (sort(keys(%{$serverhomes}))) {
 4197:                 unless ($excluded{$name}) {
 4198:                     if (exists($altids->{$serverhomes->{$name}})) {
 4199:                         push(@choices,$altids->{$serverhomes->{$name}});
 4200:                     } else {
 4201:                         push(@choices,$serverhomes->{$name});
 4202:                     }
 4203:                 }
 4204:             }
 4205:         }
 4206:     }
 4207:     return sort(@choices);
 4208: }
 4209: 
 4210: sub print_loadbalancing {
 4211:     my ($dom,$settings,$rowtotal) = @_;
 4212:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 4213:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 4214:     my $numinrow = 1;
 4215:     my $datatable;
 4216:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 4217:     my (%currbalancer,%currtargets,%currrules,%existing);
 4218:     if (ref($settings) eq 'HASH') {
 4219:         %existing = %{$settings};
 4220:     }
 4221:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 4222:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 4223:                                   \%currtargets,\%currrules);
 4224:     } else {
 4225:         return;
 4226:     }
 4227:     my ($othertitle,$usertypes,$types) =
 4228:         &Apache::loncommon::sorted_inst_types($dom);
 4229:     my $rownum = 8;
 4230:     if (ref($types) eq 'ARRAY') {
 4231:         $rownum += scalar(@{$types});
 4232:     }
 4233:     my @css_class = ('LC_odd_row','LC_even_row');
 4234:     my $balnum = 0;
 4235:     my $islast;
 4236:     my (@toshow,$disabledtext);
 4237:     if (keys(%currbalancer) > 0) {
 4238:         @toshow = sort(keys(%currbalancer));
 4239:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 4240:             push(@toshow,'');
 4241:         }
 4242:     } else {
 4243:         @toshow = ('');
 4244:         $disabledtext = &mt('No existing load balancer');
 4245:     }
 4246:     foreach my $lonhost (@toshow) {
 4247:         if ($balnum == scalar(@toshow)-1) {
 4248:             $islast = 1;
 4249:         } else {
 4250:             $islast = 0;
 4251:         }
 4252:         my $cssidx = $balnum%2;
 4253:         my $targets_div_style = 'display: none';
 4254:         my $disabled_div_style = 'display: block';
 4255:         my $homedom_div_style = 'display: none';
 4256:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 4257:                       '<td rowspan="'.$rownum.'" valign="top">'.
 4258:                       '<p>';
 4259:         if ($lonhost eq '') {
 4260:             $datatable .= '<span class="LC_nobreak">';
 4261:             if (keys(%currbalancer) > 0) {
 4262:                 $datatable .= &mt('Add balancer:');
 4263:             } else {
 4264:                 $datatable .= &mt('Enable balancer:');
 4265:             }
 4266:             $datatable .= '&nbsp;'.
 4267:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 4268:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 4269:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 4270:                           '<option value="" selected="selected">'.&mt('None').
 4271:                           '</option>'."\n";
 4272:             foreach my $server (sort(keys(%servers))) {
 4273:                 next if ($currbalancer{$server});
 4274:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 4275:             }
 4276:             $datatable .=
 4277:                 '</select>'."\n".
 4278:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 4279:         } else {
 4280:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 4281:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 4282:                            &mt('Stop balancing').'</label>'.
 4283:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 4284:             $targets_div_style = 'display: block';
 4285:             $disabled_div_style = 'display: none';
 4286:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 4287:                 $homedom_div_style = 'display: block';
 4288:             }
 4289:         }
 4290:         $datatable .= '</p></td><td rowspan="'.$rownum.'" valign="top">'.
 4291:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 4292:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 4293:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 4294:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 4295:         my @sparestypes = ('primary','default');
 4296:         my %typetitles = &sparestype_titles();
 4297:         foreach my $sparetype (@sparestypes) {
 4298:             my $targettable;
 4299:             for (my $i=0; $i<$numspares; $i++) {
 4300:                 my $checked;
 4301:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 4302:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 4303:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 4304:                             $checked = ' checked="checked"';
 4305:                         }
 4306:                     }
 4307:                 }
 4308:                 my ($chkboxval,$disabled);
 4309:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 4310:                     $chkboxval = $spares[$i];
 4311:                 }
 4312:                 if (exists($currbalancer{$spares[$i]})) {
 4313:                     $disabled = ' disabled="disabled"';
 4314:                 }
 4315:                 $targettable .=
 4316:                     '<td><span class="LC_nobreak"><label>'.
 4317:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 4318:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 4319:                     '</span></label></span></td>';
 4320:                 my $rem = $i%($numinrow);
 4321:                 if ($rem == 0) {
 4322:                     if (($i > 0) && ($i < $numspares-1)) {
 4323:                         $targettable .= '</tr>';
 4324:                     }
 4325:                     if ($i < $numspares-1) {
 4326:                         $targettable .= '<tr>';
 4327:                     }
 4328:                 }
 4329:             }
 4330:             if ($targettable ne '') {
 4331:                 my $rem = $numspares%($numinrow);
 4332:                 my $colsleft = $numinrow - $rem;
 4333:                 if ($colsleft > 1 ) {
 4334:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4335:                                     '&nbsp;</td>';
 4336:                 } elsif ($colsleft == 1) {
 4337:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 4338:                 }
 4339:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 4340:                                '<table><tr>'.$targettable.'</tr></table><br />';
 4341:             }
 4342:         }
 4343:         $datatable .= '</div></td></tr>'.
 4344:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 4345:                                            $othertitle,$usertypes,$types,\%servers,
 4346:                                            \%currbalancer,$lonhost,
 4347:                                            $targets_div_style,$homedom_div_style,
 4348:                                            $css_class[$cssidx],$balnum,$islast);
 4349:         $$rowtotal += $rownum;
 4350:         $balnum ++;
 4351:     }
 4352:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 4353:     return $datatable;
 4354: }
 4355: 
 4356: sub get_loadbalancers_config {
 4357:     my ($servers,$existing,$currbalancer,$currtargets,$currrules) = @_;
 4358:     return unless ((ref($servers) eq 'HASH') &&
 4359:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 4360:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH'));
 4361:     if (keys(%{$existing}) > 0) {
 4362:         my $oldlonhost;
 4363:         foreach my $key (sort(keys(%{$existing}))) {
 4364:             if ($key eq 'lonhost') {
 4365:                 $oldlonhost = $existing->{'lonhost'};
 4366:                 $currbalancer->{$oldlonhost} = 1;
 4367:             } elsif ($key eq 'targets') {
 4368:                 if ($oldlonhost) {
 4369:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 4370:                 }
 4371:             } elsif ($key eq 'rules') {
 4372:                 if ($oldlonhost) {
 4373:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 4374:                 }
 4375:             } elsif (ref($existing->{$key}) eq 'HASH') {
 4376:                 $currbalancer->{$key} = 1;
 4377:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 4378:                 $currrules->{$key} = $existing->{$key}{'rules'};
 4379:             }
 4380:         }
 4381:     } else {
 4382:         my ($balancerref,$targetsref) =
 4383:                 &Apache::lonnet::get_lonbalancer_config($servers);
 4384:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 4385:             foreach my $server (sort(keys(%{$balancerref}))) {
 4386:                 $currbalancer->{$server} = 1;
 4387:                 $currtargets->{$server} = $targetsref->{$server};
 4388:             }
 4389:         }
 4390:     }
 4391:     return;
 4392: }
 4393: 
 4394: sub loadbalancing_rules {
 4395:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 4396:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 4397:         $css_class,$balnum,$islast) = @_;
 4398:     my $output;
 4399:     my $num = 0;
 4400:     my ($alltypes,$othertypes,$titles) =
 4401:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 4402:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 4403:         foreach my $type (@{$alltypes}) {
 4404:             $num ++;
 4405:             my $current;
 4406:             if (ref($currrules) eq 'HASH') {
 4407:                 $current = $currrules->{$type};
 4408:             }
 4409:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 4410:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 4411:                     $current = '';
 4412:                 }
 4413:             }
 4414:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 4415:                                              $servers,$currbalancer,$lonhost,$dom,
 4416:                                              $targets_div_style,$homedom_div_style,
 4417:                                              $css_class,$balnum,$num,$islast);
 4418:         }
 4419:     }
 4420:     return $output;
 4421: }
 4422: 
 4423: sub loadbalancing_titles {
 4424:     my ($dom,$intdom,$usertypes,$types) = @_;
 4425:     my %othertypes = (
 4426:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 4427:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 4428:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 4429:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 4430:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 4431:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 4432:                      );
 4433:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 4434:     if (ref($types) eq 'ARRAY') {
 4435:         unshift(@alltypes,@{$types},'default');
 4436:     }
 4437:     my %titles;
 4438:     foreach my $type (@alltypes) {
 4439:         if ($type =~ /^_LC_/) {
 4440:             $titles{$type} = $othertypes{$type};
 4441:         } elsif ($type eq 'default') {
 4442:             $titles{$type} = &mt('All users from [_1]',$dom);
 4443:             if (ref($types) eq 'ARRAY') {
 4444:                 if (@{$types} > 0) {
 4445:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 4446:                 }
 4447:             }
 4448:         } elsif (ref($usertypes) eq 'HASH') {
 4449:             $titles{$type} = $usertypes->{$type};
 4450:         }
 4451:     }
 4452:     return (\@alltypes,\%othertypes,\%titles);
 4453: }
 4454: 
 4455: sub loadbalance_rule_row {
 4456:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 4457:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 4458:     my @rulenames;
 4459:     my %ruletitles = &offloadtype_text();
 4460:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 4461:         @rulenames = ('balancer','offloadedto','specific');
 4462:     } else {
 4463:         @rulenames = ('default','homeserver');
 4464:         if ($type eq '_LC_external') {
 4465:             push(@rulenames,'externalbalancer');
 4466:         } else {
 4467:             push(@rulenames,'specific');
 4468:         }
 4469:         push(@rulenames,'none');
 4470:     }
 4471:     my $style = $targets_div_style;
 4472:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 4473:         $style = $homedom_div_style;
 4474:     }
 4475:     my $space;
 4476:     if ($islast && $num == 1) {
 4477:         $space = '<div display="inline-block">&nbsp;</div>';
 4478:     }
 4479:     my $output =
 4480:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td valign="top">'.$space.
 4481:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 4482:         '<td valaign="top">'.$space.
 4483:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 4484:     for (my $i=0; $i<@rulenames; $i++) {
 4485:         my $rule = $rulenames[$i];
 4486:         my ($checked,$extra);
 4487:         if ($rulenames[$i] eq 'default') {
 4488:             $rule = '';
 4489:         }
 4490:         if ($rulenames[$i] eq 'specific') {
 4491:             if (ref($servers) eq 'HASH') {
 4492:                 my $default;
 4493:                 if (($current ne '') && (exists($servers->{$current}))) {
 4494:                     $checked = ' checked="checked"';
 4495:                 }
 4496:                 unless ($checked) {
 4497:                     $default = ' selected="selected"';
 4498:                 }
 4499:                 $extra =
 4500:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 4501:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 4502:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 4503:                     '<option value=""'.$default.'></option>'."\n";
 4504:                 foreach my $server (sort(keys(%{$servers}))) {
 4505:                     if (ref($currbalancer) eq 'HASH') {
 4506:                         next if (exists($currbalancer->{$server}));
 4507:                     }
 4508:                     my $selected;
 4509:                     if ($server eq $current) {
 4510:                         $selected = ' selected="selected"';
 4511:                     }
 4512:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 4513:                 }
 4514:                 $extra .= '</select>';
 4515:             }
 4516:         } elsif ($rule eq $current) {
 4517:             $checked = ' checked="checked"';
 4518:         }
 4519:         $output .= '<span class="LC_nobreak"><label>'.
 4520:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 4521:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 4522:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 4523:                    ')"'.$checked.' />&nbsp;';
 4524:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 4525:             $output .= $ruletitles{'particular'};
 4526:         } else {
 4527:             $output .= $ruletitles{$rulenames[$i]};
 4528:         }
 4529:         $output .= '</label>'.$extra.'</span><br />'."\n";
 4530:     }
 4531:     $output .= '</div></td></tr>'."\n";
 4532:     return $output;
 4533: }
 4534: 
 4535: sub offloadtype_text {
 4536:     my %ruletitles = &Apache::lonlocal::texthash (
 4537:            'default'          => 'Offloads to default destinations',
 4538:            'homeserver'       => "Offloads to user's home server",
 4539:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 4540:            'specific'         => 'Offloads to specific server',
 4541:            'none'             => 'No offload',
 4542:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 4543:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 4544:            'particular'       => 'Session hosted (after re-auth) on server:',
 4545:     );
 4546:     return %ruletitles;
 4547: }
 4548: 
 4549: sub sparestype_titles {
 4550:     my %typestitles = &Apache::lonlocal::texthash (
 4551:                           'primary' => 'primary',
 4552:                           'default' => 'default',
 4553:                       );
 4554:     return %typestitles;
 4555: }
 4556: 
 4557: sub contact_titles {
 4558:     my %titles = &Apache::lonlocal::texthash (
 4559:                    'supportemail' => 'Support E-mail address',
 4560:                    'adminemail'   => 'Default Server Admin E-mail address',
 4561:                    'errormail'    => 'Error reports to be e-mailed to',
 4562:                    'packagesmail' => 'Package update alerts to be e-mailed to',
 4563:                    'helpdeskmail' => 'Helpdesk requests to be e-mailed to',
 4564:                    'lonstatusmail' => 'E-mail from nightly status check (warnings/errors)',
 4565:                    'requestsmail' => 'E-mail from course requests requiring approval',
 4566:                    'updatesmail'  => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 4567:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 4568:                  );
 4569:     my %short_titles = &Apache::lonlocal::texthash (
 4570:                            adminemail   => 'Admin E-mail address',
 4571:                            supportemail => 'Support E-mail',
 4572:                        );   
 4573:     return (\%titles,\%short_titles);
 4574: }
 4575: 
 4576: sub tool_titles {
 4577:     my %titles = &Apache::lonlocal::texthash (
 4578:                      aboutme    => 'Personal web page',
 4579:                      blog       => 'Blog',
 4580:                      webdav     => 'WebDAV',
 4581:                      portfolio  => 'Portfolio',
 4582:                      official   => 'Official courses (with institutional codes)',
 4583:                      unofficial => 'Unofficial courses',
 4584:                      community  => 'Communities',
 4585:                      textbook   => 'Textbook courses',
 4586:                      placement  => 'Placement tests',
 4587:                  );
 4588:     return %titles;
 4589: }
 4590: 
 4591: sub courserequest_titles {
 4592:     my %titles = &Apache::lonlocal::texthash (
 4593:                                    official   => 'Official',
 4594:                                    unofficial => 'Unofficial',
 4595:                                    community  => 'Communities',
 4596:                                    textbook   => 'Textbook',
 4597:                                    placement  => 'Placement tests',
 4598:                                    norequest  => 'Not allowed',
 4599:                                    approval   => 'Approval by Dom. Coord.',
 4600:                                    validate   => 'With validation',
 4601:                                    autolimit  => 'Numerical limit',
 4602:                                    unlimited  => '(blank for unlimited)',
 4603:                  );
 4604:     return %titles;
 4605: }
 4606: 
 4607: sub authorrequest_titles {
 4608:     my %titles = &Apache::lonlocal::texthash (
 4609:                                    norequest  => 'Not allowed',
 4610:                                    approval   => 'Approval by Dom. Coord.',
 4611:                                    automatic  => 'Automatic approval',
 4612:                  );
 4613:     return %titles;
 4614: }
 4615: 
 4616: sub courserequest_conditions {
 4617:     my %conditions = &Apache::lonlocal::texthash (
 4618:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 4619:        validate   => '(Processing of request subject to institutional validation).',
 4620:                  );
 4621:     return %conditions;
 4622: }
 4623: 
 4624: 
 4625: sub print_usercreation {
 4626:     my ($position,$dom,$settings,$rowtotal) = @_;
 4627:     my $numinrow = 4;
 4628:     my $datatable;
 4629:     if ($position eq 'top') {
 4630:         $$rowtotal ++;
 4631:         my $rowcount = 0;
 4632:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 4633:         if (ref($rules) eq 'HASH') {
 4634:             if (keys(%{$rules}) > 0) {
 4635:                 $datatable .= &user_formats_row('username',$settings,$rules,
 4636:                                                 $ruleorder,$numinrow,$rowcount);
 4637:                 $$rowtotal ++;
 4638:                 $rowcount ++;
 4639:             }
 4640:         }
 4641:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 4642:         if (ref($idrules) eq 'HASH') {
 4643:             if (keys(%{$idrules}) > 0) {
 4644:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 4645:                                                 $idruleorder,$numinrow,$rowcount);
 4646:                 $$rowtotal ++;
 4647:                 $rowcount ++;
 4648:             }
 4649:         }
 4650:         if ($rowcount == 0) {
 4651:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 4652:             $$rowtotal ++;
 4653:             $rowcount ++;
 4654:         }
 4655:     } elsif ($position eq 'middle') {
 4656:         my @creators = ('author','course','requestcrs');
 4657:         my ($rules,$ruleorder) =
 4658:             &Apache::lonnet::inst_userrules($dom,'username');
 4659:         my %lt = &usercreation_types();
 4660:         my %checked;
 4661:         if (ref($settings) eq 'HASH') {
 4662:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 4663:                 foreach my $item (@creators) {
 4664:                     $checked{$item} = $settings->{'cancreate'}{$item};
 4665:                 }
 4666:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 4667:                 foreach my $item (@creators) {
 4668:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 4669:                         $checked{$item} = 'none';
 4670:                     }
 4671:                 }
 4672:             }
 4673:         }
 4674:         my $rownum = 0;
 4675:         foreach my $item (@creators) {
 4676:             $rownum ++;
 4677:             if ($checked{$item} eq '') {
 4678:                 $checked{$item} = 'any';
 4679:             }
 4680:             my $css_class;
 4681:             if ($rownum%2) {
 4682:                 $css_class = '';
 4683:             } else {
 4684:                 $css_class = ' class="LC_odd_row" ';
 4685:             }
 4686:             $datatable .= '<tr'.$css_class.'>'.
 4687:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 4688:                          '</span></td><td align="right">';
 4689:             my @options = ('any');
 4690:             if (ref($rules) eq 'HASH') {
 4691:                 if (keys(%{$rules}) > 0) {
 4692:                     push(@options,('official','unofficial'));
 4693:                 }
 4694:             }
 4695:             push(@options,'none');
 4696:             foreach my $option (@options) {
 4697:                 my $type = 'radio';
 4698:                 my $check = ' ';
 4699:                 if ($checked{$item} eq $option) {
 4700:                     $check = ' checked="checked" ';
 4701:                 } 
 4702:                 $datatable .= '<span class="LC_nobreak"><label>'.
 4703:                               '<input type="'.$type.'" name="can_createuser_'.
 4704:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 4705:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 4706:             }
 4707:             $datatable .= '</td></tr>';
 4708:         }
 4709:     } else {
 4710:         my @contexts = ('author','course','domain');
 4711:         my @authtypes = ('int','krb4','krb5','loc');
 4712:         my %checked;
 4713:         if (ref($settings) eq 'HASH') {
 4714:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 4715:                 foreach my $item (@contexts) {
 4716:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 4717:                         foreach my $auth (@authtypes) {
 4718:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 4719:                                 $checked{$item}{$auth} = ' checked="checked" ';
 4720:                             }
 4721:                         }
 4722:                     }
 4723:                 }
 4724:             }
 4725:         } else {
 4726:             foreach my $item (@contexts) {
 4727:                 foreach my $auth (@authtypes) {
 4728:                     $checked{$item}{$auth} = ' checked="checked" ';
 4729:                 }
 4730:             }
 4731:         }
 4732:         my %title = &context_names();
 4733:         my %authname = &authtype_names();
 4734:         my $rownum = 0;
 4735:         my $css_class; 
 4736:         foreach my $item (@contexts) {
 4737:             if ($rownum%2) {
 4738:                 $css_class = '';
 4739:             } else {
 4740:                 $css_class = ' class="LC_odd_row" ';
 4741:             }
 4742:             $datatable .=   '<tr'.$css_class.'>'.
 4743:                             '<td>'.$title{$item}.
 4744:                             '</td><td class="LC_left_item">'.
 4745:                             '<span class="LC_nobreak">';
 4746:             foreach my $auth (@authtypes) {
 4747:                 $datatable .= '<label>'. 
 4748:                               '<input type="checkbox" name="'.$item.'_auth" '.
 4749:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 4750:                               $authname{$auth}.'</label>&nbsp;';
 4751:             }
 4752:             $datatable .= '</span></td></tr>';
 4753:             $rownum ++;
 4754:         }
 4755:         $$rowtotal += $rownum;
 4756:     }
 4757:     return $datatable;
 4758: }
 4759: 
 4760: sub print_selfcreation {
 4761:     my ($position,$dom,$settings,$rowtotal) = @_;
 4762:     my (@selfcreate,$createsettings,$processing,$datatable);
 4763:     if (ref($settings) eq 'HASH') {
 4764:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 4765:             $createsettings = $settings->{'cancreate'};
 4766:             if (ref($createsettings) eq 'HASH') {
 4767:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 4768:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 4769:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 4770:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 4771:                         @selfcreate = ('email','login','sso');
 4772:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 4773:                         @selfcreate = ($createsettings->{'selfcreate'});
 4774:                     }
 4775:                 }
 4776:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 4777:                     $processing = $createsettings->{'selfcreateprocessing'};
 4778:                 }
 4779:             }
 4780:         }
 4781:     }
 4782:     my %radiohash;
 4783:     my $numinrow = 4;
 4784:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 4785:     if ($position eq 'top') {
 4786:         my %choices = &Apache::lonlocal::texthash (
 4787:                                                       cancreate_login      => 'Institutional Login',
 4788:                                                       cancreate_sso        => 'Institutional Single Sign On',
 4789:                                                   );
 4790:         my @toggles = sort(keys(%choices));
 4791:         my %defaultchecked = (
 4792:                                'cancreate_login' => 'off',
 4793:                                'cancreate_sso'   => 'off',
 4794:                              );
 4795:         my ($onclick,$itemcount);
 4796:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 4797:                                                      \%choices,$itemcount,$onclick);
 4798:         $$rowtotal += $itemcount;
 4799:         
 4800:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4801: 
 4802:         if (ref($usertypes) eq 'HASH') {
 4803:             if (keys(%{$usertypes}) > 0) {
 4804:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 4805:                                              $dom,$numinrow,$othertitle,
 4806:                                              'statustocreate',$$rowtotal);
 4807:                 $$rowtotal ++;
 4808:             }
 4809:         }
 4810:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 4811:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 4812:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 4813:         my $rem;
 4814:         my $numperrow = 2;
 4815:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 4816:         $datatable .= '<tr'.$css_class.'>'.
 4817:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 4818:                      '<td class="LC_left_item">'."\n".
 4819:                      '<table><tr><td>'."\n";
 4820:         for (my $i=0; $i<@fields; $i++) {
 4821:             $rem = $i%($numperrow);
 4822:             if ($rem == 0) {
 4823:                 if ($i > 0) {
 4824:                     $datatable .= '</tr>';
 4825:                 }
 4826:                 $datatable .= '<tr>';
 4827:             }
 4828:             my $currval;
 4829:             if (ref($createsettings) eq 'HASH') {
 4830:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 4831:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 4832:                 }
 4833:             }
 4834:             $datatable .= '<td class="LC_left_item">'.
 4835:                           '<span class="LC_nobreak">'.
 4836:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 4837:                           'value="'.$currval.'" size="10" />&nbsp;'.
 4838:                           $fieldtitles{$fields[$i]}.'</span></td>';
 4839:         }
 4840:         my $colsleft = $numperrow - $rem;
 4841:         if ($colsleft > 1 ) {
 4842:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4843:                          '&nbsp;</td>';
 4844:         } elsif ($colsleft == 1) {
 4845:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 4846:         }
 4847:         $datatable .= '</tr></table></td></tr>';
 4848:         $$rowtotal ++;
 4849:     } elsif ($position eq 'middle') {
 4850:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 4851:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4852:         $usertypes->{'default'} = $othertitle;
 4853:         if (ref($types) eq 'ARRAY') {
 4854:             push(@{$types},'default');
 4855:             $usertypes->{'default'} = $othertitle;
 4856:             foreach my $status (@{$types}) {
 4857:                 $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 4858:                                                        $numinrow,$$rowtotal,$usertypes);
 4859:                 $$rowtotal ++;
 4860:             }
 4861:         }
 4862:     } else {
 4863:         my %choices = &Apache::lonlocal::texthash (
 4864:                                                       cancreate_email => 'E-mail address as username',
 4865:                                                   );
 4866:         my @toggles = sort(keys(%choices));
 4867:         my %defaultchecked = (
 4868:                                'cancreate_email' => 'off',
 4869:                              );
 4870:         my $itemcount = 0;
 4871:         my $display = 'none';
 4872:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 4873:             $display = 'block';
 4874:         }
 4875:         my $onclick = "toggleDisplay(this.form,'emailoptions');";
 4876:         my $additional = '<div id="emailoptions" style="display: '.$display.'">';
 4877:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 4878:         my $usertypes = {};
 4879:         my $order = [];
 4880:         if ((ref($domdefaults{'inststatustypes'}) eq 'HASH') && (ref($domdefaults{'inststatusguest'}) eq 'ARRAY')) {
 4881:             $usertypes = $domdefaults{'inststatustypes'};
 4882:             $order = $domdefaults{'inststatusguest'};
 4883:         }
 4884:         if (ref($order) eq 'ARRAY') {
 4885:             push(@{$order},'default');
 4886:             if (@{$order} > 1) {
 4887:                 $usertypes->{'default'} = &mt('Other users');
 4888:                 $additional .= '<table><tr>';
 4889:                 foreach my $status (@{$order}) {
 4890:                     $additional .= '<th>'.$usertypes->{$status}.'</th>';
 4891:                 }
 4892:                 $additional .= '</tr><tr>';
 4893:                 foreach my $status (@{$order}) {
 4894:                     $additional .= '<td>'.&email_as_username($rowtotal,$processing,$status).'</td>';
 4895:                 }
 4896:                 $additional .= '</tr></table>';
 4897:             } else {
 4898:                 $usertypes->{'default'} = &mt('All users');
 4899:                 $additional .= &email_as_username($rowtotal,$processing);
 4900:             }
 4901:         }
 4902:         $additional .= '</div>'."\n";
 4903: 
 4904:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 4905:                                                      \%choices,$$rowtotal,$onclick,$additional);
 4906:         $$rowtotal ++;
 4907:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal);
 4908:         $$rowtotal ++;
 4909:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 4910:         $numinrow = 1;
 4911:         if (ref($order) eq 'ARRAY') {
 4912:             foreach my $status (@{$order}) {
 4913:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 4914:                                                        $numinrow,$$rowtotal,$usertypes,$infofields,$infotitles);
 4915:                 $$rowtotal ++;
 4916:             }
 4917:         }
 4918:         my ($emailrules,$emailruleorder) =
 4919:             &Apache::lonnet::inst_userrules($dom,'email');
 4920:         if (ref($emailrules) eq 'HASH') {
 4921:             if (keys(%{$emailrules}) > 0) {
 4922:                 $datatable .= &user_formats_row('email',$settings,$emailrules,
 4923:                                                 $emailruleorder,$numinrow,$$rowtotal);
 4924:                 $$rowtotal ++;
 4925:             }
 4926:         }
 4927:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal);
 4928:     }
 4929:     return $datatable;
 4930: }
 4931: 
 4932: sub email_as_username {
 4933:     my ($rowtotal,$processing,$type) = @_;
 4934:     my %choices =
 4935:         &Apache::lonlocal::texthash (
 4936:                                       automatic => 'Automatic approval',
 4937:                                       approval  => 'Queued for approval',
 4938:                                     );
 4939:     my $output;
 4940:     foreach my $option ('automatic','approval') {
 4941:         my $checked;
 4942:         if (ref($processing) eq 'HASH') {
 4943:             if ($type eq '') {   
 4944:                 if (!exists($processing->{'default'})) {
 4945:                     if ($option eq 'automatic') {
 4946:                         $checked = ' checked="checked"';
 4947:                     }
 4948:                 } else {
 4949:                     if ($processing->{'default'} eq $option) {
 4950:                         $checked = ' checked="checked"';
 4951:                     }
 4952:                 }
 4953:             } else {
 4954:                 if (!exists($processing->{$type})) {
 4955:                     if ($option eq 'automatic') {
 4956:                         $checked = ' checked="checked"';
 4957:                     }
 4958:                 } else {
 4959:                     if ($processing->{$type} eq $option) {
 4960:                         $checked = ' checked="checked"';
 4961:                     }
 4962:                 }
 4963:             }
 4964:         } elsif ($option eq 'automatic') {
 4965:             $checked = ' checked="checked"'; 
 4966:         }
 4967:         my $name = 'cancreate_emailprocess';
 4968:         if (($type ne '') && ($type ne 'default')) {
 4969:             $name .= '_'.$type;
 4970:         }
 4971:         $output .= '<span class="LC_nobreak"><label>'.
 4972:                    '<input type="radio" name="'.$name.'"'.
 4973:                    $checked.' value="'.$option.'" />'.
 4974:                    $choices{$option}.'</label></span>';
 4975:         if ($type eq '') {
 4976:             $output .= '&nbsp;';
 4977:         } else {
 4978:             $output .= '<br />';
 4979:         }
 4980:     }
 4981:     $$rowtotal ++;
 4982:     return $output;
 4983: }
 4984: 
 4985: sub captcha_choice {
 4986:     my ($context,$settings,$itemcount) = @_;
 4987:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
 4988:         $vertext,$currver);
 4989:     my %lt = &captcha_phrases();
 4990:     $keyentry = 'hidden';
 4991:     if ($context eq 'cancreate') {
 4992:         $rowname = &mt('CAPTCHA validation');
 4993:     } elsif ($context eq 'login') {
 4994:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
 4995:     }
 4996:     if (ref($settings) eq 'HASH') {
 4997:         if ($settings->{'captcha'}) {
 4998:             $checked{$settings->{'captcha'}} = ' checked="checked"';
 4999:         } else {
 5000:             $checked{'original'} = ' checked="checked"';
 5001:         }
 5002:         if ($settings->{'captcha'} eq 'recaptcha') {
 5003:             $pubtext = $lt{'pub'};
 5004:             $privtext = $lt{'priv'};
 5005:             $keyentry = 'text';
 5006:             $vertext = $lt{'ver'};
 5007:             $currver = $settings->{'recaptchaversion'};
 5008:             if ($currver ne '2') {
 5009:                 $currver = 1;
 5010:             }
 5011:         }
 5012:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
 5013:             $currpub = $settings->{'recaptchakeys'}{'public'};
 5014:             $currpriv = $settings->{'recaptchakeys'}{'private'};
 5015:         }
 5016:     } else {
 5017:         $checked{'original'} = ' checked="checked"';
 5018:     }
 5019:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5020:     my $output = '<tr'.$css_class.'>'.
 5021:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="2">'."\n".
 5022:                  '<table><tr><td>'."\n";
 5023:     foreach my $option ('original','recaptcha','notused') {
 5024:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
 5025:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
 5026:                    $lt{$option}.'</label></span>';
 5027:         unless ($option eq 'notused') {
 5028:             $output .= ('&nbsp;'x2)."\n";
 5029:         }
 5030:     }
 5031: #
 5032: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
 5033: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
 5034: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
 5035: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
 5036: #
 5037:     $output .= '</td></tr>'."\n".
 5038:                '<tr><td>'."\n".
 5039:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
 5040:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
 5041:                $currpub.'" size="40" /></span><br />'."\n".
 5042:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
 5043:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
 5044:                $currpriv.'" size="40" /></span><br />'.
 5045:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
 5046:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
 5047:                $currver.'" size="3" /></span><br />'.
 5048:                '</td></tr></table>'."\n".
 5049:                '</td></tr>';
 5050:     return $output;
 5051: }
 5052: 
 5053: sub user_formats_row {
 5054:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount) = @_;
 5055:     my $output;
 5056:     my %text = (
 5057:                    'username' => 'new usernames',
 5058:                    'id'       => 'IDs',
 5059:                    'email'    => 'self-created accounts (e-mail)',
 5060:                );
 5061:     my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 5062:     $output = '<tr '.$css_class.'>'.
 5063:               '<td><span class="LC_nobreak">';
 5064:     if ($type eq 'email') {
 5065:         $output .= &mt("Formats disallowed for $text{$type}: ");
 5066:     } else {
 5067:         $output .= &mt("Format rules to check for $text{$type}: ");
 5068:     }
 5069:     $output .= '</span></td>'.
 5070:                '<td class="LC_left_item" colspan="2"><table>';
 5071:     my $rem;
 5072:     if (ref($ruleorder) eq 'ARRAY') {
 5073:         for (my $i=0; $i<@{$ruleorder}; $i++) {
 5074:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
 5075:                 my $rem = $i%($numinrow);
 5076:                 if ($rem == 0) {
 5077:                     if ($i > 0) {
 5078:                         $output .= '</tr>';
 5079:                     }
 5080:                     $output .= '<tr>';
 5081:                 }
 5082:                 my $check = ' ';
 5083:                 if (ref($settings) eq 'HASH') {
 5084:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
 5085:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
 5086:                             $check = ' checked="checked" ';
 5087:                         }
 5088:                     }
 5089:                 }
 5090:                 $output .= '<td class="LC_left_item">'.
 5091:                            '<span class="LC_nobreak"><label>'.
 5092:                            '<input type="checkbox" name="'.$type.'_rule" '.
 5093:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
 5094:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
 5095:             }
 5096:         }
 5097:         $rem = @{$ruleorder}%($numinrow);
 5098:     }
 5099:     my $colsleft = $numinrow - $rem;
 5100:     if ($colsleft > 1 ) {
 5101:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 5102:                    '&nbsp;</td>';
 5103:     } elsif ($colsleft == 1) {
 5104:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 5105:     }
 5106:     $output .= '</tr></table></td></tr>';
 5107:     return $output;
 5108: }
 5109: 
 5110: sub usercreation_types {
 5111:     my %lt = &Apache::lonlocal::texthash (
 5112:                     author     => 'When adding a co-author',
 5113:                     course     => 'When adding a user to a course',
 5114:                     requestcrs => 'When requesting a course',
 5115:                     any        => 'Any',
 5116:                     official   => 'Institutional only ',
 5117:                     unofficial => 'Non-institutional only',
 5118:                     none       => 'None',
 5119:     );
 5120:     return %lt;
 5121: }
 5122: 
 5123: sub selfcreation_types {
 5124:     my %lt = &Apache::lonlocal::texthash (
 5125:                     selfcreate => 'User creates own account',
 5126:                     any        => 'Any',
 5127:                     official   => 'Institutional only ',
 5128:                     unofficial => 'Non-institutional only',
 5129:                     email      => 'E-mail address',
 5130:                     login      => 'Institutional Login',
 5131:                     sso        => 'SSO',
 5132:              );
 5133: }
 5134: 
 5135: sub authtype_names {
 5136:     my %lt = &Apache::lonlocal::texthash(
 5137:                       int    => 'Internal',
 5138:                       krb4   => 'Kerberos 4',
 5139:                       krb5   => 'Kerberos 5',
 5140:                       loc    => 'Local',
 5141:                   );
 5142:     return %lt;
 5143: }
 5144: 
 5145: sub context_names {
 5146:     my %context_title = &Apache::lonlocal::texthash(
 5147:        author => 'Creating users when an Author',
 5148:        course => 'Creating users when in a course',
 5149:        domain => 'Creating users when a Domain Coordinator',
 5150:     );
 5151:     return %context_title;
 5152: }
 5153: 
 5154: sub print_usermodification {
 5155:     my ($position,$dom,$settings,$rowtotal) = @_;
 5156:     my $numinrow = 4;
 5157:     my ($context,$datatable,$rowcount);
 5158:     if ($position eq 'top') {
 5159:         $rowcount = 0;
 5160:         $context = 'author'; 
 5161:         foreach my $role ('ca','aa') {
 5162:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 5163:                                                    $numinrow,$rowcount);
 5164:             $$rowtotal ++;
 5165:             $rowcount ++;
 5166:         }
 5167:     } elsif ($position eq 'bottom') {
 5168:         $context = 'course';
 5169:         $rowcount = 0;
 5170:         foreach my $role ('st','ep','ta','in','cr') {
 5171:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 5172:                                                    $numinrow,$rowcount);
 5173:             $$rowtotal ++;
 5174:             $rowcount ++;
 5175:         }
 5176:     }
 5177:     return $datatable;
 5178: }
 5179: 
 5180: sub print_defaults {
 5181:     my ($position,$dom,$settings,$rowtotal) = @_;
 5182:     my $rownum = 0;
 5183:     my ($datatable,$css_class);
 5184:     if ($position eq 'top') {
 5185:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
 5186:                      'datelocale_def','portal_def');
 5187:         my %defaults;
 5188:         if (ref($settings) eq 'HASH') {
 5189:             %defaults = %{$settings};
 5190:         } else {
 5191:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 5192:             foreach my $item (@items) {
 5193:                 $defaults{$item} = $domdefaults{$item};
 5194:             }
 5195:         }
 5196:         my $titles = &defaults_titles($dom);
 5197:         foreach my $item (@items) {
 5198:             if ($rownum%2) {
 5199:                 $css_class = '';
 5200:             } else {
 5201:                 $css_class = ' class="LC_odd_row" ';
 5202:             }
 5203:             $datatable .= '<tr'.$css_class.'>'.
 5204:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 5205:                           '</span></td><td class="LC_right_item" colspan="3">';
 5206:             if ($item eq 'auth_def') {
 5207:                 my @authtypes = ('internal','krb4','krb5','localauth');
 5208:                 my %shortauth = (
 5209:                                  internal => 'int',
 5210:                                  krb4 => 'krb4',
 5211:                                  krb5 => 'krb5',
 5212:                                  localauth  => 'loc'
 5213:                                 );
 5214:                 my %authnames = &authtype_names();
 5215:                 foreach my $auth (@authtypes) {
 5216:                     my $checked = ' ';
 5217:                     if ($defaults{$item} eq $auth) {
 5218:                         $checked = ' checked="checked" ';
 5219:                     }
 5220:                     $datatable .= '<label><input type="radio" name="'.$item.
 5221:                                   '" value="'.$auth.'"'.$checked.'/>'.
 5222:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
 5223:                 }
 5224:             } elsif ($item eq 'timezone_def') {
 5225:                 my $includeempty = 1;
 5226:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
 5227:             } elsif ($item eq 'datelocale_def') {
 5228:                 my $includeempty = 1;
 5229:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
 5230:             } elsif ($item eq 'lang_def') {
 5231:                 my $includeempty = 1;
 5232:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
 5233:             } else {
 5234:                 my $size;
 5235:                 if ($item eq 'portal_def') {
 5236:                     $size = ' size="25"';
 5237:                 }
 5238:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 5239:                               $defaults{$item}.'"'.$size.' />';
 5240:             }
 5241:             $datatable .= '</td></tr>';
 5242:             $rownum ++;
 5243:         }
 5244:     } else {
 5245:         my (%defaults);
 5246:         if (ref($settings) eq 'HASH') {
 5247:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH') &&
 5248:                 (ref($settings->{'inststatusguest'}) eq 'ARRAY')) {
 5249:                 my $maxnum = @{$settings->{'inststatusorder'}};
 5250:                 for (my $i=0; $i<$maxnum; $i++) {
 5251:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
 5252:                     my $item = $settings->{'inststatusorder'}->[$i];
 5253:                     my $title = $settings->{'inststatustypes'}->{$item};
 5254:                     my $guestok;
 5255:                     if (grep(/^\Q$item\E$/,@{$settings->{'inststatusguest'}})) {
 5256:                         $guestok = 1;
 5257:                     }
 5258:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
 5259:                     $datatable .= '<tr'.$css_class.'>'.
 5260:                                   '<td><span class="LC_nobreak">'.
 5261:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
 5262:                     for (my $k=0; $k<=$maxnum; $k++) {
 5263:                         my $vpos = $k+1;
 5264:                         my $selstr;
 5265:                         if ($k == $i) {
 5266:                             $selstr = ' selected="selected" ';
 5267:                         }
 5268:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5269:                     }
 5270:                     my ($checkedon,$checkedoff);
 5271:                     $checkedoff = ' checked="checked"';
 5272:                     if ($guestok) {
 5273:                         $checkedon = $checkedoff;
 5274:                         $checkedoff = ''; 
 5275:                     }
 5276:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
 5277:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
 5278:                                   &mt('delete').'</span></td>'.
 5279:                                   '<td class="LC_left_item"><span class="LC_nobreak">'.&mt('Name displayed:').
 5280:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
 5281:                                   '</span></td>'.
 5282:                                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 5283:                                   '<label><input type="radio" value="1" name="inststatus_guest_'.$item.'"'.$checkedon.' />'.
 5284:                                   &mt('Yes').'</label>'.('&nbsp;'x2).
 5285:                                   '<label><input type="radio" value="0" name="inststatus_guest_'.$item.'"'.$checkedoff.' />'.
 5286:                                   &mt('No').'</label></span></td></tr>';
 5287:                 }
 5288:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
 5289:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
 5290:                 $datatable .= '<tr '.$css_class.'>'.
 5291:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
 5292:                 for (my $k=0; $k<=$maxnum; $k++) {
 5293:                     my $vpos = $k+1;
 5294:                     my $selstr;
 5295:                     if ($k == $maxnum) {
 5296:                         $selstr = ' selected="selected" ';
 5297:                     }
 5298:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5299:                 }
 5300:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
 5301:                               '<input type="text" size="10" name="addinststatus" value="" />'.
 5302:                               '&nbsp;'.&mt('(new)').
 5303:                               '</span></td><td class="LC_left_item"><span class="LC_nobreak">'.
 5304:                               &mt('Name displayed:').
 5305:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
 5306:                               '<td class="LC_right_item"><span class="LC_nobreak">'.
 5307:                               '<label><input type="radio" value="1" name="addinststatus_guest" />'.
 5308:                               &mt('Yes').'</label>'.('&nbsp;'x2).
 5309:                               '<label><input type="radio" value="0" name="addinststatus_guest" />'.
 5310:                               &mt('No').'</label></span></td></tr>';
 5311:                               '</tr>'."\n";
 5312:                 $rownum ++;
 5313:             }
 5314:         }
 5315:     }
 5316:     $$rowtotal += $rownum;
 5317:     return $datatable;
 5318: }
 5319: 
 5320: sub get_languages_hash {
 5321:     my %langchoices;
 5322:     foreach my $id (&Apache::loncommon::languageids()) {
 5323:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 5324:         if ($code ne '') {
 5325:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 5326:         }
 5327:     }
 5328:     return %langchoices;
 5329: }
 5330: 
 5331: sub defaults_titles {
 5332:     my ($dom) = @_;
 5333:     my %titles = &Apache::lonlocal::texthash (
 5334:                    'auth_def'      => 'Default authentication type',
 5335:                    'auth_arg_def'  => 'Default authentication argument',
 5336:                    'lang_def'      => 'Default language',
 5337:                    'timezone_def'  => 'Default timezone',
 5338:                    'datelocale_def' => 'Default locale for dates',
 5339:                    'portal_def'     => 'Portal/Default URL',
 5340:                  );
 5341:     if ($dom) {
 5342:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
 5343:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 5344:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
 5345:         $protocol = 'http' if ($protocol ne 'https');
 5346:         if ($uint_dom) {
 5347:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
 5348:                                          $uint_dom);
 5349:         }
 5350:     }
 5351:     return (\%titles);
 5352: }
 5353: 
 5354: sub print_scantronformat {
 5355:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
 5356:     my $itemcount = 1;
 5357:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
 5358:         %confhash);
 5359:     my $switchserver = &check_switchserver($dom,$confname);
 5360:     my %lt = &Apache::lonlocal::texthash (
 5361:                 default => 'Default bubblesheet format file error',
 5362:                 custom  => 'Custom bubblesheet format file error',
 5363:              );
 5364:     my %scantronfiles = (
 5365:         default => 'default.tab',
 5366:         custom => 'custom.tab',
 5367:     );
 5368:     foreach my $key (keys(%scantronfiles)) {
 5369:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
 5370:                               .$scantronfiles{$key};
 5371:     }
 5372:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
 5373:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
 5374:         if (!$switchserver) {
 5375:             my $servadm = $r->dir_config('lonAdmEMail');
 5376:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
 5377:             if ($configuserok eq 'ok') {
 5378:                 if ($author_ok eq 'ok') {
 5379:                     my %legacyfile = (
 5380:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab', 
 5381:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab', 
 5382:                     );
 5383:                     my %md5chk;
 5384:                     foreach my $type (keys(%legacyfile)) {
 5385:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
 5386:                         chomp($md5chk{$type});
 5387:                     }
 5388:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
 5389:                         foreach my $type (keys(%legacyfile)) {
 5390:                             ($scantronurls{$type},my $error) = 
 5391:                                 &legacy_scantronformat($r,$dom,$confname,
 5392:                                                  $type,$legacyfile{$type},
 5393:                                                  $scantronurls{$type},
 5394:                                                  $scantronfiles{$type});
 5395:                             if ($error ne '') {
 5396:                                 $error{$type} = $error;
 5397:                             }
 5398:                         }
 5399:                         if (keys(%error) == 0) {
 5400:                             $is_custom = 1;
 5401:                             $confhash{'scantron'}{'scantronformat'} = 
 5402:                                 $scantronurls{'custom'};
 5403:                             my $putresult = 
 5404:                                 &Apache::lonnet::put_dom('configuration',
 5405:                                                          \%confhash,$dom);
 5406:                             if ($putresult ne 'ok') {
 5407:                                 $error{'custom'} = 
 5408:                                     '<span class="LC_error">'.
 5409:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 5410:                             }
 5411:                         }
 5412:                     } else {
 5413:                         ($scantronurls{'default'},my $error) =
 5414:                             &legacy_scantronformat($r,$dom,$confname,
 5415:                                           'default',$legacyfile{'default'},
 5416:                                           $scantronurls{'default'},
 5417:                                           $scantronfiles{'default'});
 5418:                         if ($error eq '') {
 5419:                             $confhash{'scantron'}{'scantronformat'} = ''; 
 5420:                             my $putresult =
 5421:                                 &Apache::lonnet::put_dom('configuration',
 5422:                                                          \%confhash,$dom);
 5423:                             if ($putresult ne 'ok') {
 5424:                                 $error{'default'} =
 5425:                                     '<span class="LC_error">'.
 5426:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 5427:                             }
 5428:                         } else {
 5429:                             $error{'default'} = $error;
 5430:                         }
 5431:                     }
 5432:                 }
 5433:             }
 5434:         } else {
 5435:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
 5436:         }
 5437:     }
 5438:     if (ref($settings) eq 'HASH') {
 5439:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
 5440:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
 5441:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
 5442:                 $scantronurl = '';
 5443:             } else {
 5444:                 $scantronurl = $settings->{'scantronformat'};
 5445:             }
 5446:             $is_custom = 1;
 5447:         } else {
 5448:             $scantronurl = $scantronurls{'default'};
 5449:         }
 5450:     } else {
 5451:         if ($is_custom) {
 5452:             $scantronurl = $scantronurls{'custom'};
 5453:         } else {
 5454:             $scantronurl = $scantronurls{'default'};
 5455:         }
 5456:     }
 5457:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5458:     $datatable .= '<tr'.$css_class.'>';
 5459:     if (!$is_custom) {
 5460:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
 5461:                       '<span class="LC_nobreak">';
 5462:         if ($scantronurl) {
 5463:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
 5464:                                                          undef,undef,undef,undef,'background-color:#ffffff');
 5465:         } else {
 5466:             $datatable = &mt('File unavailable for display');
 5467:         }
 5468:         $datatable .= '</span></td>';
 5469:         if (keys(%error) == 0) { 
 5470:             $datatable .= '<td valign="bottom">';
 5471:             if (!$switchserver) {
 5472:                 $datatable .= &mt('Upload:').'<br />';
 5473:             }
 5474:         } else {
 5475:             my $errorstr;
 5476:             foreach my $key (sort(keys(%error))) {
 5477:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 5478:             }
 5479:             $datatable .= '<td>'.$errorstr;
 5480:         }
 5481:     } else {
 5482:         if (keys(%error) > 0) {
 5483:             my $errorstr;
 5484:             foreach my $key (sort(keys(%error))) {
 5485:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 5486:             } 
 5487:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
 5488:         } elsif ($scantronurl) {
 5489:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
 5490:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 5491:             $datatable .= '<td><span class="LC_nobreak">'.
 5492:                           $link.
 5493:                           '<label><input type="checkbox" name="scantronformat_del"'.
 5494:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
 5495:                           '<td><span class="LC_nobreak">&nbsp;'.
 5496:                           &mt('Replace:').'</span><br />';
 5497:         }
 5498:     }
 5499:     if (keys(%error) == 0) {
 5500:         if ($switchserver) {
 5501:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5502:         } else {
 5503:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 5504:                          '<input type="file" name="scantronformat" /></span>';
 5505:         }
 5506:     }
 5507:     $datatable .= '</td></tr>';
 5508:     $$rowtotal ++;
 5509:     return $datatable;
 5510: }
 5511: 
 5512: sub legacy_scantronformat {
 5513:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
 5514:     my ($url,$error);
 5515:     my @statinfo = &Apache::lonnet::stat_file($newurl);
 5516:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
 5517:         (my $result,$url) =
 5518:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
 5519:                          '','',$newfile);
 5520:         if ($result ne 'ok') {
 5521:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
 5522:         }
 5523:     }
 5524:     return ($url,$error);
 5525: }
 5526: 
 5527: sub print_coursecategories {
 5528:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
 5529:     my $datatable;
 5530:     if ($position eq 'top') {
 5531:         my (%checked);
 5532:         my @catitems = ('unauth','auth');
 5533:         my @cattypes = ('std','domonly','codesrch','none');
 5534:         $checked{'unauth'} = 'std';
 5535:         $checked{'auth'} = 'std';
 5536:         if (ref($settings) eq 'HASH') {
 5537:             foreach my $type (@cattypes) {
 5538:                 if ($type eq $settings->{'unauth'}) {
 5539:                     $checked{'unauth'} = $type;
 5540:                 }
 5541:                 if ($type eq $settings->{'auth'}) {
 5542:                     $checked{'auth'} = $type;
 5543:                 }
 5544:             }
 5545:         }
 5546:         my %lt = &Apache::lonlocal::texthash (
 5547:                                                unauth   => 'Catalog type for unauthenticated users',
 5548:                                                auth     => 'Catalog type for authenticated users',
 5549:                                                none     => 'No catalog',
 5550:                                                std      => 'Standard catalog',
 5551:                                                domonly  => 'Domain-only catalog',
 5552:                                                codesrch => "Code search form",
 5553:                                              );
 5554:        my $itemcount = 0;
 5555:        foreach my $item (@catitems) {
 5556:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 5557:            $datatable .= '<tr '.$css_class.'>'.
 5558:                          '<td>'.$lt{$item}.'</td>'.
 5559:                          '<td class="LC_right_item"><span class="LC_nobreak">';
 5560:            foreach my $type (@cattypes) {
 5561:                my $ischecked;
 5562:                if ($checked{$item} eq $type) {
 5563:                    $ischecked=' checked="checked"';
 5564:                }
 5565:                $datatable .= '<label>'.
 5566:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
 5567:                              ' />'.$lt{$type}.'</label>&nbsp;';
 5568:            }
 5569:            $datatable .= '</td></tr>';
 5570:            $itemcount ++;
 5571:         }
 5572:         $$rowtotal += $itemcount;
 5573:     } elsif ($position eq 'middle') {
 5574:         my $toggle_cats_crs = ' ';
 5575:         my $toggle_cats_dom = ' checked="checked" ';
 5576:         my $can_cat_crs = ' ';
 5577:         my $can_cat_dom = ' checked="checked" ';
 5578:         my $toggle_catscomm_comm = ' ';
 5579:         my $toggle_catscomm_dom = ' checked="checked" ';
 5580:         my $can_catcomm_comm = ' ';
 5581:         my $can_catcomm_dom = ' checked="checked" ';
 5582:         my $toggle_catsplace_place = ' ';
 5583:         my $toggle_catsplace_dom = ' checked="checked" ';
 5584:         my $can_catplace_place = ' ';
 5585:         my $can_catplace_dom = ' checked="checked" ';
 5586: 
 5587:         if (ref($settings) eq 'HASH') {
 5588:             if ($settings->{'togglecats'} eq 'crs') {
 5589:                 $toggle_cats_crs = $toggle_cats_dom;
 5590:                 $toggle_cats_dom = ' ';
 5591:             }
 5592:             if ($settings->{'categorize'} eq 'crs') {
 5593:                 $can_cat_crs = $can_cat_dom;
 5594:                 $can_cat_dom = ' ';
 5595:             }
 5596:             if ($settings->{'togglecatscomm'} eq 'comm') {
 5597:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
 5598:                 $toggle_catscomm_dom = ' ';
 5599:             }
 5600:             if ($settings->{'categorizecomm'} eq 'comm') {
 5601:                 $can_catcomm_comm = $can_catcomm_dom;
 5602:                 $can_catcomm_dom = ' ';
 5603:             }
 5604:             if ($settings->{'togglecatsplace'} eq 'place') {
 5605:                 $toggle_catsplace_place = $toggle_catsplace_dom;
 5606:                 $toggle_catsplace_dom = ' ';
 5607:             }
 5608:             if ($settings->{'categorizeplace'} eq 'place') {
 5609:                 $can_catplace_place = $can_catplace_dom;
 5610:                 $can_catplace_dom = ' ';
 5611:             }
 5612:         }
 5613:         my %title = &Apache::lonlocal::texthash (
 5614:                      togglecats      => 'Show/Hide a course in catalog',
 5615:                      togglecatscomm  => 'Show/Hide a community in catalog',
 5616:                      togglecatsplace => 'Show/Hide a placement test in catalog',
 5617:                      categorize      => 'Assign a category to a course',
 5618:                      categorizecomm  => 'Assign a category to a community',
 5619:                      categorizeplace => 'Assign a category to a placement test',
 5620:                     );
 5621:         my %level = &Apache::lonlocal::texthash (
 5622:                      dom   => 'Set in Domain',
 5623:                      crs   => 'Set in Course',
 5624:                      comm  => 'Set in Community',
 5625:                      place => 'Set in Placement Test',
 5626:                     );
 5627:         $datatable = '<tr class="LC_odd_row">'.
 5628:                   '<td>'.$title{'togglecats'}.'</td>'.
 5629:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 5630:                   '<input type="radio" name="togglecats"'.
 5631:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 5632:                   '<label><input type="radio" name="togglecats"'.
 5633:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
 5634:                   '</tr><tr>'.
 5635:                   '<td>'.$title{'categorize'}.'</td>'.
 5636:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 5637:                   '<label><input type="radio" name="categorize"'.
 5638:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 5639:                   '<label><input type="radio" name="categorize"'.
 5640:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
 5641:                   '</tr><tr class="LC_odd_row">'.
 5642:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
 5643:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 5644:                   '<input type="radio" name="togglecatscomm"'.
 5645:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 5646:                   '<label><input type="radio" name="togglecatscomm"'.
 5647:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
 5648:                   '</tr><tr>'.
 5649:                   '<td>'.$title{'categorizecomm'}.'</td>'.
 5650:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 5651:                   '<label><input type="radio" name="categorizecomm"'.
 5652:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 5653:                   '<label><input type="radio" name="categorizecomm"'.
 5654:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
 5655:                   '</tr><tr>'.
 5656:                   '<td>'.$title{'togglecatsplace'}.'</td>'.
 5657:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 5658:                   '<input type="radio" name="togglecatsplace"'.
 5659:                   $toggle_catsplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 5660:                   '<label><input type="radio" name="togglecatscomm"'.
 5661:                   $toggle_catsplace_place.' value="comm" />'.$level{'place'}.'</label></span></td>'.
 5662:                   '</tr><tr>'.
 5663:                   '<td>'.$title{'categorizeplace'}.'</td>'.
 5664:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 5665:                   '<label><input type="radio" name="categorizeplace"'.
 5666:                   $can_catplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 5667:                   '<label><input type="radio" name="categorizeplace"'.
 5668:                   $can_catplace_place.'value="place" />'.$level{'place'}.'</label></span></td>'.
 5669:                   '</tr>';
 5670:         $$rowtotal += 6;
 5671:     } else {
 5672:         my $css_class;
 5673:         my $itemcount = 1;
 5674:         my $cathash; 
 5675:         if (ref($settings) eq 'HASH') {
 5676:             $cathash = $settings->{'cats'};
 5677:         }
 5678:         if (ref($cathash) eq 'HASH') {
 5679:             my (@cats,@trails,%allitems,%idx,@jsarray);
 5680:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
 5681:                                                    \%allitems,\%idx,\@jsarray);
 5682:             my $maxdepth = scalar(@cats);
 5683:             my $colattrib = '';
 5684:             if ($maxdepth > 2) {
 5685:                 $colattrib = ' colspan="2" ';
 5686:             }
 5687:             my @path;
 5688:             if (@cats > 0) {
 5689:                 if (ref($cats[0]) eq 'ARRAY') {
 5690:                     my $numtop = @{$cats[0]};
 5691:                     my $maxnum = $numtop;
 5692:                     my %default_names = (
 5693:                           instcode    => &mt('Official courses'),
 5694:                           communities => &mt('Communities'),
 5695:                           placement   => &mt('Placement Tests'),
 5696:                     );
 5697: 
 5698:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
 5699:                         ($cathash->{'instcode::0'} eq '') ||
 5700:                         (!grep(/^communities$/,@{$cats[0]})) || 
 5701:                         ($cathash->{'communities::0'} eq '') ||
 5702:                         (!grep(/^placement$/,@{$cats[0]})) ||
 5703:                         ($cathash->{'placement::0'} eq '')) {
 5704:                         $maxnum ++;
 5705:                     }
 5706:                     my $lastidx;
 5707:                     for (my $i=0; $i<$numtop; $i++) {
 5708:                         my $parent = $cats[0][$i];
 5709:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5710:                         my $item = &escape($parent).'::0';
 5711:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
 5712:                         $lastidx = $idx{$item};
 5713:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5714:                                       .'<select name="'.$item.'"'.$chgstr.'>';
 5715:                         for (my $k=0; $k<=$maxnum; $k++) {
 5716:                             my $vpos = $k+1;
 5717:                             my $selstr;
 5718:                             if ($k == $i) {
 5719:                                 $selstr = ' selected="selected" ';
 5720:                             }
 5721:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5722:                         }
 5723:                         $datatable .= '</select></span></td><td>';
 5724:                         if ($parent eq 'instcode' || $parent eq 'communities' || $parent eq 'placement') {
 5725:                             $datatable .=  '<span class="LC_nobreak">'
 5726:                                            .$default_names{$parent}.'</span>';
 5727:                             if ($parent eq 'instcode') {
 5728:                                 $datatable .= '<br /><span class="LC_nobreak">('
 5729:                                               .&mt('with institutional codes')
 5730:                                               .')</span></td><td'.$colattrib.'>';
 5731:                             } else {
 5732:                                 $datatable .= '<table><tr><td>';
 5733:                             }
 5734:                             $datatable .= '<span class="LC_nobreak">'
 5735:                                           .'<label><input type="radio" name="'
 5736:                                           .$parent.'" value="1" checked="checked" />'
 5737:                                           .&mt('Display').'</label>';
 5738:                             if ($parent eq 'instcode') {
 5739:                                 $datatable .= '&nbsp;';
 5740:                             } else {
 5741:                                 $datatable .= '</span></td></tr><tr><td>'
 5742:                                               .'<span class="LC_nobreak">';
 5743:                             }
 5744:                             $datatable .= '<label><input type="radio" name="'
 5745:                                           .$parent.'" value="0" />'
 5746:                                           .&mt('Do not display').'</label></span>';
 5747:                             if (($parent eq 'communities') || ($parent eq 'placement')) {
 5748:                                 $datatable .= '</td></tr></table>';
 5749:                             }
 5750:                             $datatable .= '</td>';
 5751:                         } else {
 5752:                             $datatable .= $parent
 5753:                                           .'&nbsp;<span class="LC_nobreak"><label>'
 5754:                                           .'<input type="checkbox" name="deletecategory" '
 5755:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
 5756:                         }
 5757:                         my $depth = 1;
 5758:                         push(@path,$parent);
 5759:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
 5760:                         pop(@path);
 5761:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 5762:                         $itemcount ++;
 5763:                     }
 5764:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5765:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
 5766:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
 5767:                     for (my $k=0; $k<=$maxnum; $k++) {
 5768:                         my $vpos = $k+1;
 5769:                         my $selstr;
 5770:                         if ($k == $numtop) {
 5771:                             $selstr = ' selected="selected" ';
 5772:                         }
 5773:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5774:                     }
 5775:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
 5776:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
 5777:                                   .'</tr>'."\n";
 5778:                     $itemcount ++;
 5779:                     foreach my $default ('instcode','communities','placement') {
 5780:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
 5781:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5782:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
 5783:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
 5784:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
 5785:                             for (my $k=0; $k<=$maxnum; $k++) {
 5786:                                 my $vpos = $k+1;
 5787:                                 my $selstr;
 5788:                                 if ($k == $maxnum) {
 5789:                                     $selstr = ' selected="selected" ';
 5790:                                 }
 5791:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5792:                             }
 5793:                             $datatable .= '</select></span></td>'.
 5794:                                           '<td><span class="LC_nobreak">'.
 5795:                                           $default_names{$default}.'</span>';
 5796:                             if ($default eq 'instcode') {
 5797:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
 5798:                                               .&mt('with institutional codes').')</span>';
 5799:                             }
 5800:                             $datatable .= '</td>'
 5801:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
 5802:                                           .&mt('Display').'</label>&nbsp;'
 5803:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
 5804:                                           .&mt('Do not display').'</label></span></td></tr>';
 5805:                         }
 5806:                     }
 5807:                 }
 5808:             } else {
 5809:                 $datatable .= &initialize_categories($itemcount);
 5810:             }
 5811:         } else {
 5812:             $datatable .= '<td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td>'
 5813:                           .&initialize_categories($itemcount);
 5814:         }
 5815:         $$rowtotal += $itemcount;
 5816:     }
 5817:     return $datatable;
 5818: }
 5819: 
 5820: sub print_serverstatuses {
 5821:     my ($dom,$settings,$rowtotal) = @_;
 5822:     my $datatable;
 5823:     my @pages = &serverstatus_pages();
 5824:     my (%namedaccess,%machineaccess);
 5825:     foreach my $type (@pages) {
 5826:         $namedaccess{$type} = '';
 5827:         $machineaccess{$type}= '';
 5828:     }
 5829:     if (ref($settings) eq 'HASH') {
 5830:         foreach my $type (@pages) {
 5831:             if (exists($settings->{$type})) {
 5832:                 if (ref($settings->{$type}) eq 'HASH') {
 5833:                     foreach my $key (keys(%{$settings->{$type}})) {
 5834:                         if ($key eq 'namedusers') {
 5835:                             $namedaccess{$type} = $settings->{$type}->{$key};
 5836:                         } elsif ($key eq 'machines') {
 5837:                             $machineaccess{$type} = $settings->{$type}->{$key};
 5838:                         }
 5839:                     }
 5840:                 }
 5841:             }
 5842:         }
 5843:     }
 5844:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
 5845:     my $rownum = 0;
 5846:     my $css_class;
 5847:     foreach my $type (@pages) {
 5848:         $rownum ++;
 5849:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 5850:         $datatable .= '<tr'.$css_class.'>'.
 5851:                       '<td><span class="LC_nobreak">'.
 5852:                       $titles->{$type}.'</span></td>'.
 5853:                       '<td class="LC_left_item">'.
 5854:                       '<input type="text" name="'.$type.'_namedusers" '.
 5855:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
 5856:                       '<td class="LC_right_item">'.
 5857:                       '<span class="LC_nobreak">'.
 5858:                       '<input type="text" name="'.$type.'_machines" '.
 5859:                       'value="'.$machineaccess{$type}.'" size="10" />'.
 5860:                       '</td></tr>'."\n";
 5861:     }
 5862:     $$rowtotal += $rownum;
 5863:     return $datatable;
 5864: }
 5865: 
 5866: sub serverstatus_pages {
 5867:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
 5868:             'checksums','clusterstatus','metadata_keywords','metadata_harvest',
 5869:             'takeoffline','takeonline','showenv','toggledebug','ping','domconf',
 5870:             'uniquecodes','diskusage','coursecatalog');
 5871: }
 5872: 
 5873: sub defaults_javascript {
 5874:     my ($settings) = @_;
 5875:     return unless (ref($settings) eq 'HASH'); 
 5876:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 5877:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
 5878:         if ($maxnum eq '') {
 5879:             $maxnum = 0;
 5880:         }
 5881:         $maxnum ++;
 5882:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
 5883:         return <<"ENDSCRIPT";
 5884: <script type="text/javascript">
 5885: // <![CDATA[
 5886: function reorderTypes(form,caller) {
 5887:     var changedVal;
 5888: $jstext 
 5889:     var newpos = 'addinststatus_pos';
 5890:     var current = new Array;
 5891:     var maxh = $maxnum;
 5892:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 5893:     var oldVal;
 5894:     if (caller == newpos) {
 5895:         changedVal = newitemVal;
 5896:     } else {
 5897:         var curritem = 'inststatus_pos_'+caller;
 5898:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
 5899:         current[newitemVal] = newpos;
 5900:     }
 5901:     for (var i=0; i<inststatuses.length; i++) {
 5902:         if (inststatuses[i] != caller) {
 5903:             var elementName = 'inststatus_pos_'+inststatuses[i];
 5904:             if (form.elements[elementName]) {
 5905:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 5906:                 current[currVal] = elementName;
 5907:             }
 5908:         }
 5909:     }
 5910:     for (var j=0; j<maxh; j++) {
 5911:         if (current[j] == undefined) {
 5912:             oldVal = j;
 5913:         }
 5914:     }
 5915:     if (oldVal < changedVal) {
 5916:         for (var k=oldVal+1; k<=changedVal ; k++) {
 5917:            var elementName = current[k];
 5918:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 5919:         }
 5920:     } else {
 5921:         for (var k=changedVal; k<oldVal; k++) {
 5922:             var elementName = current[k];
 5923:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 5924:         }
 5925:     }
 5926:     return;
 5927: }
 5928: 
 5929: // ]]>
 5930: </script>
 5931: 
 5932: ENDSCRIPT
 5933:     }
 5934: }
 5935: 
 5936: sub coursecategories_javascript {
 5937:     my ($settings) = @_;
 5938:     my ($output,$jstext,$cathash);
 5939:     if (ref($settings) eq 'HASH') {
 5940:         $cathash = $settings->{'cats'};
 5941:     }
 5942:     if (ref($cathash) eq 'HASH') {
 5943:         my (@cats,@jsarray,%idx);
 5944:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
 5945:         if (@jsarray > 0) {
 5946:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
 5947:             for (my $i=0; $i<@jsarray; $i++) {
 5948:                 if (ref($jsarray[$i]) eq 'ARRAY') {
 5949:                     my $catstr = join('","',@{$jsarray[$i]});
 5950:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
 5951:                 }
 5952:             }
 5953:         }
 5954:     } else {
 5955:         $jstext  = '    var categories = Array(1);'."\n".
 5956:                    '    categories[0] = Array("instcode_pos");'."\n"; 
 5957:     }
 5958:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
 5959:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
 5960:     my $placement_reserved = &mt('The name: [_1] is a reserved category.','"placement"');
 5961:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
 5962:     &js_escape(\$instcode_reserved);
 5963:     &js_escape(\$communities_reserved);
 5964:     &js_escape(\$placement_reserved);
 5965:     &js_escape(\$choose_again);
 5966:     $output = <<"ENDSCRIPT";
 5967: <script type="text/javascript">
 5968: // <![CDATA[
 5969: function reorderCats(form,parent,item,idx) {
 5970:     var changedVal;
 5971: $jstext
 5972:     var newpos = 'addcategory_pos';
 5973:     if (parent == '') {
 5974:         var has_instcode = 0;
 5975:         var maxtop = categories[idx].length;
 5976:         for (var j=0; j<maxtop; j++) {
 5977:             if (categories[idx][j] == 'instcode::0') {
 5978:                 has_instcode == 1;
 5979:             }
 5980:         }
 5981:         if (has_instcode == 0) {
 5982:             categories[idx][maxtop] = 'instcode_pos';
 5983:         }
 5984:     } else {
 5985:         newpos += '_'+parent;
 5986:     }
 5987:     var maxh = 1 + categories[idx].length;
 5988:     var current = new Array;
 5989:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 5990:     if (item == newpos) {
 5991:         changedVal = newitemVal;
 5992:     } else {
 5993:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 5994:         current[newitemVal] = newpos;
 5995:     }
 5996:     for (var i=0; i<categories[idx].length; i++) {
 5997:         var elementName = categories[idx][i];
 5998:         if (elementName != item) {
 5999:             if (form.elements[elementName]) {
 6000:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 6001:                 current[currVal] = elementName;
 6002:             }
 6003:         }
 6004:     }
 6005:     var oldVal;
 6006:     for (var j=0; j<maxh; j++) {
 6007:         if (current[j] == undefined) {
 6008:             oldVal = j;
 6009:         }
 6010:     }
 6011:     if (oldVal < changedVal) {
 6012:         for (var k=oldVal+1; k<=changedVal ; k++) {
 6013:            var elementName = current[k];
 6014:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 6015:         }
 6016:     } else {
 6017:         for (var k=changedVal; k<oldVal; k++) {
 6018:             var elementName = current[k];
 6019:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 6020:         }
 6021:     }
 6022:     return;
 6023: }
 6024: 
 6025: function categoryCheck(form) {
 6026:     if (form.elements['addcategory_name'].value == 'instcode') {
 6027:         alert('$instcode_reserved\\n$choose_again');
 6028:         return false;
 6029:     }
 6030:     if (form.elements['addcategory_name'].value == 'communities') {
 6031:         alert('$communities_reserved\\n$choose_again');
 6032:         return false;
 6033:     }
 6034:     if (form.elements['addcategory_name'].value == 'placement') {
 6035:         alert('$placement_reserved\\n$choose_again');
 6036:         return false;
 6037:     }
 6038:     return true;
 6039: }
 6040: 
 6041: // ]]>
 6042: </script>
 6043: 
 6044: ENDSCRIPT
 6045:     return $output;
 6046: }
 6047: 
 6048: sub initialize_categories {
 6049:     my ($itemcount) = @_;
 6050:     my ($datatable,$css_class,$chgstr);
 6051:     my %default_names = (
 6052:                       instcode    => 'Official courses (with institutional codes)',
 6053:                       communities => 'Communities',
 6054:                       placement   => 'Placement Tests',
 6055:                         );
 6056:     my $select0 = ' selected="selected"';
 6057:     my $select1 = '';
 6058:     foreach my $default ('instcode','communities','placement') {
 6059:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6060:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'',$default"."_pos','0'".');"';
 6061:         if (($default eq 'communities') || ($default eq 'placement')) {
 6062:             $select1 = $select0;
 6063:             $select0 = '';
 6064:         }
 6065:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 6066:                      .'<select name="'.$default.'_pos">'
 6067:                      .'<option value="0"'.$select0.'>1</option>'
 6068:                      .'<option value="1"'.$select1.'>2</option>'
 6069:                      .'<option value="2">3</option></select>&nbsp;'
 6070:                      .$default_names{$default}
 6071:                      .'</span></td><td><span class="LC_nobreak">'
 6072:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
 6073:                      .&mt('Display').'</label>&nbsp;<label>'
 6074:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
 6075:                  .'</label></span></td></tr>';
 6076:         $itemcount ++;
 6077:     }
 6078:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6079:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
 6080:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 6081:                   .'<select name="addcategory_pos"'.$chgstr.'>'
 6082:                   .'<option value="0">1</option>'
 6083:                   .'<option value="1">2</option>'
 6084:                   .'<option value="2" selected="selected">3</option></select>&nbsp;'
 6085:                   .&mt('Add category').'</td><td>'.&mt('Name:')
 6086:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></td></tr>';
 6087:     return $datatable;
 6088: }
 6089: 
 6090: sub build_category_rows {
 6091:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
 6092:     my ($text,$name,$item,$chgstr);
 6093:     if (ref($cats) eq 'ARRAY') {
 6094:         my $maxdepth = scalar(@{$cats});
 6095:         if (ref($cats->[$depth]) eq 'HASH') {
 6096:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 6097:                 my $numchildren = @{$cats->[$depth]{$parent}};
 6098:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6099:                 $text .= '<td><table class="LC_data_table">';
 6100:                 my ($idxnum,$parent_name,$parent_item);
 6101:                 my $higher = $depth - 1;
 6102:                 if ($higher == 0) {
 6103:                     $parent_name = &escape($parent).'::'.$higher;
 6104:                 } else {
 6105:                     if (ref($path) eq 'ARRAY') {
 6106:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 6107:                     }
 6108:                 }
 6109:                 $parent_item = 'addcategory_pos_'.$parent_name;
 6110:                 for (my $j=0; $j<=$numchildren; $j++) {
 6111:                     if ($j < $numchildren) {
 6112:                         $name = $cats->[$depth]{$parent}[$j];
 6113:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
 6114:                         $idxnum = $idx->{$item};
 6115:                     } else {
 6116:                         $name = $parent_name;
 6117:                         $item = $parent_item;
 6118:                     }
 6119:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
 6120:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
 6121:                     for (my $i=0; $i<=$numchildren; $i++) {
 6122:                         my $vpos = $i+1;
 6123:                         my $selstr;
 6124:                         if ($j == $i) {
 6125:                             $selstr = ' selected="selected" ';
 6126:                         }
 6127:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
 6128:                     }
 6129:                     $text .= '</select>&nbsp;';
 6130:                     if ($j < $numchildren) {
 6131:                         my $deeper = $depth+1;
 6132:                         $text .= $name.'&nbsp;'
 6133:                                  .'<label><input type="checkbox" name="deletecategory" value="'
 6134:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
 6135:                         if(ref($path) eq 'ARRAY') {
 6136:                             push(@{$path},$name);
 6137:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
 6138:                             pop(@{$path});
 6139:                         }
 6140:                     } else {
 6141:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="textbox" size="20" name="addcategory_name_';
 6142:                         if ($j == $numchildren) {
 6143:                             $text .= $name;
 6144:                         } else {
 6145:                             $text .= $item;
 6146:                         }
 6147:                         $text .= '" value="" />';
 6148:                     }
 6149:                     $text .= '</td></tr>';
 6150:                 }
 6151:                 $text .= '</table></td>';
 6152:             } else {
 6153:                 my $higher = $depth-1;
 6154:                 if ($higher == 0) {
 6155:                     $name = &escape($parent).'::'.$higher;
 6156:                 } else {
 6157:                     if (ref($path) eq 'ARRAY') {
 6158:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 6159:                     }
 6160:                 }
 6161:                 my $colspan;
 6162:                 if ($parent ne 'instcode') {
 6163:                     $colspan = $maxdepth - $depth - 1;
 6164:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="textbox" size="20" name="subcat_'.$name.'" value="" /></td>';
 6165:                 }
 6166:             }
 6167:         }
 6168:     }
 6169:     return $text;
 6170: }
 6171: 
 6172: sub modifiable_userdata_row {
 6173:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref) = @_;
 6174:     my ($role,$rolename,$statustype);
 6175:     $role = $item;
 6176:     if ($context eq 'cancreate') {
 6177:         if ($item =~ /^emailusername_(.+)$/) {
 6178:             $statustype = $1;
 6179:             $role = 'emailusername';
 6180:             if (ref($usertypes) eq 'HASH') {
 6181:                 if ($usertypes->{$statustype}) {
 6182:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
 6183:                 } else {
 6184:                     $rolename = &mt('Data provided by user');
 6185:                 }
 6186:             }
 6187:         }
 6188:     } elsif ($context eq 'selfcreate') {
 6189:         if (ref($usertypes) eq 'HASH') {
 6190:             $rolename = $usertypes->{$role};
 6191:         } else {
 6192:             $rolename = $role;
 6193:         }
 6194:     } else {
 6195:         if ($role eq 'cr') {
 6196:             $rolename = &mt('Custom role');
 6197:         } else {
 6198:             $rolename = &Apache::lonnet::plaintext($role);
 6199:         }
 6200:     }
 6201:     my (@fields,%fieldtitles);
 6202:     if (ref($fieldsref) eq 'ARRAY') {
 6203:         @fields = @{$fieldsref};
 6204:     } else {
 6205:         @fields = ('lastname','firstname','middlename','generation',
 6206:                    'permanentemail','id');
 6207:     }
 6208:     if ((ref($titlesref) eq 'HASH')) {
 6209:         %fieldtitles = %{$titlesref};
 6210:     } else {
 6211:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 6212:     }
 6213:     my $output;
 6214:     my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 6215:     $output = '<tr '.$css_class.'>'.
 6216:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
 6217:               '<td class="LC_left_item" colspan="2"><table>';
 6218:     my $rem;
 6219:     my %checks;
 6220:     if (ref($settings) eq 'HASH') {
 6221:         if (ref($settings->{$context}) eq 'HASH') {
 6222:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
 6223:                 my $hashref = $settings->{$context}->{$role};
 6224:                 if ($role eq 'emailusername') {
 6225:                     if ($statustype) {
 6226:                         if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
 6227:                             $hashref = $settings->{$context}->{$role}->{$statustype};
 6228:                             if (ref($hashref) eq 'HASH') { 
 6229:                                 foreach my $field (@fields) {
 6230:                                     if ($hashref->{$field}) {
 6231:                                         $checks{$field} = $hashref->{$field};
 6232:                                     }
 6233:                                 }
 6234:                             }
 6235:                         }
 6236:                     }
 6237:                 } else {
 6238:                     if (ref($hashref) eq 'HASH') {
 6239:                         foreach my $field (@fields) {
 6240:                             if ($hashref->{$field}) {
 6241:                                 $checks{$field} = ' checked="checked" ';
 6242:                             }
 6243:                         }
 6244:                     }
 6245:                 }
 6246:             }
 6247:         }
 6248:     }
 6249:      
 6250:     for (my $i=0; $i<@fields; $i++) {
 6251:         my $rem = $i%($numinrow);
 6252:         if ($rem == 0) {
 6253:             if ($i > 0) {
 6254:                 $output .= '</tr>';
 6255:             }
 6256:             $output .= '<tr>';
 6257:         }
 6258:         my $check = ' ';
 6259:         unless ($role eq 'emailusername') {
 6260:             if (exists($checks{$fields[$i]})) {
 6261:                 $check = $checks{$fields[$i]}
 6262:             } else {
 6263:                 if ($role eq 'st') {
 6264:                     if (ref($settings) ne 'HASH') {
 6265:                         $check = ' checked="checked" '; 
 6266:                     }
 6267:                 }
 6268:             }
 6269:         }
 6270:         $output .= '<td class="LC_left_item">'.
 6271:                    '<span class="LC_nobreak">';
 6272:         if ($role eq 'emailusername') {
 6273:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
 6274:                 $checks{$fields[$i]} = 'omit';
 6275:             }
 6276:             foreach my $option ('required','optional','omit') {
 6277:                 my $checked='';
 6278:                 if ($checks{$fields[$i]} eq $option) {
 6279:                     $checked='checked="checked" ';
 6280:                 }
 6281:                 $output .= '<label>'.
 6282:                            '<input type="radio" name="canmodify_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
 6283:                            &mt($option).'</label>'.('&nbsp;' x2);
 6284:             }
 6285:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
 6286:         } else {
 6287:             $output .= '<label>'.
 6288:                        '<input type="checkbox" name="canmodify_'.$role.'" '.
 6289:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
 6290:                        '</label>';
 6291:         }
 6292:         $output .= '</span></td>';
 6293:         $rem = @fields%($numinrow);
 6294:     }
 6295:     my $colsleft = $numinrow - $rem;
 6296:     if ($colsleft > 1 ) {
 6297:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6298:                    '&nbsp;</td>';
 6299:     } elsif ($colsleft == 1) {
 6300:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 6301:     }
 6302:     $output .= '</tr></table></td></tr>';
 6303:     return $output;
 6304: }
 6305: 
 6306: sub insttypes_row {
 6307:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rownum) = @_;
 6308:     my %lt = &Apache::lonlocal::texthash (
 6309:                       cansearch => 'Users allowed to search',
 6310:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
 6311:                       lockablenames => 'User preference to lock name',
 6312:              );
 6313:     my $showdom;
 6314:     if ($context eq 'cansearch') {
 6315:         $showdom = ' ('.$dom.')';
 6316:     }
 6317:     my $class = 'LC_left_item';
 6318:     if ($context eq 'statustocreate') {
 6319:         $class = 'LC_right_item';
 6320:     }
 6321:     my $css_class = ' class="LC_odd_row"';
 6322:     if ($rownum ne '') { 
 6323:         $css_class = ($rownum%2? ' class="LC_odd_row"':'');
 6324:     }
 6325:     my $output = '<tr'.$css_class.'>'.
 6326:                  '<td>'.$lt{$context}.$showdom.
 6327:                  '</td><td class="'.$class.'" colspan="2"><table>';
 6328:     my $rem;
 6329:     if (ref($types) eq 'ARRAY') {
 6330:         for (my $i=0; $i<@{$types}; $i++) {
 6331:             if (defined($usertypes->{$types->[$i]})) {
 6332:                 my $rem = $i%($numinrow);
 6333:                 if ($rem == 0) {
 6334:                     if ($i > 0) {
 6335:                         $output .= '</tr>';
 6336:                     }
 6337:                     $output .= '<tr>';
 6338:                 }
 6339:                 my $check = ' ';
 6340:                 if (ref($settings) eq 'HASH') {
 6341:                     if (ref($settings->{$context}) eq 'ARRAY') {
 6342:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
 6343:                             $check = ' checked="checked" ';
 6344:                         }
 6345:                     } elsif ($context eq 'statustocreate') {
 6346:                         $check = ' checked="checked" ';
 6347:                     }
 6348:                 }
 6349:                 $output .= '<td class="LC_left_item">'.
 6350:                            '<span class="LC_nobreak"><label>'.
 6351:                            '<input type="checkbox" name="'.$context.'" '.
 6352:                            'value="'.$types->[$i].'"'.$check.'/>'.
 6353:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 6354:             }
 6355:         }
 6356:         $rem = @{$types}%($numinrow);
 6357:     }
 6358:     my $colsleft = $numinrow - $rem;
 6359:     if (($rem == 0) && (@{$types} > 0)) {
 6360:         $output .= '<tr>';
 6361:     }
 6362:     if ($colsleft > 1) {
 6363:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6364:     } else {
 6365:         $output .= '<td class="LC_left_item">';
 6366:     }
 6367:     my $defcheck = ' ';
 6368:     if (ref($settings) eq 'HASH') {  
 6369:         if (ref($settings->{$context}) eq 'ARRAY') {
 6370:             if (grep(/^default$/,@{$settings->{$context}})) {
 6371:                 $defcheck = ' checked="checked" ';
 6372:             }
 6373:         } elsif ($context eq 'statustocreate') {
 6374:             $defcheck = ' checked="checked" ';
 6375:         }
 6376:     }
 6377:     $output .= '<span class="LC_nobreak"><label>'.
 6378:                '<input type="checkbox" name="'.$context.'" '.
 6379:                'value="default"'.$defcheck.'/>'.
 6380:                $othertitle.'</label></span></td>'.
 6381:                '</tr></table></td></tr>';
 6382:     return $output;
 6383: }
 6384: 
 6385: sub sorted_searchtitles {
 6386:     my %searchtitles = &Apache::lonlocal::texthash(
 6387:                          'uname' => 'username',
 6388:                          'lastname' => 'last name',
 6389:                          'lastfirst' => 'last name, first name',
 6390:                      );
 6391:     my @titleorder = ('uname','lastname','lastfirst');
 6392:     return (\%searchtitles,\@titleorder);
 6393: }
 6394: 
 6395: sub sorted_searchtypes {
 6396:     my %srchtypes_desc = (
 6397:                            exact    => 'is exact match',
 6398:                            contains => 'contains ..',
 6399:                            begins   => 'begins with ..',
 6400:                          );
 6401:     my @srchtypeorder = ('exact','begins','contains');
 6402:     return (\%srchtypes_desc,\@srchtypeorder);
 6403: }
 6404: 
 6405: sub usertype_update_row {
 6406:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
 6407:     my $datatable;
 6408:     my $numinrow = 4;
 6409:     foreach my $type (@{$types}) {
 6410:         if (defined($usertypes->{$type})) {
 6411:             $$rownums ++;
 6412:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
 6413:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
 6414:                           '</td><td class="LC_left_item"><table>';
 6415:             for (my $i=0; $i<@{$fields}; $i++) {
 6416:                 my $rem = $i%($numinrow);
 6417:                 if ($rem == 0) {
 6418:                     if ($i > 0) {
 6419:                         $datatable .= '</tr>';
 6420:                     }
 6421:                     $datatable .= '<tr>';
 6422:                 }
 6423:                 my $check = ' ';
 6424:                 if (ref($settings) eq 'HASH') {
 6425:                     if (ref($settings->{'fields'}) eq 'HASH') {
 6426:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
 6427:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
 6428:                                 $check = ' checked="checked" ';
 6429:                             }
 6430:                         }
 6431:                     }
 6432:                 }
 6433: 
 6434:                 if ($i == @{$fields}-1) {
 6435:                     my $colsleft = $numinrow - $rem;
 6436:                     if ($colsleft > 1) {
 6437:                         $datatable .= '<td colspan="'.$colsleft.'">';
 6438:                     } else {
 6439:                         $datatable .= '<td>';
 6440:                     }
 6441:                 } else {
 6442:                     $datatable .= '<td>';
 6443:                 }
 6444:                 $datatable .= '<span class="LC_nobreak"><label>'.
 6445:                               '<input type="checkbox" name="updateable_'.$type.
 6446:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
 6447:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
 6448:             }
 6449:             $datatable .= '</tr></table></td></tr>';
 6450:         }
 6451:     }
 6452:     return $datatable;
 6453: }
 6454: 
 6455: sub modify_login {
 6456:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
 6457:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
 6458:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon);
 6459:     %title = ( coursecatalog => 'Display course catalog',
 6460:                adminmail => 'Display administrator E-mail address',
 6461:                helpdesk  => 'Display "Contact Helpdesk" link',
 6462:                newuser => 'Link for visitors to create a user account',
 6463:                loginheader => 'Log-in box header');
 6464:     @offon = ('off','on');
 6465:     if (ref($domconfig{login}) eq 'HASH') {
 6466:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
 6467:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
 6468:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
 6469:             }
 6470:         }
 6471:     }
 6472:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
 6473:                                            \%domconfig,\%loginhash);
 6474:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 6475:     foreach my $item (@toggles) {
 6476:         $loginhash{login}{$item} = $env{'form.'.$item};
 6477:     }
 6478:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
 6479:     if (ref($colchanges{'login'}) eq 'HASH') {  
 6480:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
 6481:                                          \%loginhash);
 6482:     }
 6483: 
 6484:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 6485:     my %domservers = &Apache::lonnet::get_servers($dom);
 6486:     my @loginvia_attribs = ('serverpath','custompath','exempt');
 6487:     if (keys(%servers) > 1) {
 6488:         foreach my $lonhost (keys(%servers)) {
 6489:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
 6490:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
 6491:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
 6492:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
 6493:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
 6494:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 6495:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 6496:                         $changes{'loginvia'}{$lonhost} = 1;
 6497:                     } else {
 6498:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
 6499:                         $changes{'loginvia'}{$lonhost} = 1;
 6500:                     }
 6501:                 } else {
 6502:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 6503:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 6504:                         $changes{'loginvia'}{$lonhost} = 1;
 6505:                     }
 6506:                 }
 6507:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
 6508:                     foreach my $item (@loginvia_attribs) {
 6509:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
 6510:                     }
 6511:                 } else {
 6512:                     foreach my $item (@loginvia_attribs) {
 6513:                         my $new = $env{'form.'.$lonhost.'_'.$item};
 6514:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
 6515:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
 6516:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
 6517:                                 $new = '/';
 6518:                             }
 6519:                         }
 6520:                         if (($item eq 'custompath') && 
 6521:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
 6522:                             $new = '';
 6523:                         }
 6524:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
 6525:                             $changes{'loginvia'}{$lonhost} = 1;
 6526:                         }
 6527:                         if ($item eq 'exempt') {
 6528:                             $new = &check_exempt_addresses($new);
 6529:                         }
 6530:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
 6531:                     }
 6532:                 }
 6533:             } else {
 6534:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 6535:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 6536:                     $changes{'loginvia'}{$lonhost} = 1;
 6537:                     foreach my $item (@loginvia_attribs) {
 6538:                         my $new = $env{'form.'.$lonhost.'_'.$item};
 6539:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
 6540:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
 6541:                                 $new = '/';
 6542:                             }
 6543:                         }
 6544:                         if (($item eq 'custompath') && 
 6545:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
 6546:                             $new = '';
 6547:                         }
 6548:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
 6549:                     }
 6550:                 }
 6551:             }
 6552:         }
 6553:     }
 6554: 
 6555:     my $servadm = $r->dir_config('lonAdmEMail');
 6556:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 6557:     if (ref($domconfig{'login'}) eq 'HASH') {
 6558:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
 6559:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
 6560:                 if ($lang eq 'nolang') {
 6561:                     push(@currlangs,$lang);
 6562:                 } elsif (defined($langchoices{$lang})) {
 6563:                     push(@currlangs,$lang);
 6564:                 } else {
 6565:                     next;
 6566:                 }
 6567:             }
 6568:         }
 6569:     }
 6570:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
 6571:     if (@currlangs > 0) {
 6572:         foreach my $lang (@currlangs) {
 6573:             if (grep(/^\Q$lang\E$/,@delurls)) {
 6574:                 $changes{'helpurl'}{$lang} = 1;
 6575:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
 6576:                 $changes{'helpurl'}{$lang} = 1;
 6577:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
 6578:                 push(@newlangs,$lang);
 6579:             } else {
 6580:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
 6581:             }
 6582:         }
 6583:     }
 6584:     unless (grep(/^nolang$/,@currlangs)) {
 6585:         if ($env{'form.loginhelpurl_nolang.filename'}) {
 6586:             $changes{'helpurl'}{'nolang'} = 1;
 6587:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
 6588:             push(@newlangs,'nolang');
 6589:         }
 6590:     }
 6591:     if ($env{'form.loginhelpurl_add_lang'}) {
 6592:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
 6593:             ($env{'form.loginhelpurl_add_file.filename'})) {
 6594:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
 6595:             $addedfile = $env{'form.loginhelpurl_add_lang'};
 6596:         }
 6597:     }
 6598:     if ((@newlangs > 0) || ($addedfile)) {
 6599:         my $error;
 6600:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 6601:         if ($configuserok eq 'ok') {
 6602:             if ($switchserver) {
 6603:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
 6604:             } elsif ($author_ok eq 'ok') {
 6605:                 my @allnew = @newlangs;
 6606:                 if ($addedfile ne '') {
 6607:                     push(@allnew,$addedfile);
 6608:                 }
 6609:                 foreach my $lang (@allnew) {
 6610:                     my $formelem = 'loginhelpurl_'.$lang;
 6611:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
 6612:                         $formelem = 'loginhelpurl_add_file';
 6613:                     }
 6614:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 6615:                                                                "help/$lang",'','',$newfile{$lang});
 6616:                     if ($result eq 'ok') {
 6617:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
 6618:                         $changes{'helpurl'}{$lang} = 1;
 6619:                     } else {
 6620:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
 6621:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 6622:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
 6623:                             (!grep(/^\Q$lang\E$/,@delurls))) {
 6624:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
 6625:                         }
 6626:                     }
 6627:                 }
 6628:             } else {
 6629:                 $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);
 6630:             }
 6631:         } else {
 6632:             $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);
 6633:         }
 6634:         if ($error) {
 6635:             &Apache::lonnet::logthis($error);
 6636:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 6637:         }
 6638:     }
 6639: 
 6640:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
 6641:     if (ref($domconfig{'login'}) eq 'HASH') {
 6642:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
 6643:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
 6644:                 if ($domservers{$lonhost}) {
 6645:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
 6646:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
 6647:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
 6648:                     }
 6649:                 }
 6650:             }
 6651:         }
 6652:     }
 6653:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
 6654:     foreach my $lonhost (sort(keys(%domservers))) {
 6655:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
 6656:             $changes{'headtag'}{$lonhost} = 1;
 6657:         } else {
 6658:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
 6659:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
 6660:             }
 6661:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
 6662:                 push(@newhosts,$lonhost);
 6663:             } elsif ($currheadtagurls{$lonhost}) {
 6664:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
 6665:                 if ($currexempt{$lonhost}) {
 6666:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) { 
 6667:                         $changes{'headtag'}{$lonhost} = 1;
 6668:                     }
 6669:                 } elsif ($possexempt{$lonhost}) {
 6670:                     $changes{'headtag'}{$lonhost} = 1;
 6671:                 }
 6672:                 if ($possexempt{$lonhost}) {
 6673:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
 6674:                 }
 6675:             }
 6676:         }
 6677:     }
 6678:     if (@newhosts) {
 6679:         my $error;
 6680:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 6681:         if ($configuserok eq 'ok') {
 6682:             if ($switchserver) {
 6683:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
 6684:             } elsif ($author_ok eq 'ok') {
 6685:                 foreach my $lonhost (@newhosts) {
 6686:                     my $formelem = 'loginheadtag_'.$lonhost;
 6687:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 6688:                                                                           "login/headtag/$lonhost",'','',
 6689:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
 6690:                     if ($result eq 'ok') {
 6691:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
 6692:                         $changes{'headtag'}{$lonhost} = 1;
 6693:                         if ($possexempt{$lonhost}) {
 6694:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
 6695:                         }
 6696:                     } else {
 6697:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
 6698:                                            $newheadtagurls{$lonhost},$result);
 6699:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 6700:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
 6701:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
 6702:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
 6703:                         }
 6704:                     }
 6705:                 }
 6706:             } else {
 6707:                 $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);
 6708:             }
 6709:         } else {
 6710:             $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);
 6711:         }
 6712:         if ($error) {
 6713:             &Apache::lonnet::logthis($error);
 6714:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 6715:         }
 6716:     }
 6717:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
 6718: 
 6719:     my $defaulthelpfile = '/adm/loginproblems.html';
 6720:     my $defaulttext = &mt('Default in use');
 6721: 
 6722:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
 6723:                                              $dom);
 6724:     if ($putresult eq 'ok') {
 6725:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 6726:         my %defaultchecked = (
 6727:                     'coursecatalog' => 'on',
 6728:                     'helpdesk'      => 'on',
 6729:                     'adminmail'     => 'off',
 6730:                     'newuser'       => 'off',
 6731:         );
 6732:         if (ref($domconfig{'login'}) eq 'HASH') {
 6733:             foreach my $item (@toggles) {
 6734:                 if ($defaultchecked{$item} eq 'on') { 
 6735:                     if (($domconfig{'login'}{$item} eq '0') &&
 6736:                         ($env{'form.'.$item} eq '1')) {
 6737:                         $changes{$item} = 1;
 6738:                     } elsif (($domconfig{'login'}{$item} eq '' ||
 6739:                               $domconfig{'login'}{$item} eq '1') &&
 6740:                              ($env{'form.'.$item} eq '0')) {
 6741:                         $changes{$item} = 1;
 6742:                     }
 6743:                 } elsif ($defaultchecked{$item} eq 'off') {
 6744:                     if (($domconfig{'login'}{$item} eq '1') &&
 6745:                         ($env{'form.'.$item} eq '0')) {
 6746:                         $changes{$item} = 1;
 6747:                     } elsif (($domconfig{'login'}{$item} eq '' ||
 6748:                               $domconfig{'login'}{$item} eq '0') &&
 6749:                              ($env{'form.'.$item} eq '1')) {
 6750:                         $changes{$item} = 1;
 6751:                     }
 6752:                 }
 6753:             }
 6754:         }
 6755:         if (keys(%changes) > 0 || $colchgtext) {
 6756:             &Apache::loncommon::devalidate_domconfig_cache($dom);
 6757:             if (ref($lastactref) eq 'HASH') {
 6758:                 $lastactref->{'domainconfig'} = 1;
 6759:             }
 6760:             $resulttext = &mt('Changes made:').'<ul>';
 6761:             foreach my $item (sort(keys(%changes))) {
 6762:                 if ($item eq 'loginvia') {
 6763:                     if (ref($changes{$item}) eq 'HASH') {
 6764:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
 6765:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
 6766:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
 6767:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
 6768:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
 6769:                                     $protocol = 'http' if ($protocol ne 'https');
 6770:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
 6771: 
 6772:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
 6773:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
 6774:                                     } else {
 6775:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
 6776:                                     }
 6777:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
 6778:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
 6779:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
 6780:                                     }
 6781:                                     $resulttext .= '</li>';
 6782:                                 } else {
 6783:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
 6784:                                 }
 6785:                             } else {
 6786:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
 6787:                             }
 6788:                         }
 6789:                         $resulttext .= '</ul></li>';
 6790:                     }
 6791:                 } elsif ($item eq 'helpurl') {
 6792:                     if (ref($changes{$item}) eq 'HASH') {
 6793:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
 6794:                             if (grep(/^\Q$lang\E$/,@delurls)) {
 6795:                                 my ($chg,$link);
 6796:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
 6797:                                 if ($lang eq 'nolang') {
 6798:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
 6799:                                 } else {
 6800:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
 6801:                                 }
 6802:                                 $resulttext .= '<li>'.$chg.'</li>';
 6803:                             } else {
 6804:                                 my $chg;
 6805:                                 if ($lang eq 'nolang') {
 6806:                                     $chg = &mt('custom log-in help file for no preferred language');
 6807:                                 } else {
 6808:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
 6809:                                 }
 6810:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
 6811:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
 6812:                                                       '?inhibitmenu=yes',$chg,600,500).
 6813:                                                '</li>';
 6814:                             }
 6815:                         }
 6816:                     }
 6817:                 } elsif ($item eq 'headtag') {
 6818:                     if (ref($changes{$item}) eq 'HASH') {
 6819:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
 6820:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
 6821:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
 6822:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
 6823:                                 $resulttext .= '<li><a href="'.
 6824:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
 6825:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 6826:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
 6827:                                 if ($possexempt{$lonhost}) {
 6828:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
 6829:                                 } else {
 6830:                                     $resulttext .= &mt('included for any client IP');
 6831:                                 }
 6832:                                 $resulttext .= '</li>';
 6833:                             }
 6834:                         }
 6835:                     }
 6836:                 } elsif ($item eq 'captcha') {
 6837:                     if (ref($loginhash{'login'}) eq 'HASH') {
 6838:                         my $chgtxt;
 6839:                         if ($loginhash{'login'}{$item} eq 'notused') {
 6840:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
 6841:                         } else {
 6842:                             my %captchas = &captcha_phrases();
 6843:                             if ($captchas{$loginhash{'login'}{$item}}) {
 6844:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
 6845:                             } else {
 6846:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
 6847:                             }
 6848:                         }
 6849:                         $resulttext .= '<li>'.$chgtxt.'</li>';
 6850:                     }
 6851:                 } elsif ($item eq 'recaptchakeys') {
 6852:                     if (ref($loginhash{'login'}) eq 'HASH') {
 6853:                         my ($privkey,$pubkey);
 6854:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
 6855:                             $pubkey = $loginhash{'login'}{$item}{'public'};
 6856:                             $privkey = $loginhash{'login'}{$item}{'private'};
 6857:                         }
 6858:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
 6859:                         if (!$pubkey) {
 6860:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
 6861:                         } else {
 6862:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
 6863:                         }
 6864:                         if (!$privkey) {
 6865:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
 6866:                         } else {
 6867:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
 6868:                         }
 6869:                         $chgtxt .= '</ul>';
 6870:                         $resulttext .= '<li>'.$chgtxt.'</li>';
 6871:                     }
 6872:                 } elsif ($item eq 'recaptchaversion') {
 6873:                     if (ref($loginhash{'login'}) eq 'HASH') {
 6874:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
 6875:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
 6876:                                            '</li>';
 6877:                         }
 6878:                     }
 6879:                 } else {
 6880:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
 6881:                 }
 6882:             }
 6883:             $resulttext .= $colchgtext.'</ul>';
 6884:         } else {
 6885:             $resulttext = &mt('No changes made to log-in page settings');
 6886:         }
 6887:     } else {
 6888:         $resulttext = '<span class="LC_error">'.
 6889: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 6890:     }
 6891:     if ($errors) {
 6892:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
 6893:                        $errors.'</ul>';
 6894:     }
 6895:     return $resulttext;
 6896: }
 6897: 
 6898: 
 6899: sub check_exempt_addresses {
 6900:     my ($iplist) = @_;
 6901:     $iplist =~ s/^\s+//;
 6902:     $iplist =~ s/\s+$//;
 6903:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
 6904:     my (@okips,$new);
 6905:     foreach my $ip (@poss_ips) {
 6906:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
 6907:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
 6908:                 push(@okips,$ip);
 6909:             }
 6910:         }
 6911:     }
 6912:     if (@okips > 0) {
 6913:         $new = join(',',@okips);
 6914:     } else {
 6915:         $new = '';
 6916:     }
 6917:     return $new;
 6918: }
 6919: 
 6920: sub color_font_choices {
 6921:     my %choices =
 6922:         &Apache::lonlocal::texthash (
 6923:             img => "Header",
 6924:             bgs => "Background colors",
 6925:             links => "Link colors",
 6926:             images => "Images",
 6927:             font => "Font color",
 6928:             fontmenu => "Font menu",
 6929:             pgbg => "Page",
 6930:             tabbg => "Header",
 6931:             sidebg => "Border",
 6932:             link => "Link",
 6933:             alink => "Active link",
 6934:             vlink => "Visited link",
 6935:         );
 6936:     return %choices;
 6937: }
 6938: 
 6939: sub modify_rolecolors {
 6940:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
 6941:     my ($resulttext,%rolehash);
 6942:     $rolehash{'rolecolors'} = {};
 6943:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
 6944:         if ($domconfig{'rolecolors'} eq '') {
 6945:             $domconfig{'rolecolors'} = {};
 6946:         }
 6947:     }
 6948:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
 6949:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
 6950:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
 6951:                                              $dom);
 6952:     if ($putresult eq 'ok') {
 6953:         if (keys(%changes) > 0) {
 6954:             &Apache::loncommon::devalidate_domconfig_cache($dom);
 6955:             if (ref($lastactref) eq 'HASH') {
 6956:                 $lastactref->{'domainconfig'} = 1;
 6957:             }
 6958:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
 6959:                                              $rolehash{'rolecolors'});
 6960:         } else {
 6961:             $resulttext = &mt('No changes made to default color schemes');
 6962:         }
 6963:     } else {
 6964:         $resulttext = '<span class="LC_error">'.
 6965: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 6966:     }
 6967:     if ($errors) {
 6968:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
 6969:                        $errors.'</ul>';
 6970:     }
 6971:     return $resulttext;
 6972: }
 6973: 
 6974: sub modify_colors {
 6975:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
 6976:     my (%changes,%choices);
 6977:     my @bgs;
 6978:     my @links = ('link','alink','vlink');
 6979:     my @logintext;
 6980:     my @images;
 6981:     my $servadm = $r->dir_config('lonAdmEMail');
 6982:     my $errors;
 6983:     my %defaults;
 6984:     foreach my $role (@{$roles}) {
 6985:         if ($role eq 'login') {
 6986:             %choices = &login_choices();
 6987:             @logintext = ('textcol','bgcol');
 6988:         } else {
 6989:             %choices = &color_font_choices();
 6990:         }
 6991:         if ($role eq 'login') {
 6992:             @images = ('img','logo','domlogo','login');
 6993:             @bgs = ('pgbg','mainbg','sidebg');
 6994:         } else {
 6995:             @images = ('img');
 6996:             @bgs = ('pgbg','tabbg','sidebg');
 6997:         }
 6998:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
 6999:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
 7000:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
 7001:         }
 7002:         if ($role eq 'login') {
 7003:             foreach my $item (@logintext) {
 7004:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
 7005:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
 7006:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
 7007:                 }
 7008:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
 7009:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
 7010:                 }
 7011:             }
 7012:         } else {
 7013:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
 7014:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
 7015:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
 7016:             }
 7017:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
 7018:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
 7019:             }
 7020:         }
 7021:         foreach my $item (@bgs) {
 7022:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
 7023:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
 7024:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
 7025:             }
 7026:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
 7027:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
 7028:             }
 7029:         }
 7030:         foreach my $item (@links) {
 7031:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
 7032:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
 7033:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
 7034:             }
 7035:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
 7036:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
 7037:             }
 7038:         }
 7039:         my ($configuserok,$author_ok,$switchserver) = 
 7040:             &config_check($dom,$confname,$servadm);
 7041:         my ($width,$height) = &thumb_dimensions();
 7042:         if (ref($domconfig->{$role}) ne 'HASH') {
 7043:             $domconfig->{$role} = {};
 7044:         }
 7045:         foreach my $img (@images) {
 7046:             if (($role eq 'login') && (($img eq 'img') || ($img eq 'logo'))) {  
 7047:                 if (defined($env{'form.login_showlogo_'.$img})) {
 7048:                     $confhash->{$role}{'showlogo'}{$img} = 1;
 7049:                 } else { 
 7050:                     $confhash->{$role}{'showlogo'}{$img} = 0;
 7051:                 }
 7052:             } 
 7053: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
 7054: 		 && !defined($domconfig->{$role}{$img})
 7055: 		 && !$env{'form.'.$role.'_del_'.$img}
 7056: 		 && $env{'form.'.$role.'_import_'.$img}) {
 7057: 		# import the old configured image from the .tab setting
 7058: 		# if they haven't provided a new one 
 7059: 		$domconfig->{$role}{$img} = 
 7060: 		    $env{'form.'.$role.'_import_'.$img};
 7061: 	    }
 7062:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
 7063:                 my $error;
 7064:                 if ($configuserok eq 'ok') {
 7065:                     if ($switchserver) {
 7066:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
 7067:                     } else {
 7068:                         if ($author_ok eq 'ok') {
 7069:                             my ($result,$logourl) = 
 7070:                                 &publishlogo($r,'upload',$role.'_'.$img,
 7071:                                            $dom,$confname,$img,$width,$height);
 7072:                             if ($result eq 'ok') {
 7073:                                 $confhash->{$role}{$img} = $logourl;
 7074:                                 $changes{$role}{'images'}{$img} = 1;
 7075:                             } else {
 7076:                                 $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);
 7077:                             }
 7078:                         } else {
 7079:                             $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);
 7080:                         }
 7081:                     }
 7082:                 } else {
 7083:                     $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);
 7084:                 }
 7085:                 if ($error) {
 7086:                     &Apache::lonnet::logthis($error);
 7087:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 7088:                 }
 7089:             } elsif ($domconfig->{$role}{$img} ne '') {
 7090:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 7091:                     my $error;
 7092:                     if ($configuserok eq 'ok') {
 7093: # is confname an author?
 7094:                         if ($switchserver eq '') {
 7095:                             if ($author_ok eq 'ok') {
 7096:                                 my ($result,$logourl) = 
 7097:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
 7098:                                             $dom,$confname,$img,$width,$height);
 7099:                                 if ($result eq 'ok') {
 7100:                                     $confhash->{$role}{$img} = $logourl;
 7101: 				    $changes{$role}{'images'}{$img} = 1;
 7102:                                 }
 7103:                             }
 7104:                         }
 7105:                     }
 7106:                 }
 7107:             }
 7108:         }
 7109:         if (ref($domconfig) eq 'HASH') {
 7110:             if (ref($domconfig->{$role}) eq 'HASH') {
 7111:                 foreach my $img (@images) {
 7112:                     if ($domconfig->{$role}{$img} ne '') {
 7113:                         if ($env{'form.'.$role.'_del_'.$img}) {
 7114:                             $confhash->{$role}{$img} = '';
 7115:                             $changes{$role}{'images'}{$img} = 1;
 7116:                         } else {
 7117:                             if ($confhash->{$role}{$img} eq '') {
 7118:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
 7119:                             }
 7120:                         }
 7121:                     } else {
 7122:                         if ($env{'form.'.$role.'_del_'.$img}) {
 7123:                             $confhash->{$role}{$img} = '';
 7124:                             $changes{$role}{'images'}{$img} = 1;
 7125:                         } 
 7126:                     }
 7127:                     if (($role eq 'login') && (($img eq 'logo') || ($img eq 'img'))) {
 7128:                         if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
 7129:                             if ($confhash->{$role}{'showlogo'}{$img} ne 
 7130:                                 $domconfig->{$role}{'showlogo'}{$img}) {
 7131:                                 $changes{$role}{'showlogo'}{$img} = 1; 
 7132:                             }
 7133:                         } else {
 7134:                             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
 7135:                                 $changes{$role}{'showlogo'}{$img} = 1;
 7136:                             }
 7137:                         }
 7138:                     }
 7139:                 }
 7140:                 if ($domconfig->{$role}{'font'} ne '') {
 7141:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
 7142:                         $changes{$role}{'font'} = 1;
 7143:                     }
 7144:                 } else {
 7145:                     if ($confhash->{$role}{'font'}) {
 7146:                         $changes{$role}{'font'} = 1;
 7147:                     }
 7148:                 }
 7149:                 if ($role ne 'login') {
 7150:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
 7151:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
 7152:                             $changes{$role}{'fontmenu'} = 1;
 7153:                         }
 7154:                     } else {
 7155:                         if ($confhash->{$role}{'fontmenu'}) {
 7156:                             $changes{$role}{'fontmenu'} = 1;
 7157:                         }
 7158:                     }
 7159:                 }
 7160:                 foreach my $item (@bgs) {
 7161:                     if ($domconfig->{$role}{$item} ne '') {
 7162:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
 7163:                             $changes{$role}{'bgs'}{$item} = 1;
 7164:                         } 
 7165:                     } else {
 7166:                         if ($confhash->{$role}{$item}) {
 7167:                             $changes{$role}{'bgs'}{$item} = 1;
 7168:                         }
 7169:                     }
 7170:                 }
 7171:                 foreach my $item (@links) {
 7172:                     if ($domconfig->{$role}{$item} ne '') {
 7173:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
 7174:                             $changes{$role}{'links'}{$item} = 1;
 7175:                         }
 7176:                     } else {
 7177:                         if ($confhash->{$role}{$item}) {
 7178:                             $changes{$role}{'links'}{$item} = 1;
 7179:                         }
 7180:                     }
 7181:                 }
 7182:                 foreach my $item (@logintext) {
 7183:                     if ($domconfig->{$role}{$item} ne '') {
 7184:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
 7185:                             $changes{$role}{'logintext'}{$item} = 1;
 7186:                         }
 7187:                     } else {
 7188:                         if ($confhash->{$role}{$item}) {
 7189:                             $changes{$role}{'logintext'}{$item} = 1;
 7190:                         }
 7191:                     }
 7192:                 }
 7193:             } else {
 7194:                 &default_change_checker($role,\@images,\@links,\@bgs,
 7195:                                         \@logintext,$confhash,\%changes); 
 7196:             }
 7197:         } else {
 7198:             &default_change_checker($role,\@images,\@links,\@bgs,
 7199:                                     \@logintext,$confhash,\%changes); 
 7200:         }
 7201:     }
 7202:     return ($errors,%changes);
 7203: }
 7204: 
 7205: sub config_check {
 7206:     my ($dom,$confname,$servadm) = @_;
 7207:     my ($configuserok,$author_ok,$switchserver,%currroles);
 7208:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
 7209:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
 7210:                                                    $confname,$servadm);
 7211:     if ($configuserok eq 'ok') {
 7212:         $switchserver = &check_switchserver($dom,$confname);
 7213:         if ($switchserver eq '') {
 7214:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
 7215:         }
 7216:     }
 7217:     return ($configuserok,$author_ok,$switchserver);
 7218: }
 7219: 
 7220: sub default_change_checker {
 7221:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
 7222:     foreach my $item (@{$links}) {
 7223:         if ($confhash->{$role}{$item}) {
 7224:             $changes->{$role}{'links'}{$item} = 1;
 7225:         }
 7226:     }
 7227:     foreach my $item (@{$bgs}) {
 7228:         if ($confhash->{$role}{$item}) {
 7229:             $changes->{$role}{'bgs'}{$item} = 1;
 7230:         }
 7231:     }
 7232:     foreach my $item (@{$logintext}) {
 7233:         if ($confhash->{$role}{$item}) {
 7234:             $changes->{$role}{'logintext'}{$item} = 1;
 7235:         }
 7236:     }
 7237:     foreach my $img (@{$images}) {
 7238:         if ($env{'form.'.$role.'_del_'.$img}) {
 7239:             $confhash->{$role}{$img} = '';
 7240:             $changes->{$role}{'images'}{$img} = 1;
 7241:         }
 7242:         if ($role eq 'login') {
 7243:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
 7244:                 $changes->{$role}{'showlogo'}{$img} = 1;
 7245:             }
 7246:         }
 7247:     }
 7248:     if ($confhash->{$role}{'font'}) {
 7249:         $changes->{$role}{'font'} = 1;
 7250:     }
 7251: }
 7252: 
 7253: sub display_colorchgs {
 7254:     my ($dom,$changes,$roles,$confhash) = @_;
 7255:     my (%choices,$resulttext);
 7256:     if (!grep(/^login$/,@{$roles})) {
 7257:         $resulttext = &mt('Changes made:').'<br />';
 7258:     }
 7259:     foreach my $role (@{$roles}) {
 7260:         if ($role eq 'login') {
 7261:             %choices = &login_choices();
 7262:         } else {
 7263:             %choices = &color_font_choices();
 7264:         }
 7265:         if (ref($changes->{$role}) eq 'HASH') {
 7266:             if ($role ne 'login') {
 7267:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
 7268:             }
 7269:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
 7270:                 if ($role ne 'login') {
 7271:                     $resulttext .= '<ul>';
 7272:                 }
 7273:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
 7274:                     if ($role ne 'login') {
 7275:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
 7276:                     }
 7277:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
 7278:                         if (($role eq 'login') && ($key eq 'showlogo')) {
 7279:                             if ($confhash->{$role}{$key}{$item}) {
 7280:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
 7281:                             } else {
 7282:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
 7283:                             }
 7284:                         } elsif ($confhash->{$role}{$item} eq '') {
 7285:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
 7286:                         } else {
 7287:                             my $newitem = $confhash->{$role}{$item};
 7288:                             if ($key eq 'images') {
 7289:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" valign="bottom" />';
 7290:                             }
 7291:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
 7292:                         }
 7293:                     }
 7294:                     if ($role ne 'login') {
 7295:                         $resulttext .= '</ul></li>';
 7296:                     }
 7297:                 } else {
 7298:                     if ($confhash->{$role}{$key} eq '') {
 7299:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
 7300:                     } else {
 7301:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
 7302:                     }
 7303:                 }
 7304:                 if ($role ne 'login') {
 7305:                     $resulttext .= '</ul>';
 7306:                 }
 7307:             }
 7308:         }
 7309:     }
 7310:     return $resulttext;
 7311: }
 7312: 
 7313: sub thumb_dimensions {
 7314:     return ('200','50');
 7315: }
 7316: 
 7317: sub check_dimensions {
 7318:     my ($inputfile) = @_;
 7319:     my ($fullwidth,$fullheight);
 7320:     if ($inputfile =~ m|^[/\w.\-]+$|) {
 7321:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
 7322:             my $imageinfo = <PIPE>;
 7323:             if (!close(PIPE)) {
 7324:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
 7325:             }
 7326:             chomp($imageinfo);
 7327:             my ($fullsize) = 
 7328:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
 7329:             if ($fullsize) {
 7330:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
 7331:             }
 7332:         }
 7333:     }
 7334:     return ($fullwidth,$fullheight);
 7335: }
 7336: 
 7337: sub check_configuser {
 7338:     my ($uhome,$dom,$confname,$servadm) = @_;
 7339:     my ($configuserok,%currroles);
 7340:     if ($uhome eq 'no_host') {
 7341:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
 7342:         my $configpass = &LONCAPA::Enrollment::create_password();
 7343:         $configuserok = 
 7344:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
 7345:                              $configpass,'','','','','',undef,$servadm);
 7346:     } else {
 7347:         $configuserok = 'ok';
 7348:         %currroles = 
 7349:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
 7350:     }
 7351:     return ($configuserok,%currroles);
 7352: }
 7353: 
 7354: sub check_authorstatus {
 7355:     my ($dom,$confname,%currroles) = @_;
 7356:     my $author_ok;
 7357:     if (!$currroles{':'.$dom.':au'}) {
 7358:         my $start = time;
 7359:         my $end = 0;
 7360:         $author_ok = 
 7361:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
 7362:                                         'au',$end,$start,'','','domconfig');
 7363:     } else {
 7364:         $author_ok = 'ok';
 7365:     }
 7366:     return $author_ok;
 7367: }
 7368: 
 7369: sub publishlogo {
 7370:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
 7371:     my ($output,$fname,$logourl,$madethumb);
 7372:     if ($action eq 'upload') {
 7373:         $fname=$env{'form.'.$formname.'.filename'};
 7374:         chop($env{'form.'.$formname});
 7375:     } else {
 7376:         ($fname) = ($formname =~ /([^\/]+)$/);
 7377:     }
 7378:     if ($savefileas ne '') {
 7379:         $fname = $savefileas;
 7380:     }
 7381:     $fname=&Apache::lonnet::clean_filename($fname);
 7382: # See if there is anything left
 7383:     unless ($fname) { return ('error: no uploaded file'); }
 7384:     $fname="$subdir/$fname";
 7385:     my $docroot=$r->dir_config('lonDocRoot');
 7386:     my $filepath="$docroot/priv";
 7387:     my $relpath = "$dom/$confname";
 7388:     my ($fnamepath,$file,$fetchthumb);
 7389:     $file=$fname;
 7390:     if ($fname=~m|/|) {
 7391:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 7392:     }
 7393:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
 7394:     my $count;
 7395:     for ($count=5;$count<=$#parts;$count++) {
 7396:         $filepath.="/$parts[$count]";
 7397:         if ((-e $filepath)!=1) {
 7398:             mkdir($filepath,02770);
 7399:         }
 7400:     }
 7401:     # Check for bad extension and disallow upload
 7402:     if ($file=~/\.(\w+)$/ &&
 7403:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 7404:         $output = 
 7405:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
 7406:     } elsif ($file=~/\.(\w+)$/ &&
 7407:         !defined(&Apache::loncommon::fileembstyle($1))) {
 7408:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 7409:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
 7410:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 7411:     } elsif (-d "$filepath/$file") {
 7412:         $output = &mt('Filename is a directory name - rename the file and re-upload');
 7413:     } else {
 7414:         my $source = $filepath.'/'.$file;
 7415:         my $logfile;
 7416:         if (!open($logfile,">>$source".'.log')) {
 7417:             return (&mt('No write permission to Authoring Space'));
 7418:         }
 7419:         print $logfile
 7420: "\n================= Publish ".localtime()." ================\n".
 7421: $env{'user.name'}.':'.$env{'user.domain'}."\n";
 7422: # Save the file
 7423:         if (!open(FH,'>'.$source)) {
 7424:             &Apache::lonnet::logthis('Failed to create '.$source);
 7425:             return (&mt('Failed to create file'));
 7426:         }
 7427:         if ($action eq 'upload') {
 7428:             if (!print FH ($env{'form.'.$formname})) {
 7429:                 &Apache::lonnet::logthis('Failed to write to '.$source);
 7430:                 return (&mt('Failed to write file'));
 7431:             }
 7432:         } else {
 7433:             my $original = &Apache::lonnet::filelocation('',$formname);
 7434:             if(!copy($original,$source)) {
 7435:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
 7436:                 return (&mt('Failed to write file'));
 7437:             }
 7438:         }
 7439:         close(FH);
 7440:         chmod(0660, $source); # Permissions to rw-rw---.
 7441: 
 7442:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
 7443:         my $copyfile=$targetdir.'/'.$file;
 7444: 
 7445:         my @parts=split(/\//,$targetdir);
 7446:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 7447:         for (my $count=5;$count<=$#parts;$count++) {
 7448:             $path.="/$parts[$count]";
 7449:             if (!-e $path) {
 7450:                 print $logfile "\nCreating directory ".$path;
 7451:                 mkdir($path,02770);
 7452:             }
 7453:         }
 7454:         my $versionresult;
 7455:         if (-e $copyfile) {
 7456:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
 7457:         } else {
 7458:             $versionresult = 'ok';
 7459:         }
 7460:         if ($versionresult eq 'ok') {
 7461:             if (copy($source,$copyfile)) {
 7462:                 print $logfile "\nCopied original source to ".$copyfile."\n";
 7463:                 $output = 'ok';
 7464:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
 7465:                 push(@{$modified_urls},[$copyfile,$source]);
 7466:                 my $metaoutput = 
 7467:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
 7468:                 unless ($registered_cleanup) {
 7469:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
 7470:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
 7471:                     $registered_cleanup=1;
 7472:                 }
 7473:             } else {
 7474:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
 7475:                 $output = &mt('Failed to copy file to RES space').", $!";
 7476:             }
 7477:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 7478:                 my $inputfile = $filepath.'/'.$file;
 7479:                 my $outfile = $filepath.'/'.'tn-'.$file;
 7480:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
 7481:                 if ($fullwidth ne '' && $fullheight ne '') { 
 7482:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
 7483:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 7484:                         system("convert -sample $thumbsize $inputfile $outfile");
 7485:                         chmod(0660, $filepath.'/tn-'.$file);
 7486:                         if (-e $outfile) {
 7487:                             my $copyfile=$targetdir.'/tn-'.$file;
 7488:                             if (copy($outfile,$copyfile)) {
 7489:                                 print $logfile "\nCopied source to ".$copyfile."\n";
 7490:                                 my $thumb_metaoutput = 
 7491:                                     &write_metadata($dom,$confname,$formname,
 7492:                                                     $targetdir,'tn-'.$file,$logfile);
 7493:                                 push(@{$modified_urls},[$copyfile,$outfile]);
 7494:                                 unless ($registered_cleanup) {
 7495:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
 7496:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
 7497:                                     $registered_cleanup=1;
 7498:                                 }
 7499:                                 $madethumb = 1;
 7500:                             } else {
 7501:                                 print $logfile "\nUnable to write ".$copyfile.
 7502:                                                ':'.$!."\n";
 7503:                             }
 7504:                         }
 7505:                     }
 7506:                 }
 7507:             }
 7508:         } else {
 7509:             $output = $versionresult;
 7510:         }
 7511:     }
 7512:     return ($output,$logourl,$madethumb);
 7513: }
 7514: 
 7515: sub logo_versioning {
 7516:     my ($targetdir,$file,$logfile) = @_;
 7517:     my $target = $targetdir.'/'.$file;
 7518:     my ($maxversion,$fn,$extn,$output);
 7519:     $maxversion = 0;
 7520:     if ($file =~ /^(.+)\.(\w+)$/) {
 7521:         $fn=$1;
 7522:         $extn=$2;
 7523:     }
 7524:     opendir(DIR,$targetdir);
 7525:     while (my $filename=readdir(DIR)) {
 7526:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
 7527:             $maxversion=($1>$maxversion)?$1:$maxversion;
 7528:         }
 7529:     }
 7530:     $maxversion++;
 7531:     print $logfile "\nCreating old version ".$maxversion."\n";
 7532:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
 7533:     if (copy($target,$copyfile)) {
 7534:         print $logfile "Copied old target to ".$copyfile."\n";
 7535:         $copyfile=$copyfile.'.meta';
 7536:         if (copy($target.'.meta',$copyfile)) {
 7537:             print $logfile "Copied old target metadata to ".$copyfile."\n";
 7538:             $output = 'ok';
 7539:         } else {
 7540:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
 7541:             $output = &mt('Failed to copy old meta').", $!, ";
 7542:         }
 7543:     } else {
 7544:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
 7545:         $output = &mt('Failed to copy old target').", $!, ";
 7546:     }
 7547:     return $output;
 7548: }
 7549: 
 7550: sub write_metadata {
 7551:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
 7552:     my (%metadatafields,%metadatakeys,$output);
 7553:     $metadatafields{'title'}=$formname;
 7554:     $metadatafields{'creationdate'}=time;
 7555:     $metadatafields{'lastrevisiondate'}=time;
 7556:     $metadatafields{'copyright'}='public';
 7557:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
 7558:                                          $env{'user.domain'};
 7559:     $metadatafields{'authorspace'}=$confname.':'.$dom;
 7560:     $metadatafields{'domain'}=$dom;
 7561:     {
 7562:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
 7563:         my $mfh;
 7564:         if (open($mfh,'>'.$targetdir.'/'.$file.'.meta')) {
 7565:             foreach (sort(keys(%metadatafields))) {
 7566:                 unless ($_=~/\./) {
 7567:                     my $unikey=$_;
 7568:                     $unikey=~/^([A-Za-z]+)/;
 7569:                     my $tag=$1;
 7570:                     $tag=~tr/A-Z/a-z/;
 7571:                     print $mfh "\n\<$tag";
 7572:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
 7573:                         my $value=$metadatafields{$unikey.'.'.$_};
 7574:                         $value=~s/\"/\'\'/g;
 7575:                         print $mfh ' '.$_.'="'.$value.'"';
 7576:                     }
 7577:                     print $mfh '>'.
 7578:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
 7579:                             .'</'.$tag.'>';
 7580:                 }
 7581:             }
 7582:             $output = 'ok';
 7583:             print $logfile "\nWrote metadata";
 7584:             close($mfh);
 7585:         } else {
 7586:             print $logfile "\nFailed to open metadata file";
 7587:             $output = &mt('Could not write metadata');
 7588:         }
 7589:     }
 7590:     return $output;
 7591: }
 7592: 
 7593: sub notifysubscribed {
 7594:     foreach my $targetsource (@{$modified_urls}){
 7595:         next unless (ref($targetsource) eq 'ARRAY');
 7596:         my ($target,$source)=@{$targetsource};
 7597:         if ($source ne '') {
 7598:             if (open(my $logfh,'>>'.$source.'.log')) {
 7599:                 print $logfh "\nCleanup phase: Notifications\n";
 7600:                 my @subscribed=&subscribed_hosts($target);
 7601:                 foreach my $subhost (@subscribed) {
 7602:                     print $logfh "\nNotifying host ".$subhost.':';
 7603:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
 7604:                     print $logfh $reply;
 7605:                 }
 7606:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
 7607:                 foreach my $subhost (@subscribedmeta) {
 7608:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
 7609:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
 7610:                                                         $subhost);
 7611:                     print $logfh $reply;
 7612:                 }
 7613:                 print $logfh "\n============ Done ============\n";
 7614:                 close($logfh);
 7615:             }
 7616:         }
 7617:     }
 7618:     return OK;
 7619: }
 7620: 
 7621: sub subscribed_hosts {
 7622:     my ($target) = @_;
 7623:     my @subscribed;
 7624:     if (open(my $fh,"<$target.subscription")) {
 7625:         while (my $subline=<$fh>) {
 7626:             if ($subline =~ /^($match_lonid):/) {
 7627:                 my $host = $1;
 7628:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
 7629:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
 7630:                         push(@subscribed,$host);
 7631:                     }
 7632:                 }
 7633:             }
 7634:         }
 7635:     }
 7636:     return @subscribed;
 7637: }
 7638: 
 7639: sub check_switchserver {
 7640:     my ($dom,$confname) = @_;
 7641:     my ($allowed,$switchserver);
 7642:     my $home = &Apache::lonnet::homeserver($confname,$dom);
 7643:     if ($home eq 'no_host') {
 7644:         $home = &Apache::lonnet::domain($dom,'primary');
 7645:     }
 7646:     my @ids=&Apache::lonnet::current_machine_ids();
 7647:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 7648:     if (!$allowed) {
 7649: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 7650:     }
 7651:     return $switchserver;
 7652: }
 7653: 
 7654: sub modify_quotas {
 7655:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
 7656:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
 7657:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
 7658:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
 7659:         $validationfieldsref);
 7660:     if ($action eq 'quotas') {
 7661:         $context = 'tools'; 
 7662:     } else {
 7663:         $context = $action;
 7664:     }
 7665:     if ($context eq 'requestcourses') {
 7666:         @usertools = ('official','unofficial','community','textbook','placement');
 7667:         @options =('norequest','approval','validate','autolimit');
 7668:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 7669:         %titles = &courserequest_titles();
 7670:         $toolregexp = join('|',@usertools);
 7671:         %conditions = &courserequest_conditions();
 7672:         $confname = $dom.'-domainconfig';
 7673:         my $servadm = $r->dir_config('lonAdmEMail');
 7674:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 7675:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
 7676:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
 7677:     } elsif ($context eq 'requestauthor') {
 7678:         @usertools = ('author');
 7679:         %titles = &authorrequest_titles();
 7680:     } else {
 7681:         @usertools = ('aboutme','blog','webdav','portfolio');
 7682:         %titles = &tool_titles();
 7683:     }
 7684:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 7685:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7686:     foreach my $key (keys(%env)) {
 7687:         if ($context eq 'requestcourses') {
 7688:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
 7689:                 my $item = $1;
 7690:                 my $type = $2;
 7691:                 if ($type =~ /^limit_(.+)/) {
 7692:                     $limithash{$item}{$1} = $env{$key};
 7693:                 } else {
 7694:                     $confhash{$item}{$type} = $env{$key};
 7695:                 }
 7696:             }
 7697:         } elsif ($context eq 'requestauthor') {
 7698:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
 7699:                 $confhash{$1} = $env{$key};
 7700:             }
 7701:         } else {
 7702:             if ($key =~ /^form\.quota_(.+)$/) {
 7703:                 $confhash{'defaultquota'}{$1} = $env{$key};
 7704:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
 7705:                 $confhash{'authorquota'}{$1} = $env{$key};
 7706:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
 7707:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
 7708:             }
 7709:         }
 7710:     }
 7711:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 7712:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
 7713:         @approvalnotify = sort(@approvalnotify);
 7714:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
 7715:         my @crstypes = ('official','unofficial','community','textbook','placement');
 7716:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
 7717:         foreach my $type (@hasuniquecode) {
 7718:             if (grep(/^\Q$type\E$/,@crstypes)) {
 7719:                 $confhash{'uniquecode'}{$type} = 1;
 7720:             }
 7721:         }
 7722:         my (%newbook,%allpos);
 7723:         if ($context eq 'requestcourses') {
 7724:             foreach my $type ('textbooks','templates') {
 7725:                 @{$allpos{$type}} = (); 
 7726:                 my $invalid;
 7727:                 if ($type eq 'textbooks') {
 7728:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
 7729:                 } else {
 7730:                     $invalid = &mt('Invalid LON-CAPA course for template');
 7731:                 }
 7732:                 if ($env{'form.'.$type.'_addbook'}) {
 7733:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
 7734:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
 7735:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
 7736:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
 7737:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
 7738:                         } else {
 7739:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
 7740:                             my $position = $env{'form.'.$type.'_addbook_pos'};
 7741:                             $position =~ s/\D+//g;
 7742:                             if ($position ne '') {
 7743:                                 $allpos{$type}[$position] = $newbook{$type};
 7744:                             }
 7745:                         }
 7746:                     } else {
 7747:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
 7748:                     }
 7749:                 }
 7750:             } 
 7751:         }
 7752:         if (ref($domconfig{$action}) eq 'HASH') {
 7753:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
 7754:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
 7755:                     $changes{'notify'}{'approval'} = 1;
 7756:                 }
 7757:             } else {
 7758:                 if ($confhash{'notify'}{'approval'}) {
 7759:                     $changes{'notify'}{'approval'} = 1;
 7760:                 }
 7761:             }
 7762:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
 7763:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
 7764:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
 7765:                         unless ($confhash{'uniquecode'}{$crstype}) {
 7766:                             $changes{'uniquecode'} = 1;
 7767:                         }
 7768:                     }
 7769:                     unless ($changes{'uniquecode'}) {
 7770:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
 7771:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
 7772:                                 $changes{'uniquecode'} = 1;
 7773:                             }
 7774:                         }
 7775:                     }
 7776:                } else {
 7777:                    $changes{'uniquecode'} = 1;
 7778:                }
 7779:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
 7780:                 $changes{'uniquecode'} = 1;
 7781:             }
 7782:             if ($context eq 'requestcourses') {
 7783:                 foreach my $type ('textbooks','templates') {
 7784:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
 7785:                         my %deletions;
 7786:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
 7787:                         if (@todelete) {
 7788:                             map { $deletions{$_} = 1; } @todelete;
 7789:                         }
 7790:                         my %imgdeletions;
 7791:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
 7792:                         if (@todeleteimages) {
 7793:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
 7794:                         }
 7795:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
 7796:                         for (my $i=0; $i<=$maxnum; $i++) {
 7797:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
 7798:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
 7799:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
 7800:                                 if ($deletions{$key}) {
 7801:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
 7802:                                         #FIXME need to obsolete item in RES space
 7803:                                     }
 7804:                                     next;
 7805:                                 } else {
 7806:                                     my $newpos = $env{'form.'.$itemid};
 7807:                                     $newpos =~ s/\D+//g;
 7808:                                     foreach my $item ('subject','title','publisher','author') {
 7809:                                         next if ((($item eq 'author') || ($item eq 'publisher')) && 
 7810:                                                  ($type eq 'templates'));
 7811:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
 7812:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
 7813:                                             $changes{$type}{$key} = 1;
 7814:                                         }
 7815:                                     }
 7816:                                     $allpos{$type}[$newpos] = $key;
 7817:                                 }
 7818:                                 if ($imgdeletions{$key}) {
 7819:                                     $changes{$type}{$key} = 1;
 7820:                                     #FIXME need to obsolete item in RES space
 7821:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
 7822:                                     my ($cdom,$cnum) = split(/_/,$key);
 7823:                                     my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
 7824:                                                                                   $cdom,$cnum,$type,$configuserok,
 7825:                                                                                   $switchserver,$author_ok);
 7826:                                     if ($imgurl) {
 7827:                                         $confhash{$type}{$key}{'image'} = $imgurl;
 7828:                                         $changes{$type}{$key} = 1; 
 7829:                                     }
 7830:                                     if ($error) {
 7831:                                         &Apache::lonnet::logthis($error);
 7832:                                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 7833:                                     } 
 7834:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
 7835:                                     $confhash{$type}{$key}{'image'} = 
 7836:                                         $domconfig{$action}{$type}{$key}{'image'};
 7837:                                 }
 7838:                             }
 7839:                         }
 7840:                     }
 7841:                 }
 7842:             }
 7843:         } else {
 7844:             if ($confhash{'notify'}{'approval'}) {
 7845:                 $changes{'notify'}{'approval'} = 1;
 7846:             }
 7847:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
 7848:                 $changes{'uniquecode'} = 1;
 7849:             }
 7850:         }
 7851:         if ($context eq 'requestcourses') {
 7852:             foreach my $type ('textbooks','templates') {
 7853:                 if ($newbook{$type}) {
 7854:                     $changes{$type}{$newbook{$type}} = 1;
 7855:                     foreach my $item ('subject','title','publisher','author') {
 7856:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
 7857:                                  ($type eq 'template'));
 7858:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
 7859:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
 7860:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
 7861:                         }
 7862:                     }
 7863:                     if ($type eq 'textbooks') {
 7864:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
 7865:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
 7866:                             my ($imageurl,$error) =
 7867:                                 &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
 7868:                                                         $configuserok,$switchserver,$author_ok);
 7869:                             if ($imageurl) {
 7870:                                 $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
 7871:                             }
 7872:                             if ($error) {
 7873:                                 &Apache::lonnet::logthis($error);
 7874:                                 $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 7875:                             }
 7876:                         }
 7877:                     }
 7878:                 }
 7879:                 if (@{$allpos{$type}} > 0) {
 7880:                     my $idx = 0;
 7881:                     foreach my $item (@{$allpos{$type}}) {
 7882:                         if ($item ne '') {
 7883:                             $confhash{$type}{$item}{'order'} = $idx;
 7884:                             if (ref($domconfig{$action}) eq 'HASH') {
 7885:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
 7886:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
 7887:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
 7888:                                             $changes{$type}{$item} = 1;
 7889:                                         }
 7890:                                     }
 7891:                                 }
 7892:                             }
 7893:                             $idx ++;
 7894:                         }
 7895:                     }
 7896:                 }
 7897:             }
 7898:             if (ref($validationitemsref) eq 'ARRAY') {
 7899:                 foreach my $item (@{$validationitemsref}) {
 7900:                     if ($item eq 'fields') {
 7901:                         my @changed;
 7902:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
 7903:                         if (@{$confhash{'validation'}{$item}} > 0) {
 7904:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
 7905:                         }
 7906:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 7907:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 7908:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
 7909:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
 7910:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
 7911:                                 } else {
 7912:                                     @changed = @{$confhash{'validation'}{$item}};
 7913:                                 }
 7914:                             } else {
 7915:                                 @changed = @{$confhash{'validation'}{$item}};
 7916:                             }
 7917:                         } else {
 7918:                             @changed = @{$confhash{'validation'}{$item}};
 7919:                         }
 7920:                         if (@changed) {
 7921:                             if ($confhash{'validation'}{$item}) {
 7922:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
 7923:                             } else {
 7924:                                 $changes{'validation'}{$item} = &mt('None');
 7925:                             }
 7926:                         }
 7927:                     } else {
 7928:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
 7929:                         if ($item eq 'markup') {
 7930:                             if ($env{'form.requestcourses_validation_'.$item}) {
 7931:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
 7932:                             }
 7933:                         }
 7934:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 7935:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 7936:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
 7937:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
 7938:                                 }
 7939:                             } else {
 7940:                                 if ($confhash{'validation'}{$item} ne '') {
 7941:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
 7942:                                 }
 7943:                             }
 7944:                         } else {
 7945:                             if ($confhash{'validation'}{$item} ne '') {
 7946:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
 7947:                             }
 7948:                         }
 7949:                     }
 7950:                 }
 7951:             }
 7952:             if ($env{'form.validationdc'}) {
 7953:                 my $newval = $env{'form.validationdc'};
 7954:                 my %domcoords = &get_active_dcs($dom);
 7955:                 if (exists($domcoords{$newval})) {
 7956:                     $confhash{'validation'}{'dc'} = $newval;
 7957:                 }
 7958:             }
 7959:             if (ref($confhash{'validation'}) eq 'HASH') {
 7960:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 7961:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 7962:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
 7963:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
 7964:                                 if ($confhash{'validation'}{'dc'} eq '') {
 7965:                                     $changes{'validation'}{'dc'} = &mt('None');
 7966:                                 } else {
 7967:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 7968:                                 }
 7969:                             }
 7970:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
 7971:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 7972:                         }
 7973:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
 7974:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 7975:                     }
 7976:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
 7977:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 7978:                 }  
 7979:             } else {
 7980:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 7981:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 7982:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
 7983:                             $changes{'validation'}{'dc'} = &mt('None');
 7984:                         }
 7985:                     }
 7986:                 }
 7987:             }
 7988:         }
 7989:     } else {
 7990:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
 7991:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
 7992:     }
 7993:     foreach my $item (@usertools) {
 7994:         foreach my $type (@{$types},'default','_LC_adv') {
 7995:             my $unset; 
 7996:             if ($context eq 'requestcourses') {
 7997:                 $unset = '0';
 7998:                 if ($type eq '_LC_adv') {
 7999:                     $unset = '';
 8000:                 }
 8001:                 if ($confhash{$item}{$type} eq 'autolimit') {
 8002:                     $confhash{$item}{$type} .= '=';
 8003:                     unless ($limithash{$item}{$type} =~ /\D/) {
 8004:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
 8005:                     }
 8006:                 }
 8007:             } elsif ($context eq 'requestauthor') {
 8008:                 $unset = '0';
 8009:                 if ($type eq '_LC_adv') {
 8010:                     $unset = '';
 8011:                 }
 8012:             } else {
 8013:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
 8014:                     $confhash{$item}{$type} = 1;
 8015:                 } else {
 8016:                     $confhash{$item}{$type} = 0;
 8017:                 }
 8018:             }
 8019:             if (ref($domconfig{$action}) eq 'HASH') {
 8020:                 if ($action eq 'requestauthor') {
 8021:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
 8022:                         $changes{$type} = 1;
 8023:                     }
 8024:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
 8025:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
 8026:                         $changes{$item}{$type} = 1;
 8027:                     }
 8028:                 } else {
 8029:                     if ($context eq 'requestcourses') {
 8030:                         if ($confhash{$item}{$type} ne $unset) {
 8031:                             $changes{$item}{$type} = 1;
 8032:                         }
 8033:                     } else {
 8034:                         if (!$confhash{$item}{$type}) {
 8035:                             $changes{$item}{$type} = 1;
 8036:                         }
 8037:                     }
 8038:                 }
 8039:             } else {
 8040:                 if ($context eq 'requestcourses') {
 8041:                     if ($confhash{$item}{$type} ne $unset) {
 8042:                         $changes{$item}{$type} = 1;
 8043:                     }
 8044:                 } elsif ($context eq 'requestauthor') {
 8045:                     if ($confhash{$type} ne $unset) {
 8046:                         $changes{$type} = 1;
 8047:                     }
 8048:                 } else {
 8049:                     if (!$confhash{$item}{$type}) {
 8050:                         $changes{$item}{$type} = 1;
 8051:                     }
 8052:                 }
 8053:             }
 8054:         }
 8055:     }
 8056:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 8057:         if (ref($domconfig{'quotas'}) eq 'HASH') {
 8058:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 8059:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
 8060:                     if (exists($confhash{'defaultquota'}{$key})) {
 8061:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
 8062:                             $changes{'defaultquota'}{$key} = 1;
 8063:                         }
 8064:                     } else {
 8065:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
 8066:                     }
 8067:                 }
 8068:             } else {
 8069:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
 8070:                     if (exists($confhash{'defaultquota'}{$key})) {
 8071:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
 8072:                             $changes{'defaultquota'}{$key} = 1;
 8073:                         }
 8074:                     } else {
 8075:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
 8076:                     }
 8077:                 }
 8078:             }
 8079:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 8080:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
 8081:                     if (exists($confhash{'authorquota'}{$key})) {
 8082:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
 8083:                             $changes{'authorquota'}{$key} = 1;
 8084:                         }
 8085:                     } else {
 8086:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
 8087:                     }
 8088:                 }
 8089:             }
 8090:         }
 8091:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
 8092:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
 8093:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
 8094:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 8095:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
 8096:                             $changes{'defaultquota'}{$key} = 1;
 8097:                         }
 8098:                     } else {
 8099:                         if (!exists($domconfig{'quotas'}{$key})) {
 8100:                             $changes{'defaultquota'}{$key} = 1;
 8101:                         }
 8102:                     }
 8103:                 } else {
 8104:                     $changes{'defaultquota'}{$key} = 1;
 8105:                 }
 8106:             }
 8107:         }
 8108:         if (ref($confhash{'authorquota'}) eq 'HASH') {
 8109:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
 8110:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
 8111:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 8112:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
 8113:                             $changes{'authorquota'}{$key} = 1;
 8114:                         }
 8115:                     } else {
 8116:                         $changes{'authorquota'}{$key} = 1;
 8117:                     }
 8118:                 } else {
 8119:                     $changes{'authorquota'}{$key} = 1;
 8120:                 }
 8121:             }
 8122:         }
 8123:     }
 8124: 
 8125:     if ($context eq 'requestauthor') {
 8126:         $domdefaults{'requestauthor'} = \%confhash;
 8127:     } else {
 8128:         foreach my $key (keys(%confhash)) {
 8129:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
 8130:                 $domdefaults{$key} = $confhash{$key};
 8131:             }
 8132:         }
 8133:     }
 8134: 
 8135:     my %quotahash = (
 8136:                       $action => { %confhash }
 8137:                     );
 8138:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
 8139:                                              $dom);
 8140:     if ($putresult eq 'ok') {
 8141:         if (keys(%changes) > 0) {
 8142:             my $cachetime = 24*60*60;
 8143:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
 8144:             if (ref($lastactref) eq 'HASH') {
 8145:                 $lastactref->{'domdefaults'} = 1;
 8146:             }
 8147:             $resulttext = &mt('Changes made:').'<ul>';
 8148:             unless (($context eq 'requestcourses') ||
 8149:                     ($context eq 'requestauthor')) {
 8150:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
 8151:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
 8152:                     foreach my $type (@{$types},'default') {
 8153:                         if (defined($changes{'defaultquota'}{$type})) {
 8154:                             my $typetitle = $usertypes->{$type};
 8155:                             if ($type eq 'default') {
 8156:                                 $typetitle = $othertitle;
 8157:                             }
 8158:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
 8159:                         }
 8160:                     }
 8161:                     $resulttext .= '</ul></li>';
 8162:                 }
 8163:                 if (ref($changes{'authorquota'}) eq 'HASH') {
 8164:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
 8165:                     foreach my $type (@{$types},'default') {
 8166:                         if (defined($changes{'authorquota'}{$type})) {
 8167:                             my $typetitle = $usertypes->{$type};
 8168:                             if ($type eq 'default') {
 8169:                                 $typetitle = $othertitle;
 8170:                             }
 8171:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
 8172:                         }
 8173:                     }
 8174:                     $resulttext .= '</ul></li>';
 8175:                 }
 8176:             }
 8177:             my %newenv;
 8178:             foreach my $item (@usertools) {
 8179:                 my (%haschgs,%inconf);
 8180:                 if ($context eq 'requestauthor') {
 8181:                     %haschgs = %changes;
 8182:                     %inconf = %confhash;
 8183:                 } else {
 8184:                     if (ref($changes{$item}) eq 'HASH') {
 8185:                         %haschgs = %{$changes{$item}};
 8186:                     }
 8187:                     if (ref($confhash{$item}) eq 'HASH') {
 8188:                         %inconf = %{$confhash{$item}};
 8189:                     }
 8190:                 }
 8191:                 if (keys(%haschgs) > 0) {
 8192:                     my $newacc = 
 8193:                         &Apache::lonnet::usertools_access($env{'user.name'},
 8194:                                                           $env{'user.domain'},
 8195:                                                           $item,'reload',$context);
 8196:                     if (($context eq 'requestcourses') ||
 8197:                         ($context eq 'requestauthor')) {
 8198:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
 8199:                             $newenv{'environment.canrequest.'.$item} = $newacc;
 8200:                         }
 8201:                     } else {
 8202:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
 8203:                             $newenv{'environment.availabletools.'.$item} = $newacc;
 8204:                         }
 8205:                     }
 8206:                     unless ($context eq 'requestauthor') {
 8207:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
 8208:                     }
 8209:                     foreach my $type (@{$types},'default','_LC_adv') {
 8210:                         if ($haschgs{$type}) {
 8211:                             my $typetitle = $usertypes->{$type};
 8212:                             if ($type eq 'default') {
 8213:                                 $typetitle = $othertitle;
 8214:                             } elsif ($type eq '_LC_adv') {
 8215:                                 $typetitle = 'LON-CAPA Advanced Users'; 
 8216:                             }
 8217:                             if ($inconf{$type}) {
 8218:                                 if ($context eq 'requestcourses') {
 8219:                                     my $cond;
 8220:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
 8221:                                         if ($1 eq '') {
 8222:                                             $cond = &mt('(Automatic processing of any request).');
 8223:                                         } else {
 8224:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
 8225:                                         }
 8226:                                     } else { 
 8227:                                         $cond = $conditions{$inconf{$type}};
 8228:                                     }
 8229:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
 8230:                                 } elsif ($context eq 'requestauthor') {
 8231:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
 8232:                                                              $titles{$inconf{$type}},$typetitle);
 8233: 
 8234:                                 } else {
 8235:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
 8236:                                 }
 8237:                             } else {
 8238:                                 if ($type eq '_LC_adv') {
 8239:                                     if ($inconf{$type} eq '0') {
 8240:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
 8241:                                     } else { 
 8242:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
 8243:                                     }
 8244:                                 } else {
 8245:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
 8246:                                 }
 8247:                             }
 8248:                         }
 8249:                     }
 8250:                     unless ($context eq 'requestauthor') {
 8251:                         $resulttext .= '</ul></li>';
 8252:                     }
 8253:                 }
 8254:             }
 8255:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
 8256:                 if (ref($changes{'notify'}) eq 'HASH') {
 8257:                     if ($changes{'notify'}{'approval'}) {
 8258:                         if (ref($confhash{'notify'}) eq 'HASH') {
 8259:                             if ($confhash{'notify'}{'approval'}) {
 8260:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
 8261:                             } else {
 8262:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
 8263:                             }
 8264:                         }
 8265:                     }
 8266:                 }
 8267:             }
 8268:             if ($action eq 'requestcourses') {
 8269:                 my @offon = ('off','on');
 8270:                 if ($changes{'uniquecode'}) {
 8271:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
 8272:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
 8273:                         $resulttext .= '<li>'.
 8274:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
 8275:                                        '</li>';
 8276:                     } else {
 8277:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
 8278:                                        '</li>';
 8279:                     }
 8280:                 }
 8281:                 foreach my $type ('textbooks','templates') {
 8282:                     if (ref($changes{$type}) eq 'HASH') {
 8283:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
 8284:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
 8285:                             my %coursehash = &Apache::lonnet::coursedescription($key);
 8286:                             my $coursetitle = $coursehash{'description'};
 8287:                             my $position = $confhash{$type}{$key}{'order'} + 1;
 8288:                             $resulttext .= '<li>';
 8289:                             foreach my $item ('subject','title','publisher','author') {
 8290:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
 8291:                                          ($type eq 'templates'));
 8292:                                 my $name = $item.':';
 8293:                                 $name =~ s/^(\w)/\U$1/;
 8294:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
 8295:                             }
 8296:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
 8297:                             if ($type eq 'textbooks') {
 8298:                                 if ($confhash{$type}{$key}{'image'}) {
 8299:                                     $resulttext .= ' '.&mt('Image: [_1]',
 8300:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
 8301:                                                    ' alt="Textbook cover" />').'<br />';
 8302:                                 }
 8303:                             }
 8304:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
 8305:                         }
 8306:                         $resulttext .= '</ul></li>';
 8307:                     }
 8308:                 }
 8309:                 if (ref($changes{'validation'}) eq 'HASH') {
 8310:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
 8311:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
 8312:                         foreach my $item (@{$validationitemsref}) {
 8313:                             if (exists($changes{'validation'}{$item})) {
 8314:                                 if ($item eq 'markup') {
 8315:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
 8316:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
 8317:                                 } else {
 8318:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
 8319:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
 8320:                                 }
 8321:                             }
 8322:                         }
 8323:                         if (exists($changes{'validation'}{'dc'})) {
 8324:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
 8325:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
 8326:                         }
 8327:                     }
 8328:                 }
 8329:             }
 8330:             $resulttext .= '</ul>';
 8331:             if (keys(%newenv)) {
 8332:                 &Apache::lonnet::appenv(\%newenv);
 8333:             }
 8334:         } else {
 8335:             if ($context eq 'requestcourses') {
 8336:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
 8337:             } elsif ($context eq 'requestauthor') {
 8338:                 $resulttext = &mt('No changes made to rights to request author space.');
 8339:             } else {
 8340:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
 8341:             }
 8342:         }
 8343:     } else {
 8344:         $resulttext = '<span class="LC_error">'.
 8345: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 8346:     }
 8347:     if ($errors) {
 8348:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
 8349:                        '<ul>'.$errors.'</ul></p>';
 8350:     }
 8351:     return $resulttext;
 8352: }
 8353: 
 8354: sub process_textbook_image {
 8355:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
 8356:     my $filename = $env{'form.'.$caller.'.filename'};
 8357:     my ($error,$url);
 8358:     my ($width,$height) = (50,50);
 8359:     if ($configuserok eq 'ok') {
 8360:         if ($switchserver) {
 8361:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
 8362:                          $switchserver);
 8363:         } elsif ($author_ok eq 'ok') {
 8364:             my ($result,$imageurl) =
 8365:                 &publishlogo($r,'upload',$caller,$dom,$confname,
 8366:                              "$type/$dom/$cnum/cover",$width,$height);
 8367:             if ($result eq 'ok') {
 8368:                 $url = $imageurl;
 8369:             } else {
 8370:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
 8371:             }
 8372:         } else {
 8373:             $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);
 8374:         }
 8375:     } else {
 8376:         $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);
 8377:     }
 8378:     return ($url,$error);
 8379: }
 8380: 
 8381: sub modify_ltitools {
 8382:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
 8383:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 8384:     my ($newid,@allpos,%changes,%confhash,$errors,$resulttext);
 8385:     my $confname = $dom.'-domainconfig';
 8386:     my $servadm = $r->dir_config('lonAdmEMail');
 8387:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 8388:     my (%posslti,%possfield);
 8389:     my @courseroles = ('cc','in','ta','ep','st');
 8390:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
 8391:     map { $posslti{$_} = 1; } @ltiroles;
 8392:     my @allfields = ('fullname','firstname','lastname','email','user','roles');
 8393:     map { $possfield{$_} = 1; } @allfields;
 8394:     my %lt = &ltitools_names(); 
 8395:     if ($env{'form.ltitools_add'}) {
 8396:         my $title = $env{'form.ltitools_add_title'};
 8397:         $title =~ s/(`)/'/g;
 8398:         ($newid,my $error) = &get_ltitools_id($dom,$title);
 8399:         if ($newid) {
 8400:             my $position = $env{'form.ltitools_add_pos'};
 8401:             $position =~ s/\D+//g;
 8402:             if ($position ne '') {
 8403:                 $allpos[$position] = $newid;
 8404:             }
 8405:             $changes{$newid} = 1;
 8406:             foreach my $item ('title','url','key','secret') {
 8407:                 $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
 8408:                 if ($env{'form.ltitools_add_'.$item}) {
 8409:                     $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
 8410:                 }
 8411:             }
 8412:             if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
 8413:                 $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
 8414:             }
 8415:             if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
 8416:                 $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
 8417:             }
 8418:             foreach my $item ('width','height') {
 8419:                 $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
 8420:                 $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
 8421:                 if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
 8422:                     $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
 8423:                 }
 8424:             }
 8425:             if ($env{'form.ltitools_add_target'} eq 'window') {
 8426:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
 8427:             } else {
 8428:                 $confhash{$newid}{'display'}{'target'} = 'iframe';
 8429:             }
 8430:             foreach my $item ('passback','roster') {
 8431:                 if ($env{'form.ltitools_add_'.$item}) {
 8432:                     $confhash{$newid}{$item} = 1;
 8433:                 }
 8434:             }
 8435:             if ($env{'form.ltitools_add_image.filename'} ne '') {
 8436:                 my ($imageurl,$error) =
 8437:                     &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$dom,
 8438:                                             $configuserok,$switchserver,$author_ok);
 8439:                 if ($imageurl) {
 8440:                     $confhash{$newid}{'image'} = $imageurl;
 8441:                 }
 8442:                 if ($error) {
 8443:                     &Apache::lonnet::logthis($error);
 8444:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 8445:                 }
 8446:             }
 8447:             my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
 8448:             foreach my $field (@fields) {
 8449:                 if ($possfield{$field}) {
 8450:                     if ($field eq 'roles') {
 8451:                         foreach my $role (@courseroles) {
 8452:                             my $choice = $env{'form.ltitools_add_roles_'.$role};
 8453:                             if (($choice ne '') && ($posslti{$choice})) {
 8454:                                 $confhash{$newid}{'roles'}{$role} = $choice;
 8455:                                 if ($role eq 'cc') {
 8456:                                     $confhash{$newid}{'roles'}{'co'} = $choice; 
 8457:                                 }
 8458:                             }
 8459:                         }
 8460:                     } else {
 8461:                         $confhash{$newid}{'fields'}{$field} = 1;
 8462:                     }
 8463:                 }
 8464:             }
 8465:             my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
 8466:             foreach my $item (@courseconfig) {
 8467:                 $confhash{$newid}{'crsconf'}{$item} = 1;
 8468:             }
 8469:             if ($env{'form.ltitools_add_custom'}) {
 8470:                 my $name = $env{'form.ltitools_add_custom_name'};
 8471:                 my $value = $env{'form.ltitools_add_custom_value'};
 8472:                 $value =~ s/(`)/'/g;
 8473:                 $name =~ s/(`)/'/g;
 8474:                 $confhash{$newid}{'custom'}{$name} = $value;
 8475:             }
 8476:         } else {
 8477:             my $error = &mt('Failed to acquire unique ID for new external tool');   
 8478:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 8479:         }
 8480:     }
 8481:     if (ref($domconfig{$action}) eq 'HASH') {
 8482:         my %deletions;
 8483:         my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
 8484:         if (@todelete) {
 8485:             map { $deletions{$_} = 1; } @todelete;
 8486:         }
 8487:         my %customadds;
 8488:         my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
 8489:         if (@newcustom) {
 8490:             map { $customadds{$_} = 1; } @newcustom;
 8491:         } 
 8492:         my %imgdeletions;
 8493:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
 8494:         if (@todeleteimages) {
 8495:             map { $imgdeletions{$_} = 1; } @todeleteimages;
 8496:         }
 8497:         my $maxnum = $env{'form.ltitools_maxnum'};
 8498:         for (my $i=0; $i<=$maxnum; $i++) {
 8499:             my $itemid = $env{'form.ltitools_id_'.$i};
 8500:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
 8501:                 if ($deletions{$itemid}) {
 8502:                     if ($domconfig{$action}{$itemid}{'image'}) {
 8503:                         #FIXME need to obsolete item in RES space
 8504:                     }
 8505:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
 8506:                     next;
 8507:                 } else {
 8508:                     my $newpos = $env{'form.ltitools_'.$itemid};
 8509:                     $newpos =~ s/\D+//g;
 8510:                     foreach my $item ('title','url','key','secret') {
 8511:                         $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
 8512:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
 8513:                             $changes{$itemid} = 1;
 8514:                         }
 8515:                     }
 8516:                     if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
 8517:                         $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
 8518:                     }
 8519:                     if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
 8520:                         $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
 8521:                     }
 8522:                     foreach my $size ('width','height') {
 8523:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
 8524:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
 8525:                         if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
 8526:                             $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
 8527:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
 8528:                                 if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
 8529:                                     $changes{$itemid} = 1;
 8530:                                 }
 8531:                             } else {
 8532:                                 $changes{$itemid} = 1;
 8533:                             }
 8534:                         }
 8535:                     }
 8536:                     if ($env{'form.ltitools_target_'.$i} eq 'window') {
 8537:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
 8538:                     } else {
 8539:                         $confhash{$itemid}{'display'}{'target'} = 'iframe';
 8540:                     }
 8541:                     if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
 8542:                         if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
 8543:                             $changes{$itemid} = 1;
 8544:                         }
 8545:                     } else {
 8546:                         $changes{$itemid} = 1;
 8547:                     }
 8548:                     foreach my $extra ('passback','roster') {
 8549:                         if ($env{'form.ltitools_'.$extra.'_'.$i}) {
 8550:                             $confhash{$itemid}{$extra} = 1;
 8551:                         }
 8552:                         if ($domconfig{$action}{$itemid}{$extra} ne $confhash{$itemid}{$extra}) {
 8553:                             $changes{$itemid} = 1;
 8554:                         }
 8555:                     }
 8556:                     my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
 8557:                     foreach my $item ('label','title','target') {
 8558:                         if (grep(/^\Q$item\E$/,@courseconfig)) {
 8559:                             $confhash{$itemid}{'crsconf'}{$item} = 1;
 8560:                             if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
 8561:                                 if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
 8562:                                     $changes{$itemid} = 1;
 8563:                                 }
 8564:                             } else {
 8565:                                 $changes{$itemid} = 1;
 8566:                             }
 8567:                         }
 8568:                     }
 8569:                     my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
 8570:                     foreach my $field (@fields) {
 8571:                         if ($possfield{$field}) {
 8572:                             if ($field eq 'roles') {
 8573:                                 foreach my $role (@courseroles) {
 8574:                                     my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
 8575:                                     if (($choice ne '') && ($posslti{$choice})) {
 8576:                                         $confhash{$itemid}{'roles'}{$role} = $choice;
 8577:                                         if ($role eq 'cc') {
 8578:                                             $confhash{$itemid}{'roles'}{'co'} = $choice;
 8579:                                         }
 8580:                                     }
 8581:                                     if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
 8582:                                         if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
 8583:                                             $changes{$itemid} = 1;
 8584:                                         }
 8585:                                     } elsif ($confhash{$itemid}{'roles'}{$role}) {
 8586:                                         $changes{$itemid} = 1;
 8587:                                     }
 8588:                                 }
 8589:                             } else {
 8590:                                 $confhash{$itemid}{'fields'}{$field} = 1;
 8591:                                 if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
 8592:                                     if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
 8593:                                         $changes{$itemid} = 1;
 8594:                                     }
 8595:                                 } else {
 8596:                                     $changes{$itemid} = 1;
 8597:                                 }
 8598:                             }
 8599:                         }
 8600:                     }
 8601:                     $allpos[$newpos] = $itemid;
 8602:                 }
 8603:                 if ($imgdeletions{$itemid}) {
 8604:                     $changes{$itemid} = 1;
 8605:                     #FIXME need to obsolete item in RES space
 8606:                 } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
 8607:                     my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
 8608:                                                                  $itemid,$configuserok,$switchserver,
 8609:                                                                  $author_ok);
 8610:                     if ($imgurl) {
 8611:                         $confhash{$itemid}{'image'} = $imgurl;
 8612:                         $changes{$itemid} = 1;
 8613:                     }
 8614:                     if ($error) {
 8615:                         &Apache::lonnet::logthis($error);
 8616:                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 8617:                     }
 8618:                 } elsif ($domconfig{$action}{$itemid}{'image'}) {
 8619:                     $confhash{$itemid}{'image'} =
 8620:                        $domconfig{$action}{$itemid}{'image'};
 8621:                 }
 8622:                 if ($customadds{$i}) {
 8623:                     my $name = $env{'form.ltitools_custom_name_'.$i};
 8624:                     $name =~ s/(`)/'/g;
 8625:                     $name =~ s/^\s+//;
 8626:                     $name =~ s/\s+$//;
 8627:                     my $value = $env{'form.ltitools_custom_value_'.$i};
 8628:                     $value =~ s/(`)/'/g;
 8629:                     $value =~ s/^\s+//;
 8630:                     $value =~ s/\s+$//;
 8631:                     if ($name ne '') {
 8632:                         $confhash{$itemid}{'custom'}{$name} = $value;
 8633:                         $changes{$itemid} = 1;
 8634:                     }
 8635:                 }
 8636:                 my %customdels;
 8637:                 my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i); 
 8638:                 if (@customdeletions) {
 8639:                     $changes{$itemid} = 1;
 8640:                 }
 8641:                 map { $customdels{$_} = 1; } @customdeletions;
 8642:                 if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
 8643:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
 8644:                         unless ($customdels{$key}) {
 8645:                             if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
 8646:                                 $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i}; 
 8647:                             }
 8648:                             if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
 8649:                                 $changes{$itemid} = 1;
 8650:                             }
 8651:                         }
 8652:                     }
 8653:                 }
 8654:                 unless ($changes{$itemid}) {
 8655:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
 8656:                         if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
 8657:                             if (ref($confhash{$itemid}{$key}) eq 'HASH') {
 8658:                                 foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
 8659:                                     unless (exists($confhash{$itemid}{$key}{$innerkey})) {
 8660:                                         $changes{$itemid} = 1;
 8661:                                         last;
 8662:                                     }
 8663:                                 }
 8664:                             } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
 8665:                                 $changes{$itemid} = 1;
 8666:                             }
 8667:                         }
 8668:                         last if ($changes{$itemid});
 8669:                     }
 8670:                 }
 8671:             }
 8672:         }
 8673:     }
 8674:     if (@allpos > 0) {
 8675:         my $idx = 0;
 8676:         foreach my $itemid (@allpos) {
 8677:             if ($itemid ne '') {
 8678:                 $confhash{$itemid}{'order'} = $idx;
 8679:                 if (ref($domconfig{$action}) eq 'HASH') {
 8680:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
 8681:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
 8682:                             $changes{$itemid} = 1;
 8683:                         }
 8684:                     }
 8685:                 }
 8686:                 $idx ++;
 8687:             }
 8688:         }
 8689:     }
 8690:     my %ltitoolshash = (
 8691:                           $action => { %confhash }
 8692:                        );
 8693:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
 8694:                                              $dom);
 8695:     if ($putresult eq 'ok') {
 8696:         if (keys(%changes) > 0) {
 8697:             my $cachetime = 24*60*60;
 8698:             &Apache::lonnet::do_cache_new('ltitools',$dom,\%confhash,$cachetime);
 8699:             if (ref($lastactref) eq 'HASH') {
 8700:                 $lastactref->{'ltitools'} = 1;
 8701:             }
 8702:             $resulttext = &mt('Changes made:').'<ul>';
 8703:             my %bynum;
 8704:             foreach my $itemid (sort(keys(%changes))) {
 8705:                 my $position = $confhash{$itemid}{'order'};
 8706:                 $bynum{$position} = $itemid;
 8707:             }
 8708:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
 8709:                 my $itemid = $bynum{$pos}; 
 8710:                 if (ref($confhash{$itemid}) ne 'HASH') {
 8711:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
 8712:                 } else {
 8713:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
 8714:                     if ($confhash{$itemid}{'image'}) {
 8715:                         $resulttext .= '&nbsp;'.
 8716:                                        '<img src="'.$confhash{$itemid}{'image'}.'"'.
 8717:                                        ' alt="'.&mt('Tool Provider icon').'" />';
 8718:                     }
 8719:                     $resulttext .= '</li><ul>';
 8720:                     my $position = $pos + 1;
 8721:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
 8722:                     foreach my $item ('version','msgtype','url','key') {
 8723:                         if ($confhash{$itemid}{$item} ne '') {
 8724:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
 8725:                         }
 8726:                     }
 8727:                     if ($confhash{$itemid}{'secret'} ne '') {
 8728:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
 8729:                         my $num = length($confhash{$itemid}{'secret'});
 8730:                         $resulttext .= ('*'x$num).'</li>';
 8731:                     }
 8732:                     $resulttext .= '<li>'.&mt('Configurable in course:');
 8733:                     my @possconfig = ('label','title','target');
 8734:                     my $numconfig = 0; 
 8735:                     if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') { 
 8736:                         foreach my $item (@possconfig) {
 8737:                             if ($confhash{$itemid}{'crsconf'}{$item}) {
 8738:                                 $numconfig ++;
 8739:                                 $resulttext .= ' '.$lt{'crs'.$item};
 8740:                             }
 8741:                         }
 8742:                     }
 8743:                     if (!$numconfig) {
 8744:                         $resulttext .= &mt('None');
 8745:                     }
 8746:                     $resulttext .= '</li>';
 8747:                     foreach my $item ('passback','roster') {
 8748:                         $resulttext .= '<li>'.$lt{$item}.'&nbsp;';
 8749:                         if ($confhash{$itemid}{$item}) {
 8750:                             $resulttext .= &mt('Yes');
 8751:                         } else {
 8752:                             $resulttext .= &mt('No');
 8753:                         }
 8754:                         $resulttext .= '</li>';
 8755:                     }
 8756:                     if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
 8757:                         my $displaylist;
 8758:                         if ($confhash{$itemid}{'display'}{'target'}) {
 8759:                             $displaylist = &mt('Display target').':&nbsp;'.
 8760:                                            $confhash{$itemid}{'display'}{'target'}.',';
 8761:                         }
 8762:                         foreach my $size ('width','height') { 
 8763:                             if ($confhash{$itemid}{'display'}{$size}) {
 8764:                                 $displaylist .= ('&nbsp;'x2).$lt{$size}.':&nbsp;'.
 8765:                                                 $confhash{$itemid}{'display'}{$size}.',';
 8766:                             }
 8767:                         }
 8768:                         if ($displaylist) {
 8769:                             $displaylist =~ s/,$//;
 8770:                             $resulttext .= '<li>'.$displaylist.'</li>';
 8771:                         }
 8772:                     } 
 8773:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
 8774:                         my $fieldlist;
 8775:                         foreach my $field (@allfields) {
 8776:                             if ($confhash{$itemid}{'fields'}{$field}) {
 8777:                                 $fieldlist .= ('&nbsp;'x2).$lt{$field}.',';
 8778:                             }
 8779:                         }
 8780:                         if ($fieldlist) {
 8781:                             $fieldlist =~ s/,$//;
 8782:                             $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
 8783:                         }
 8784:                     }
 8785:                     if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
 8786:                         my $rolemaps;
 8787:                         foreach my $role (@courseroles) {
 8788:                             if ($confhash{$itemid}{'roles'}{$role}) {
 8789:                                 $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
 8790:                                              $confhash{$itemid}{'roles'}{$role}.',';
 8791:                             }
 8792:                         }
 8793:                         if ($rolemaps) {
 8794:                             $rolemaps =~ s/,$//; 
 8795:                             $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
 8796:                         }
 8797:                     }
 8798:                     if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
 8799:                         my $customlist;
 8800:                         if (keys(%{$confhash{$itemid}{'custom'}})) {
 8801:                             foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
 8802:                                 $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.('&nbsp;'x2);
 8803:                             } 
 8804:                         }
 8805:                         if ($customlist) {
 8806:                             $resulttext .= '<li>'.&mt('Custom items').':'.$customlist.'</li>';
 8807:                         }
 8808:                     } 
 8809:                     $resulttext .= '</ul></li>';
 8810:                 }
 8811:             }
 8812:             $resulttext .= '</ul>';
 8813:         } else {
 8814:             $resulttext = &mt('No changes made.');
 8815:         }
 8816:     } else {
 8817:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
 8818:     }
 8819:     if ($errors) {
 8820:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
 8821:                        $errors.'</ul>';
 8822:     }
 8823:     return $resulttext;
 8824: }
 8825: 
 8826: sub process_ltitools_image {
 8827:     my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
 8828:     my $filename = $env{'form.'.$caller.'.filename'};
 8829:     my ($error,$url);
 8830:     my ($width,$height) = (21,21);
 8831:     if ($configuserok eq 'ok') {
 8832:         if ($switchserver) {
 8833:             $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
 8834:                          $switchserver);
 8835:         } elsif ($author_ok eq 'ok') {
 8836:             my ($result,$imageurl,$madethumb) =
 8837:                 &publishlogo($r,'upload',$caller,$dom,$confname,
 8838:                              "ltitools/$itemid/icon",$width,$height);
 8839:             if ($result eq 'ok') {
 8840:                 if ($madethumb) {
 8841:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
 8842:                     my $imagethumb = "$path/tn-".$imagefile;
 8843:                     $url = $imagethumb;
 8844:                 } else {
 8845:                     $url = $imageurl;
 8846:                 }
 8847:             } else {
 8848:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
 8849:             }
 8850:         } else {
 8851:             $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);
 8852:         }
 8853:     } else {
 8854:         $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);
 8855:     }
 8856:     return ($url,$error);
 8857: }
 8858: 
 8859: sub get_ltitools_id {
 8860:     my ($cdom,$title) = @_;
 8861:     # get lock on ltitools db
 8862:     my $lockhash = {
 8863:                       lock => $env{'user.name'}.
 8864:                               ':'.$env{'user.domain'},
 8865:                    };
 8866:     my $tries = 0;
 8867:     my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
 8868:     my ($id,$error);
 8869:  
 8870:     while (($gotlock ne 'ok') && ($tries<10)) {
 8871:         $tries ++;
 8872:         sleep (0.1);
 8873:         $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
 8874:     }
 8875:     if ($gotlock eq 'ok') {
 8876:         my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
 8877:         if ($currids{'lock'}) {
 8878:             delete($currids{'lock'});
 8879:             if (keys(%currids)) {
 8880:                 my @curr = sort { $a <=> $b } keys(%currids);
 8881:                 if ($curr[-1] =~ /^\d+$/) {
 8882:                     $id = 1 + $curr[-1];
 8883:                 }
 8884:             } else {
 8885:                 $id = 1;
 8886:             }
 8887:             if ($id) {
 8888:                 unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
 8889:                     $error = 'nostore';
 8890:                 }
 8891:             } else {
 8892:                 $error = 'nonumber';
 8893:             }
 8894:         }
 8895:         my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
 8896:     } else {
 8897:         $error = 'nolock';
 8898:     }
 8899:     return ($id,$error);
 8900: }
 8901: 
 8902: sub modify_autoenroll {
 8903:     my ($dom,$lastactref,%domconfig) = @_;
 8904:     my ($resulttext,%changes);
 8905:     my %currautoenroll;
 8906:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8907:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
 8908:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
 8909:         }
 8910:     }
 8911:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 8912:     my %title = ( run => 'Auto-enrollment active',
 8913:                   sender => 'Sender for notification messages',
 8914:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)');
 8915:     my @offon = ('off','on');
 8916:     my $sender_uname = $env{'form.sender_uname'};
 8917:     my $sender_domain = $env{'form.sender_domain'};
 8918:     if ($sender_domain eq '') {
 8919:         $sender_uname = '';
 8920:     } elsif ($sender_uname eq '') {
 8921:         $sender_domain = '';
 8922:     }
 8923:     my $coowners = $env{'form.autoassign_coowners'};
 8924:     my %autoenrollhash =  (
 8925:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
 8926:                                        'sender_uname' => $sender_uname,
 8927:                                        'sender_domain' => $sender_domain,
 8928:                                        'co-owners' => $coowners,
 8929:                                 }
 8930:                      );
 8931:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
 8932:                                              $dom);
 8933:     if ($putresult eq 'ok') {
 8934:         if (exists($currautoenroll{'run'})) {
 8935:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
 8936:                  $changes{'run'} = 1;
 8937:              }
 8938:         } elsif ($autorun) {
 8939:             if ($env{'form.autoenroll_run'} ne '1') {
 8940:                  $changes{'run'} = 1;
 8941:             }
 8942:         }
 8943:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
 8944:             $changes{'sender'} = 1;
 8945:         }
 8946:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
 8947:             $changes{'sender'} = 1;
 8948:         }
 8949:         if ($currautoenroll{'co-owners'} ne '') {
 8950:             if ($currautoenroll{'co-owners'} ne $coowners) {
 8951:                 $changes{'coowners'} = 1;
 8952:             }
 8953:         } elsif ($coowners) {
 8954:             $changes{'coowners'} = 1;
 8955:         }      
 8956:         if (keys(%changes) > 0) {
 8957:             $resulttext = &mt('Changes made:').'<ul>';
 8958:             if ($changes{'run'}) {
 8959:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
 8960:             }
 8961:             if ($changes{'sender'}) {
 8962:                 if ($sender_uname eq '' || $sender_domain eq '') {
 8963:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
 8964:                 } else {
 8965:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
 8966:                 }
 8967:             }
 8968:             if ($changes{'coowners'}) {
 8969:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
 8970:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
 8971:                 if (ref($lastactref) eq 'HASH') {
 8972:                     $lastactref->{'domainconfig'} = 1;
 8973:                 }
 8974:             }
 8975:             $resulttext .= '</ul>';
 8976:         } else {
 8977:             $resulttext = &mt('No changes made to auto-enrollment settings');
 8978:         }
 8979:     } else {
 8980:         $resulttext = '<span class="LC_error">'.
 8981: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 8982:     }
 8983:     return $resulttext;
 8984: }
 8985: 
 8986: sub modify_autoupdate {
 8987:     my ($dom,%domconfig) = @_;
 8988:     my ($resulttext,%currautoupdate,%fields,%changes);
 8989:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
 8990:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
 8991:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
 8992:         }
 8993:     }
 8994:     my @offon = ('off','on');
 8995:     my %title = &Apache::lonlocal::texthash (
 8996:                    run => 'Auto-update:',
 8997:                    classlists => 'Updates to user information in classlists?'
 8998:                 );
 8999:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 9000:     my %fieldtitles = &Apache::lonlocal::texthash (
 9001:                         id => 'Student/Employee ID',
 9002:                         permanentemail => 'E-mail address',
 9003:                         lastname => 'Last Name',
 9004:                         firstname => 'First Name',
 9005:                         middlename => 'Middle Name',
 9006:                         generation => 'Generation',
 9007:                       );
 9008:     $othertitle = &mt('All users');
 9009:     if (keys(%{$usertypes}) >  0) {
 9010:         $othertitle = &mt('Other users');
 9011:     }
 9012:     foreach my $key (keys(%env)) {
 9013:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
 9014:             my ($usertype,$item) = ($1,$2);
 9015:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
 9016:                 if ($usertype eq 'default') {   
 9017:                     push(@{$fields{$1}},$2);
 9018:                 } elsif (ref($types) eq 'ARRAY') {
 9019:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
 9020:                         push(@{$fields{$1}},$2);
 9021:                     }
 9022:                 }
 9023:             }
 9024:         }
 9025:     }
 9026:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
 9027:     @lockablenames = sort(@lockablenames);
 9028:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
 9029:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
 9030:         if (@changed) {
 9031:             $changes{'lockablenames'} = 1;
 9032:         }
 9033:     } else {
 9034:         if (@lockablenames) {
 9035:             $changes{'lockablenames'} = 1;
 9036:         }
 9037:     }
 9038:     my %updatehash = (
 9039:                       autoupdate => { run => $env{'form.autoupdate_run'},
 9040:                                       classlists => $env{'form.classlists'},
 9041:                                       fields => {%fields},
 9042:                                       lockablenames => \@lockablenames,
 9043:                                     }
 9044:                      );
 9045:     foreach my $key (keys(%currautoupdate)) {
 9046:         if (($key eq 'run') || ($key eq 'classlists')) {
 9047:             if (exists($updatehash{autoupdate}{$key})) {
 9048:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
 9049:                     $changes{$key} = 1;
 9050:                 }
 9051:             }
 9052:         } elsif ($key eq 'fields') {
 9053:             if (ref($currautoupdate{$key}) eq 'HASH') {
 9054:                 foreach my $item (@{$types},'default') {
 9055:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
 9056:                         my $change = 0;
 9057:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
 9058:                             if (!exists($fields{$item})) {
 9059:                                 $change = 1;
 9060:                                 last;
 9061:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
 9062:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
 9063:                                     $change = 1;
 9064:                                     last;
 9065:                                 }
 9066:                             }
 9067:                         }
 9068:                         if ($change) {
 9069:                             push(@{$changes{$key}},$item);
 9070:                         }
 9071:                     } 
 9072:                 }
 9073:             }
 9074:         } elsif ($key eq 'lockablenames') {
 9075:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
 9076:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
 9077:                 if (@changed) {
 9078:                     $changes{'lockablenames'} = 1;
 9079:                 }
 9080:             } else {
 9081:                 if (@lockablenames) {
 9082:                     $changes{'lockablenames'} = 1;
 9083:                 }
 9084:             }
 9085:         }
 9086:     }
 9087:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
 9088:         if (@lockablenames) {
 9089:             $changes{'lockablenames'} = 1;
 9090:         }
 9091:     }
 9092:     foreach my $item (@{$types},'default') {
 9093:         if (defined($fields{$item})) {
 9094:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
 9095:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
 9096:                     my $change = 0;
 9097:                     if (ref($fields{$item}) eq 'ARRAY') {
 9098:                         foreach my $type (@{$fields{$item}}) {
 9099:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
 9100:                                 $change = 1;
 9101:                                 last;
 9102:                             }
 9103:                         }
 9104:                     }
 9105:                     if ($change) {
 9106:                         push(@{$changes{'fields'}},$item);
 9107:                     }
 9108:                 } else {
 9109:                     push(@{$changes{'fields'}},$item);
 9110:                 }
 9111:             } else {
 9112:                 push(@{$changes{'fields'}},$item);
 9113:             }
 9114:         }
 9115:     }
 9116:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
 9117:                                              $dom);
 9118:     if ($putresult eq 'ok') {
 9119:         if (keys(%changes) > 0) {
 9120:             $resulttext = &mt('Changes made:').'<ul>';
 9121:             foreach my $key (sort(keys(%changes))) {
 9122:                 if ($key eq 'lockablenames') {
 9123:                     $resulttext .= '<li>';
 9124:                     if (@lockablenames) {
 9125:                         $usertypes->{'default'} = $othertitle;
 9126:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
 9127:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
 9128:                     } else {
 9129:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
 9130:                     }
 9131:                     $resulttext .= '</li>';
 9132:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
 9133:                     foreach my $item (@{$changes{$key}}) {
 9134:                         my @newvalues;
 9135:                         foreach my $type (@{$fields{$item}}) {
 9136:                             push(@newvalues,$fieldtitles{$type});
 9137:                         }
 9138:                         my $newvaluestr;
 9139:                         if (@newvalues > 0) {
 9140:                             $newvaluestr = join(', ',@newvalues);
 9141:                         } else {
 9142:                             $newvaluestr = &mt('none');
 9143:                         }
 9144:                         if ($item eq 'default') {
 9145:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
 9146:                         } else {
 9147:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
 9148:                         }
 9149:                     }
 9150:                 } else {
 9151:                     my $newvalue;
 9152:                     if ($key eq 'run') {
 9153:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
 9154:                     } else {
 9155:                         $newvalue = $offon[$env{'form.'.$key}];
 9156:                     }
 9157:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
 9158:                 }
 9159:             }
 9160:             $resulttext .= '</ul>';
 9161:         } else {
 9162:             $resulttext = &mt('No changes made to autoupdates');
 9163:         }
 9164:     } else {
 9165:         $resulttext = '<span class="LC_error">'.
 9166: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 9167:     }
 9168:     return $resulttext;
 9169: }
 9170: 
 9171: sub modify_autocreate {
 9172:     my ($dom,%domconfig) = @_;
 9173:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
 9174:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
 9175:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
 9176:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
 9177:         }
 9178:     }
 9179:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
 9180:                  req => 'Auto-creation of validated requests for official courses',
 9181:                  xmldc => 'Identity of course creator of courses from XML files',
 9182:                );
 9183:     my @types = ('xml','req');
 9184:     foreach my $item (@types) {
 9185:         $newvals{$item} = $env{'form.autocreate_'.$item};
 9186:         $newvals{$item} =~ s/\D//g;
 9187:         $newvals{$item} = 0 if ($newvals{$item} eq '');
 9188:     }
 9189:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
 9190:     my %domcoords = &get_active_dcs($dom);
 9191:     unless (exists($domcoords{$newvals{'xmldc'}})) {
 9192:         $newvals{'xmldc'} = '';
 9193:     } 
 9194:     %autocreatehash =  (
 9195:                         autocreate => { xml => $newvals{'xml'},
 9196:                                         req => $newvals{'req'},
 9197:                                       }
 9198:                        );
 9199:     if ($newvals{'xmldc'} ne '') {
 9200:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
 9201:     }
 9202:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
 9203:                                              $dom);
 9204:     if ($putresult eq 'ok') {
 9205:         my @items = @types;
 9206:         if ($newvals{'xml'}) {
 9207:             push(@items,'xmldc');
 9208:         }
 9209:         foreach my $item (@items) {
 9210:             if (exists($currautocreate{$item})) {
 9211:                 if ($currautocreate{$item} ne $newvals{$item}) {
 9212:                     $changes{$item} = 1;
 9213:                 }
 9214:             } elsif ($newvals{$item}) {
 9215:                 $changes{$item} = 1;
 9216:             }
 9217:         }
 9218:         if (keys(%changes) > 0) {
 9219:             my @offon = ('off','on'); 
 9220:             $resulttext = &mt('Changes made:').'<ul>';
 9221:             foreach my $item (@types) {
 9222:                 if ($changes{$item}) {
 9223:                     my $newtxt = $offon[$newvals{$item}];
 9224:                     $resulttext .= '<li>'.
 9225:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
 9226:                                        '<b>','</b>').
 9227:                                    '</li>';
 9228:                 }
 9229:             }
 9230:             if ($changes{'xmldc'}) {
 9231:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
 9232:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
 9233:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
 9234:             }
 9235:             $resulttext .= '</ul>';
 9236:         } else {
 9237:             $resulttext = &mt('No changes made to auto-creation settings');
 9238:         }
 9239:     } else {
 9240:         $resulttext = '<span class="LC_error">'.
 9241:             &mt('An error occurred: [_1]',$putresult).'</span>';
 9242:     }
 9243:     return $resulttext;
 9244: }
 9245: 
 9246: sub modify_directorysrch {
 9247:     my ($dom,%domconfig) = @_;
 9248:     my ($resulttext,%changes);
 9249:     my %currdirsrch;
 9250:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 9251:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
 9252:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
 9253:         }
 9254:     }
 9255:     my %title = ( available => 'Directory search available',
 9256:                   localonly => 'Other domains can search',
 9257:                   searchby => 'Search types',
 9258:                   searchtypes => 'Search latitude');
 9259:     my @offon = ('off','on');
 9260:     my @otherdoms = ('Yes','No');
 9261: 
 9262:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
 9263:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
 9264:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
 9265: 
 9266:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 9267:     if (keys(%{$usertypes}) == 0) {
 9268:         @cansearch = ('default');
 9269:     } else {
 9270:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
 9271:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
 9272:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
 9273:                     push(@{$changes{'cansearch'}},$type);
 9274:                 }
 9275:             }
 9276:             foreach my $type (@cansearch) {
 9277:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
 9278:                     push(@{$changes{'cansearch'}},$type);
 9279:                 }
 9280:             }
 9281:         } else {
 9282:             push(@{$changes{'cansearch'}},@cansearch);
 9283:         }
 9284:     }
 9285: 
 9286:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
 9287:         foreach my $by (@{$currdirsrch{'searchby'}}) {
 9288:             if (!grep(/^\Q$by\E$/,@searchby)) {
 9289:                 push(@{$changes{'searchby'}},$by);
 9290:             }
 9291:         }
 9292:         foreach my $by (@searchby) {
 9293:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
 9294:                 push(@{$changes{'searchby'}},$by);
 9295:             }
 9296:         }
 9297:     } else {
 9298:         push(@{$changes{'searchby'}},@searchby);
 9299:     }
 9300: 
 9301:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
 9302:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
 9303:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
 9304:                 push(@{$changes{'searchtypes'}},$type);
 9305:             }
 9306:         }
 9307:         foreach my $type (@searchtypes) {
 9308:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
 9309:                 push(@{$changes{'searchtypes'}},$type);
 9310:             }
 9311:         }
 9312:     } else {
 9313:         if (exists($currdirsrch{'searchtypes'})) {
 9314:             foreach my $type (@searchtypes) {  
 9315:                 if ($type ne $currdirsrch{'searchtypes'}) { 
 9316:                     push(@{$changes{'searchtypes'}},$type);
 9317:                 }
 9318:             }
 9319:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
 9320:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
 9321:             }   
 9322:         } else {
 9323:             push(@{$changes{'searchtypes'}},@searchtypes); 
 9324:         }
 9325:     }
 9326: 
 9327:     my %dirsrch_hash =  (
 9328:             directorysrch => { available => $env{'form.dirsrch_available'},
 9329:                                cansearch => \@cansearch,
 9330:                                localonly => $env{'form.dirsrch_localonly'},
 9331:                                searchby => \@searchby,
 9332:                                searchtypes => \@searchtypes,
 9333:                              }
 9334:             );
 9335:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
 9336:                                              $dom);
 9337:     if ($putresult eq 'ok') {
 9338:         if (exists($currdirsrch{'available'})) {
 9339:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
 9340:                  $changes{'available'} = 1;
 9341:              }
 9342:         } else {
 9343:             if ($env{'form.dirsrch_available'} eq '1') {
 9344:                 $changes{'available'} = 1;
 9345:             }
 9346:         }
 9347:         if (exists($currdirsrch{'localonly'})) {
 9348:              if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_localonly'}) {
 9349:                  $changes{'localonly'} = 1;
 9350:              }
 9351:         } else {
 9352:             if ($env{'form.dirsrch_localonly'} eq '1') {
 9353:                 $changes{'localonly'} = 1;
 9354:             }
 9355:         }
 9356:         if (keys(%changes) > 0) {
 9357:             $resulttext = &mt('Changes made:').'<ul>';
 9358:             if ($changes{'available'}) {
 9359:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
 9360:             }
 9361:             if ($changes{'localonly'}) {
 9362:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_localonly'}]").'</li>';
 9363:             }
 9364: 
 9365:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
 9366:                 my $chgtext;
 9367:                 if (ref($usertypes) eq 'HASH') {
 9368:                     if (keys(%{$usertypes}) > 0) {
 9369:                         foreach my $type (@{$types}) {
 9370:                             if (grep(/^\Q$type\E$/,@cansearch)) {
 9371:                                 $chgtext .= $usertypes->{$type}.'; ';
 9372:                             }
 9373:                         }
 9374:                         if (grep(/^default$/,@cansearch)) {
 9375:                             $chgtext .= $othertitle;
 9376:                         } else {
 9377:                             $chgtext =~ s/\; $//;
 9378:                         }
 9379:                         $resulttext .=
 9380:                             '<li>'.
 9381:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
 9382:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
 9383:                             '</li>';
 9384:                     }
 9385:                 }
 9386:             }
 9387:             if (ref($changes{'searchby'}) eq 'ARRAY') {
 9388:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
 9389:                 my $chgtext;
 9390:                 foreach my $type (@{$titleorder}) {
 9391:                     if (grep(/^\Q$type\E$/,@searchby)) {
 9392:                         if (defined($searchtitles->{$type})) {
 9393:                             $chgtext .= $searchtitles->{$type}.'; ';
 9394:                         }
 9395:                     }
 9396:                 }
 9397:                 $chgtext =~ s/\; $//;
 9398:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
 9399:             }
 9400:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
 9401:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
 9402:                 my $chgtext;
 9403:                 foreach my $type (@{$srchtypeorder}) {
 9404:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
 9405:                         if (defined($srchtypes_desc->{$type})) {
 9406:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
 9407:                         }
 9408:                     }
 9409:                 }
 9410:                 $chgtext =~ s/\; $//;
 9411:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
 9412:             }
 9413:             $resulttext .= '</ul>';
 9414:         } else {
 9415:             $resulttext = &mt('No changes made to institution directory search settings');
 9416:         }
 9417:     } else {
 9418:         $resulttext = '<span class="LC_error">'.
 9419:                       &mt('An error occurred: [_1]',$putresult).'</span>';
 9420:     }
 9421:     return $resulttext;
 9422: }
 9423: 
 9424: sub modify_contacts {
 9425:     my ($dom,$lastactref,%domconfig) = @_;
 9426:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
 9427:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 9428:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
 9429:             $currsetting{$key} = $domconfig{'contacts'}{$key};
 9430:         }
 9431:     }
 9432:     my (%others,%to,%bcc);
 9433:     my @contacts = ('supportemail','adminemail');
 9434:     my @mailings = ('errormail','packagesmail','helpdeskmail','lonstatusmail',
 9435:                     'requestsmail','updatesmail','idconflictsmail');
 9436:     my @toggles = ('reporterrors','reportupdates');
 9437:     foreach my $type (@mailings) {
 9438:         @{$newsetting{$type}} = 
 9439:             &Apache::loncommon::get_env_multiple('form.'.$type);
 9440:         foreach my $item (@contacts) {
 9441:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
 9442:                 $contacts_hash{contacts}{$type}{$item} = 1;
 9443:             } else {
 9444:                 $contacts_hash{contacts}{$type}{$item} = 0;
 9445:             }
 9446:         }  
 9447:         $others{$type} = $env{'form.'.$type.'_others'};
 9448:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
 9449:         if ($type eq 'helpdeskmail') {
 9450:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
 9451:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
 9452:         }
 9453:     }
 9454:     foreach my $item (@contacts) {
 9455:         $to{$item} = $env{'form.'.$item};
 9456:         $contacts_hash{'contacts'}{$item} = $to{$item};
 9457:     }
 9458:     foreach my $item (@toggles) {
 9459:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
 9460:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
 9461:         }
 9462:     }
 9463:     if (keys(%currsetting) > 0) {
 9464:         foreach my $item (@contacts) {
 9465:             if ($to{$item} ne $currsetting{$item}) {
 9466:                 $changes{$item} = 1;
 9467:             }
 9468:         }
 9469:         foreach my $type (@mailings) {
 9470:             foreach my $item (@contacts) {
 9471:                 if (ref($currsetting{$type}) eq 'HASH') {
 9472:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
 9473:                         push(@{$changes{$type}},$item);
 9474:                     }
 9475:                 } else {
 9476:                     push(@{$changes{$type}},@{$newsetting{$type}});
 9477:                 }
 9478:             }
 9479:             if ($others{$type} ne $currsetting{$type}{'others'}) {
 9480:                 push(@{$changes{$type}},'others');
 9481:             }
 9482:             if ($type eq 'helpdeskmail') {   
 9483:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
 9484:                     push(@{$changes{$type}},'bcc'); 
 9485:                 }
 9486:             }
 9487:         }
 9488:     } else {
 9489:         my %default;
 9490:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 9491:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 9492:         $default{'errormail'} = 'adminemail';
 9493:         $default{'packagesmail'} = 'adminemail';
 9494:         $default{'helpdeskmail'} = 'supportemail';
 9495:         $default{'lonstatusmail'} = 'adminemail';
 9496:         $default{'requestsmail'} = 'adminemail';
 9497:         $default{'updatesmail'} = 'adminemail';
 9498:         foreach my $item (@contacts) {
 9499:            if ($to{$item} ne $default{$item}) {
 9500:               $changes{$item} = 1;
 9501:            }
 9502:         }
 9503:         foreach my $type (@mailings) {
 9504:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
 9505:                
 9506:                 push(@{$changes{$type}},@{$newsetting{$type}});
 9507:             }
 9508:             if ($others{$type} ne '') {
 9509:                 push(@{$changes{$type}},'others');
 9510:             }
 9511:             if ($type eq 'helpdeskmail') {
 9512:                 if ($bcc{$type} ne '') {
 9513:                     push(@{$changes{$type}},'bcc');
 9514:                 }
 9515:             }
 9516:         }
 9517:     }
 9518:     foreach my $item (@toggles) {
 9519:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
 9520:             $changes{$item} = 1;
 9521:         } elsif ((!$env{'form.'.$item}) &&
 9522:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
 9523:             $changes{$item} = 1;
 9524:         }
 9525:     }
 9526:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
 9527:                                              $dom);
 9528:     if ($putresult eq 'ok') {
 9529:         if (keys(%changes) > 0) {
 9530:             &Apache::loncommon::devalidate_domconfig_cache($dom);
 9531:             if (ref($lastactref) eq 'HASH') {
 9532:                 $lastactref->{'domainconfig'} = 1;
 9533:             }
 9534:             my ($titles,$short_titles)  = &contact_titles();
 9535:             $resulttext = &mt('Changes made:').'<ul>';
 9536:             foreach my $item (@contacts) {
 9537:                 if ($changes{$item}) {
 9538:                     $resulttext .= '<li>'.$titles->{$item}.
 9539:                                     &mt(' set to: ').
 9540:                                     '<span class="LC_cusr_emph">'.
 9541:                                     $to{$item}.'</span></li>';
 9542:                 }
 9543:             }
 9544:             foreach my $type (@mailings) {
 9545:                 if (ref($changes{$type}) eq 'ARRAY') {
 9546:                     $resulttext .= '<li>'.$titles->{$type}.': ';
 9547:                     my @text;
 9548:                     foreach my $item (@{$newsetting{$type}}) {
 9549:                         push(@text,$short_titles->{$item});
 9550:                     }
 9551:                     if ($others{$type} ne '') {
 9552:                         push(@text,$others{$type});
 9553:                     }
 9554:                     $resulttext .= '<span class="LC_cusr_emph">'.
 9555:                                    join(', ',@text).'</span>';
 9556:                     if ($type eq 'helpdeskmail') {
 9557:                         if ($bcc{$type} ne '') {
 9558:                             $resulttext .= '&nbsp;'.&mt('with Bcc to').': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
 9559:                         }
 9560:                     }
 9561:                     $resulttext .= '</li>';
 9562:                 }
 9563:             }
 9564:             my @offon = ('off','on');
 9565:             if ($changes{'reporterrors'}) {
 9566:                 $resulttext .= '<li>'.
 9567:                                &mt('E-mail error reports to [_1] set to "'.
 9568:                                    $offon[$env{'form.reporterrors'}].'".',
 9569:                                    &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 9570:                                        &mt('LON-CAPA core group - MSU'),600,500)).
 9571:                                '</li>';
 9572:             }
 9573:             if ($changes{'reportupdates'}) {
 9574:                 $resulttext .= '<li>'.
 9575:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
 9576:                                     $offon[$env{'form.reportupdates'}].'".',
 9577:                                     &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 9578:                                         &mt('LON-CAPA core group - MSU'),600,500)).
 9579:                                 '</li>';
 9580:             }
 9581:             $resulttext .= '</ul>';
 9582:         } else {
 9583:             $resulttext = &mt('No changes made to contact information');
 9584:         }
 9585:     } else {
 9586:         $resulttext = '<span class="LC_error">'.
 9587:             &mt('An error occurred: [_1].',$putresult).'</span>';
 9588:     }
 9589:     return $resulttext;
 9590: }
 9591: 
 9592: sub modify_usercreation {
 9593:     my ($dom,%domconfig) = @_;
 9594:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
 9595:     my $warningmsg;
 9596:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9597:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
 9598:             if ($key eq 'cancreate') {
 9599:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
 9600:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
 9601:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
 9602:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
 9603:                             ($item eq 'recaptchaversion')) {
 9604:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
 9605:                         } else {
 9606:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
 9607:                         }
 9608:                     }
 9609:                 }
 9610:             } elsif ($key eq 'email_rule') {
 9611:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
 9612:             } else {
 9613:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
 9614:             }
 9615:         }
 9616:     }
 9617:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
 9618:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
 9619:     my @contexts = ('author','course','requestcrs');
 9620:     foreach my $item(@contexts) {
 9621:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
 9622:     }
 9623:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
 9624:         foreach my $item (@contexts) {
 9625:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
 9626:                 push(@{$changes{'cancreate'}},$item);
 9627:             }
 9628:         }
 9629:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
 9630:         foreach my $item (@contexts) {
 9631:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
 9632:                 if ($cancreate{$item} ne 'any') {
 9633:                     push(@{$changes{'cancreate'}},$item);
 9634:                 }
 9635:             } else {
 9636:                 if ($cancreate{$item} ne 'none') {
 9637:                     push(@{$changes{'cancreate'}},$item);
 9638:                 }
 9639:             }
 9640:         }
 9641:     } else {
 9642:         foreach my $item (@contexts)  {
 9643:             push(@{$changes{'cancreate'}},$item);
 9644:         }
 9645:     }
 9646: 
 9647:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
 9648:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
 9649:             if (!grep(/^\Q$type\E$/,@username_rule)) {
 9650:                 push(@{$changes{'username_rule'}},$type);
 9651:             }
 9652:         }
 9653:         foreach my $type (@username_rule) {
 9654:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
 9655:                 push(@{$changes{'username_rule'}},$type);
 9656:             }
 9657:         }
 9658:     } else {
 9659:         push(@{$changes{'username_rule'}},@username_rule);
 9660:     }
 9661: 
 9662:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
 9663:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
 9664:             if (!grep(/^\Q$type\E$/,@id_rule)) {
 9665:                 push(@{$changes{'id_rule'}},$type);
 9666:             }
 9667:         }
 9668:         foreach my $type (@id_rule) {
 9669:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
 9670:                 push(@{$changes{'id_rule'}},$type);
 9671:             }
 9672:         }
 9673:     } else {
 9674:         push(@{$changes{'id_rule'}},@id_rule);
 9675:     }
 9676: 
 9677:     my @authen_contexts = ('author','course','domain');
 9678:     my @authtypes = ('int','krb4','krb5','loc');
 9679:     my %authhash;
 9680:     foreach my $item (@authen_contexts) {
 9681:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
 9682:         foreach my $auth (@authtypes) {
 9683:             if (grep(/^\Q$auth\E$/,@authallowed)) {
 9684:                 $authhash{$item}{$auth} = 1;
 9685:             } else {
 9686:                 $authhash{$item}{$auth} = 0;
 9687:             }
 9688:         }
 9689:     }
 9690:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
 9691:         foreach my $item (@authen_contexts) {
 9692:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
 9693:                 foreach my $auth (@authtypes) {
 9694:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
 9695:                         push(@{$changes{'authtypes'}},$item);
 9696:                         last;
 9697:                     }
 9698:                 }
 9699:             }
 9700:         }
 9701:     } else {
 9702:         foreach my $item (@authen_contexts) {
 9703:             push(@{$changes{'authtypes'}},$item);
 9704:         }
 9705:     }
 9706: 
 9707:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
 9708:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
 9709:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
 9710:     $save_usercreate{'id_rule'} = \@id_rule;
 9711:     $save_usercreate{'username_rule'} = \@username_rule,
 9712:     $save_usercreate{'authtypes'} = \%authhash;
 9713: 
 9714:     my %usercreation_hash =  (
 9715:         usercreation     => \%save_usercreate,
 9716:     );
 9717: 
 9718:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
 9719:                                              $dom);
 9720: 
 9721:     if ($putresult eq 'ok') {
 9722:         if (keys(%changes) > 0) {
 9723:             $resulttext = &mt('Changes made:').'<ul>';
 9724:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
 9725:                 my %lt = &usercreation_types();
 9726:                 foreach my $type (@{$changes{'cancreate'}}) {
 9727:                     my $chgtext = $lt{$type}.', ';
 9728:                     if ($cancreate{$type} eq 'none') {
 9729:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
 9730:                     } elsif ($cancreate{$type} eq 'any') {
 9731:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
 9732:                     } elsif ($cancreate{$type} eq 'official') {
 9733:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
 9734:                     } elsif ($cancreate{$type} eq 'unofficial') {
 9735:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
 9736:                     }
 9737:                     $resulttext .= '<li>'.$chgtext.'</li>';
 9738:                 }
 9739:             }
 9740:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
 9741:                 my ($rules,$ruleorder) = 
 9742:                     &Apache::lonnet::inst_userrules($dom,'username');
 9743:                 my $chgtext = '<ul>';
 9744:                 foreach my $type (@username_rule) {
 9745:                     if (ref($rules->{$type}) eq 'HASH') {
 9746:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
 9747:                     }
 9748:                 }
 9749:                 $chgtext .= '</ul>';
 9750:                 if (@username_rule > 0) {
 9751:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
 9752:                 } else {
 9753:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
 9754:                 }
 9755:             }
 9756:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
 9757:                 my ($idrules,$idruleorder) = 
 9758:                     &Apache::lonnet::inst_userrules($dom,'id');
 9759:                 my $chgtext = '<ul>';
 9760:                 foreach my $type (@id_rule) {
 9761:                     if (ref($idrules->{$type}) eq 'HASH') {
 9762:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
 9763:                     }
 9764:                 }
 9765:                 $chgtext .= '</ul>';
 9766:                 if (@id_rule > 0) {
 9767:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
 9768:                 } else {
 9769:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
 9770:                 }
 9771:             }
 9772:             my %authname = &authtype_names();
 9773:             my %context_title = &context_names();
 9774:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
 9775:                 my $chgtext = '<ul>';
 9776:                 foreach my $type (@{$changes{'authtypes'}}) {
 9777:                     my @allowed;
 9778:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
 9779:                     foreach my $auth (@authtypes) {
 9780:                         if ($authhash{$type}{$auth}) {
 9781:                             push(@allowed,$authname{$auth});
 9782:                         }
 9783:                     }
 9784:                     if (@allowed > 0) {
 9785:                         $chgtext .= join(', ',@allowed).'</li>';
 9786:                     } else {
 9787:                         $chgtext .= &mt('none').'</li>';
 9788:                     }
 9789:                 }
 9790:                 $chgtext .= '</ul>';
 9791:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
 9792:                 $resulttext .= '</li>';
 9793:             }
 9794:             $resulttext .= '</ul>';
 9795:         } else {
 9796:             $resulttext = &mt('No changes made to user creation settings');
 9797:         }
 9798:     } else {
 9799:         $resulttext = '<span class="LC_error">'.
 9800:             &mt('An error occurred: [_1]',$putresult).'</span>';
 9801:     }
 9802:     if ($warningmsg ne '') {
 9803:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
 9804:     }
 9805:     return $resulttext;
 9806: }
 9807: 
 9808: sub modify_selfcreation {
 9809:     my ($dom,%domconfig) = @_;
 9810:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%changes,%cancreate);
 9811:     my (%save_usercreate,%save_usermodify);
 9812:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 9813:     if (ref($types) eq 'ARRAY') {
 9814:         $usertypes->{'default'} = $othertitle;
 9815:         push(@{$types},'default');
 9816:     }
 9817: #
 9818: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
 9819: #
 9820:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9821:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
 9822:             if ($key eq 'cancreate') {
 9823:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
 9824:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
 9825:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
 9826:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') || 
 9827:                             ($item eq 'recaptchaversion') ||
 9828:                             ($item eq 'emailusername') || ($item eq 'notify') ||
 9829:                             ($item eq 'selfcreateprocessing') || ($item eq 'shibenv')) {
 9830:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
 9831:                         } else {
 9832:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
 9833:                         }
 9834:                     }
 9835:                 }
 9836:             } elsif ($key eq 'email_rule') {
 9837:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
 9838:             } else {
 9839:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
 9840:             }
 9841:         }
 9842:     }
 9843: #
 9844: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
 9845: #
 9846:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
 9847:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
 9848:             if ($key eq 'selfcreate') {
 9849:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
 9850:             } else {
 9851:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
 9852:             }
 9853:         }
 9854:     }
 9855: 
 9856:     my @contexts = ('selfcreate');
 9857:     @{$cancreate{'selfcreate'}} = ();
 9858:     %{$cancreate{'emailusername'}} = ();
 9859:     @{$cancreate{'statustocreate'}} = ();
 9860:     %{$cancreate{'selfcreateprocessing'}} = ();
 9861:     %{$cancreate{'shibenv'}} = ();
 9862:     my %selfcreatetypes = (
 9863:                              sso   => 'users authenticated by institutional single sign on',
 9864:                              login => 'users authenticated by institutional log-in',
 9865:                              email => 'users who provide a valid e-mail address for use as username',
 9866:                           );
 9867: #
 9868: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
 9869: # is permitted.
 9870: #
 9871: 
 9872:     my @statuses;
 9873:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 9874:         if (ref($domconfig{'inststatus'}{'inststatusguest'}) eq 'ARRAY') {
 9875:             @statuses = @{$domconfig{'inststatus'}{'inststatusguest'}};
 9876:         }
 9877:     }
 9878:     push(@statuses,'default');
 9879: 
 9880:     foreach my $item ('login','sso','email') {
 9881:         if ($item eq 'email') {
 9882:             if ($env{'form.cancreate_email'}) {
 9883:                 push(@{$cancreate{'selfcreate'}},'email');
 9884:                 push(@contexts,'selfcreateprocessing');
 9885:                 foreach my $type (@statuses) {
 9886:                     if ($type eq 'default') {
 9887:                         $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess'};
 9888:                     } else { 
 9889:                         $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
 9890:                     }
 9891:                 }
 9892:             }
 9893:         } else {
 9894:             if ($env{'form.cancreate_'.$item}) {
 9895:                 push(@{$cancreate{'selfcreate'}},$item);
 9896:             }
 9897:         }
 9898:     }
 9899:     my (@email_rule,%userinfo,%savecaptcha);
 9900:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 9901: #
 9902: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
 9903: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
 9904: #
 9905: 
 9906:     if ($env{'form.cancreate_email'}) {
 9907:         push(@contexts,'emailusername');
 9908:         if (ref($types) eq 'ARRAY') {
 9909:             foreach my $type (@{$types}) {
 9910:                 if (ref($infofields) eq 'ARRAY') {
 9911:                     foreach my $field (@{$infofields}) {
 9912:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
 9913:                             $cancreate{'emailusername'}{$type}{$field} = $1;
 9914:                         }
 9915:                     }
 9916:                 }
 9917:             }
 9918:         }
 9919: #
 9920: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
 9921: # queued requests for self-creation of account using e-mail address as username
 9922: #
 9923: 
 9924:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
 9925:         @approvalnotify = sort(@approvalnotify);
 9926:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
 9927:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
 9928:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
 9929:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
 9930:                     push(@{$changes{'cancreate'}},'notify');
 9931:                 }
 9932:             } else {
 9933:                 if ($cancreate{'notify'}{'approval'}) {
 9934:                     push(@{$changes{'cancreate'}},'notify');
 9935:                 }
 9936:             }
 9937:         } elsif ($cancreate{'notify'}{'approval'}) {
 9938:             push(@{$changes{'cancreate'}},'notify');
 9939:         }
 9940: 
 9941: #
 9942: # Retrieve rules (if any) governing types of e-mail address which may be used as a username
 9943: #
 9944:         @email_rule = &Apache::loncommon::get_env_multiple('form.email_rule');
 9945:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
 9946:         if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
 9947:             if (@{$curr_usercreation{'email_rule'}} > 0) {
 9948:                 foreach my $type (@{$curr_usercreation{'email_rule'}}) {
 9949:                     if (!grep(/^\Q$type\E$/,@email_rule)) {
 9950:                         push(@{$changes{'email_rule'}},$type);
 9951:                     }
 9952:                 }
 9953:             }
 9954:             if (@email_rule > 0) {
 9955:                 foreach my $type (@email_rule) {
 9956:                     if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'email_rule'}})) {
 9957:                         push(@{$changes{'email_rule'}},$type);
 9958:                     }
 9959:                 }
 9960:             }
 9961:         } elsif (@email_rule > 0) {
 9962:             push(@{$changes{'email_rule'}},@email_rule);
 9963:         }
 9964:     }
 9965: #  
 9966: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
 9967: # institutional log-in.
 9968: #
 9969:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
 9970:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 9971:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
 9972:                ($domdefaults{'auth_def'} eq 'localauth'))) {
 9973:             $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.').' '.
 9974:                           &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.');
 9975:         }
 9976:     }
 9977:     my @fields = ('lastname','firstname','middlename','generation',
 9978:                   'permanentemail','id');
 9979:     my @shibfields = (@fields,'inststatus');
 9980:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 9981: #
 9982: # Where usernames may created for institutional log-in and/or institutional single sign on:
 9983: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
 9984: # may self-create accounts 
 9985: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
 9986: # which the user may supply, if institutional data is unavailable.
 9987: #
 9988:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
 9989:         if (ref($types) eq 'ARRAY') {
 9990:             if (@{$types} > 1) {
 9991:                 @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
 9992:                 push(@contexts,'statustocreate');
 9993:             } else {
 9994:                 undef($cancreate{'statustocreate'});
 9995:             } 
 9996:             foreach my $type (@{$types}) {
 9997:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
 9998:                 foreach my $field (@fields) {
 9999:                     if (grep(/^\Q$field\E$/,@modifiable)) {
10000:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
10001:                     } else {
10002:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
10003:                     }
10004:                 }
10005:             }
10006:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
10007:                 foreach my $type (@{$types}) {
10008:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
10009:                         foreach my $field (@fields) {
10010:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
10011:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
10012:                                 push(@{$changes{'selfcreate'}},$type);
10013:                                 last;
10014:                             }
10015:                         }
10016:                     }
10017:                 }
10018:             } else {
10019:                 foreach my $type (@{$types}) {
10020:                     push(@{$changes{'selfcreate'}},$type);
10021:                 }
10022:             }
10023:         }
10024:         foreach my $field (@shibfields) {
10025:             if ($env{'form.shibenv_'.$field} ne '') {
10026:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
10027:             }
10028:         }
10029:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
10030:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
10031:                 foreach my $field (@shibfields) {
10032:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
10033:                         push(@{$changes{'cancreate'}},'shibenv');
10034:                     }
10035:                 }
10036:             } else {
10037:                 foreach my $field (@shibfields) {
10038:                     if ($env{'form.shibenv_'.$field}) {
10039:                         push(@{$changes{'cancreate'}},'shibenv');
10040:                         last;
10041:                     }
10042:                 }
10043:             }
10044:         }
10045:     }
10046:     foreach my $item (@contexts) {
10047:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
10048:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
10049:                 if (ref($cancreate{$item}) eq 'ARRAY') {
10050:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
10051:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10052:                             push(@{$changes{'cancreate'}},$item);
10053:                         }
10054:                     }
10055:                 }
10056:             }
10057:             if (ref($cancreate{$item}) eq 'ARRAY') {
10058:                 foreach my $type (@{$cancreate{$item}}) {
10059:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
10060:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10061:                             push(@{$changes{'cancreate'}},$item);
10062:                         }
10063:                     }
10064:                 }
10065:             }
10066:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
10067:             if (ref($cancreate{$item}) eq 'HASH') {
10068:                 foreach my $curr (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
10069:                     if (ref($curr_usercreation{'cancreate'}{$item}{$curr}) eq 'HASH') {
10070:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$curr}})) {
10071:                             unless ($curr_usercreation{'cancreate'}{$item}{$curr}{$field} eq $cancreate{$item}{$curr}{$field}) {
10072:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10073:                                     push(@{$changes{'cancreate'}},$item);
10074:                                 }
10075:                             }
10076:                         }
10077:                     } elsif ($item eq 'selfcreateprocessing') {
10078:                         if ($cancreate{$item}{$curr} ne $curr_usercreation{'cancreate'}{$item}{$curr}) {
10079:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10080:                                 push(@{$changes{'cancreate'}},$item);
10081:                             }
10082:                         }
10083:                     } else {
10084:                         if (!$cancreate{$item}{$curr}) {
10085:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10086:                                 push(@{$changes{'cancreate'}},$item);
10087:                             }
10088:                         }
10089:                     }
10090:                 }
10091:                 foreach my $field (keys(%{$cancreate{$item}})) {
10092:                     if (ref($cancreate{$item}{$field}) eq 'HASH') {
10093:                         foreach my $inner (keys(%{$cancreate{$item}{$field}})) {
10094:                             if (ref($curr_usercreation{'cancreate'}{$item}{$field}) eq 'HASH') {
10095:                                 unless ($curr_usercreation{'cancreate'}{$item}{$field}{$inner} eq $cancreate{$item}{$field}{$inner}) {
10096:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10097:                                         push(@{$changes{'cancreate'}},$item);
10098:                                     }
10099:                                 }
10100:                             } else {
10101:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10102:                                     push(@{$changes{'cancreate'}},$item);
10103:                                 }
10104:                             }
10105:                         }
10106:                     } elsif ($item eq 'selfcreateprocessing') {
10107:                         if ($cancreate{$item}{$field} ne $curr_usercreation{'cancreate'}{$item}{$field}) {
10108:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10109:                                 push(@{$changes{'cancreate'}},$item);
10110:                             }
10111:                         }
10112:                     } else {
10113:                         if (!$curr_usercreation{'cancreate'}{$item}{$field}) {
10114:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10115:                                 push(@{$changes{'cancreate'}},$item);
10116:                             }
10117:                         }
10118:                     }
10119:                 }
10120:             }
10121:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
10122:             if (ref($cancreate{$item}) eq 'ARRAY') {
10123:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
10124:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10125:                         push(@{$changes{'cancreate'}},$item);
10126:                     }
10127:                 }
10128:             } elsif (ref($cancreate{$item}) eq 'HASH') {
10129:                 if (!$cancreate{$item}{$curr_usercreation{'cancreate'}{$item}}) {
10130:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10131:                         push(@{$changes{'cancreate'}},$item);
10132:                     }
10133:                 }
10134:             }
10135:         } elsif ($item eq 'emailusername') {
10136:             if (ref($cancreate{$item}) eq 'HASH') {
10137:                 foreach my $type (keys(%{$cancreate{$item}})) {
10138:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
10139:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
10140:                             if ($cancreate{$item}{$type}{$field}) {
10141:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10142:                                     push(@{$changes{'cancreate'}},$item);
10143:                                 }
10144:                                 last;
10145:                             }
10146:                         }
10147:                     }
10148:                 }
10149:             }
10150:         }
10151:     }
10152: #
10153: # Populate %save_usercreate hash with updates to self-creation configuration.
10154: #
10155:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
10156:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
10157:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
10158:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
10159:     if (ref($cancreate{'notify'}) eq 'HASH') {
10160:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
10161:     }
10162:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
10163:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
10164:     }
10165:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
10166:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
10167:     }
10168:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
10169:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
10170:     }
10171:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
10172:     $save_usercreate{'emailrule'} = \@email_rule;
10173: 
10174:     my %userconfig_hash = (
10175:             usercreation     => \%save_usercreate,
10176:             usermodification => \%save_usermodify,
10177:     );
10178:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
10179:                                              $dom);
10180: #
10181: # Accumulate details of changes to domain cofiguration for self-creation of usernames in $resulttext
10182: #
10183:     if ($putresult eq 'ok') {
10184:         if (keys(%changes) > 0) {
10185:             $resulttext = &mt('Changes made:').'<ul>';
10186:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
10187:                 my %lt = &selfcreation_types();
10188:                 foreach my $type (@{$changes{'cancreate'}}) {
10189:                     my $chgtext;
10190:                     if ($type eq 'selfcreate') {
10191:                         if (@{$cancreate{$type}} == 0) {
10192:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
10193:                         } else {
10194:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
10195:                                         '<ul>';
10196:                             foreach my $case (@{$cancreate{$type}}) {
10197:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
10198:                             }
10199:                             $chgtext .= '</ul>';
10200:                             if (ref($cancreate{$type}) eq 'ARRAY') {
10201:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
10202:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
10203:                                         if (@{$cancreate{'statustocreate'}} == 0) {
10204:                                             $chgtext .= '<br />'.
10205:                                                         '<span class="LC_warning">'.
10206:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
10207:                                                         '</span>';
10208:                                         }
10209:                                     }
10210:                                 }
10211:                             }
10212:                         }
10213:                     } elsif ($type eq 'shibenv') {
10214:                         if (keys(%{$cancreate{$type}}) == 0) {
10215:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information'); 
10216:                         } else {
10217:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
10218:                                         '<ul>';
10219:                             foreach my $field (@shibfields) {
10220:                                 next if ($cancreate{$type}{$field} eq '');
10221:                                 if ($field eq 'inststatus') {
10222:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
10223:                                 } else {
10224:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
10225:                                 }
10226:                             }
10227:                             $chgtext .= '</ul>';
10228:                         }  
10229:                     } elsif ($type eq 'statustocreate') {
10230:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
10231:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
10232:                             if (@{$cancreate{'selfcreate'}} > 0) {
10233:                                 if (@{$cancreate{'statustocreate'}} == 0) {
10234:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
10235:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
10236:                                         $chgtext .= '<br />'.
10237:                                                     '<span class="LC_warning">'.
10238:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
10239:                                                     '</span>';
10240:                                     }
10241:                                 } elsif (ref($usertypes) eq 'HASH') {
10242:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
10243:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
10244:                                     } else {
10245:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
10246:                                     }
10247:                                     $chgtext .= '<ul>';
10248:                                     foreach my $case (@{$cancreate{$type}}) {
10249:                                         if ($case eq 'default') {
10250:                                             $chgtext .= '<li>'.$othertitle.'</li>';
10251:                                         } else {
10252:                                             $chgtext .= '<li>'.$usertypes->{$case}.'</li>';
10253:                                         }
10254:                                     }
10255:                                     $chgtext .= '</ul>';
10256:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
10257:                                         $chgtext .= '<br /><span class="LC_warning">'.
10258:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
10259:                                                     '</span>';
10260:                                     }
10261:                                 }
10262:                             } else {
10263:                                 if (@{$cancreate{$type}} == 0) {
10264:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
10265:                                 } else {
10266:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
10267:                                 }
10268:                             }
10269:                         }
10270:                     } elsif ($type eq 'selfcreateprocessing') {
10271:                         my %choices = &Apache::lonlocal::texthash (
10272:                                                                     automatic => 'Automatic approval',
10273:                                                                     approval  => 'Queued for approval',
10274:                                                                   );
10275:                         if (@statuses > 1) {
10276:                             $chgtext .= &mt('Processing of requests to create account with e-mail address as username set as follows:'). 
10277:                                         '<ul>';
10278:                            foreach my $type (@statuses) {
10279:                                if ($type eq 'default') {
10280:                                    $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$type}}.'</li>';
10281:                                } else {
10282:                                    $chgtext .= '<li>'.$usertypes->{$type}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$type}}.'</li>';
10283:                                }
10284:                            }
10285:                            $chgtext .= '</ul>';
10286:                         } else {
10287:                            $chgtext .= &mt('Processing of requests to create account with e-mail address as username set to: "[_1]"',
10288:                                          $choices{$cancreate{'selfcreateprocessing'}{'default'}});
10289:                         }
10290:                     } elsif ($type eq 'captcha') {
10291:                         if ($savecaptcha{$type} eq 'notused') {
10292:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
10293:                         } else {
10294:                             my %captchas = &captcha_phrases();
10295:                             if ($captchas{$savecaptcha{$type}}) {
10296:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
10297:                             } else {
10298:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
10299:                             }
10300:                         }
10301:                     } elsif ($type eq 'recaptchakeys') {
10302:                         my ($privkey,$pubkey);
10303:                         if (ref($savecaptcha{$type}) eq 'HASH') {
10304:                             $pubkey = $savecaptcha{$type}{'public'};
10305:                             $privkey = $savecaptcha{$type}{'private'};
10306:                         }
10307:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
10308:                         if (!$pubkey) {
10309:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
10310:                         } else {
10311:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
10312:                         }
10313:                         if (!$privkey) {
10314:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
10315:                         } else {
10316:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
10317:                         }
10318:                         $chgtext .= '</ul>';
10319:                     } elsif ($type eq 'recaptchaversion') {
10320:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
10321:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
10322:                         }
10323:                     } elsif ($type eq 'emailusername') {
10324:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
10325:                             if (ref($types) eq 'ARRAY') {
10326:                                 foreach my $type (@{$types}) {
10327:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
10328:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
10329:                                             $chgtext .= &mt('When self-creating account with e-mail as username, the following information will be provided by [_1]:',"'$usertypes->{$type}'").
10330:                                                     '<ul>';
10331:                                             foreach my $field (@{$infofields}) {
10332:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
10333:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
10334:                                                 }
10335:                                             }
10336:                                             $chgtext .= '</ul>';
10337:                                         } else {
10338:                                             $chgtext .= &mt('When self creating account with e-mail as username, no information besides e-mail address will be provided by [_1].',"'$usertypes->{$type}'").'<br />';
10339:                                         }
10340:                                     } else {
10341:                                         $chgtext .= &mt('When self creating account with e-mail as username, no information besides e-mail address will be provided by [_1].',"'$usertypes->{$type}'").'<br />';
10342:                                     }
10343:                                 }
10344:                             }
10345:                         }
10346:                     } elsif ($type eq 'notify') {
10347:                         $chgtext = &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
10348:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
10349:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
10350:                                 if ($cancreate{'notify'}{'approval'}) {
10351:                                     $chgtext = &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
10352:                                 }
10353:                             }
10354:                         }
10355:                     }
10356:                     if ($chgtext) {
10357:                         $resulttext .= '<li>'.$chgtext.'</li>';
10358:                     }
10359:                 }
10360:             }
10361:             if (ref($changes{'email_rule'}) eq 'ARRAY') {
10362:                 my ($emailrules,$emailruleorder) =
10363:                     &Apache::lonnet::inst_userrules($dom,'email');
10364:                 my $chgtext = '<ul>';
10365:                 foreach my $type (@email_rule) {
10366:                     if (ref($emailrules->{$type}) eq 'HASH') {
10367:                         $chgtext .= '<li>'.$emailrules->{$type}{'name'}.'</li>';
10368:                     }
10369:                 }
10370:                 $chgtext .= '</ul>';
10371:                 if (@email_rule > 0) {
10372:                     $resulttext .= '<li>'.
10373:                                    &mt('Accounts may not be created by users self-enrolling with e-mail addresses of the following types: ').
10374:                                        $chgtext.
10375:                                    '</li>';
10376:                 } else {
10377:                     $resulttext .= '<li>'.
10378:                                    &mt('There are now no restrictions on e-mail addresses which may be used as a username when self-enrolling.').
10379:                                    '</li>';
10380:                 }
10381:             }
10382:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
10383:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
10384:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
10385:                 foreach my $type (@{$changes{'selfcreate'}}) {
10386:                     my $typename = $type;
10387:                     if (ref($usertypes) eq 'HASH') {
10388:                         if ($usertypes->{$type} ne '') {
10389:                             $typename = $usertypes->{$type};
10390:                         }
10391:                     }
10392:                     my @modifiable;
10393:                     $resulttext .= '<li>'.
10394:                                     &mt('Self-creation of account by users with status: [_1]',
10395:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
10396:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
10397:                     foreach my $field (@fields) {
10398:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
10399:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
10400:                         }
10401:                     }
10402:                     if (@modifiable > 0) {
10403:                         $resulttext .= join(', ',@modifiable);
10404:                     } else {
10405:                         $resulttext .= &mt('none');
10406:                     }
10407:                     $resulttext .= '</li>';
10408:                 }
10409:                 $resulttext .= '</ul></li>';
10410:             }
10411:             $resulttext .= '</ul>';
10412:         } else {
10413:             $resulttext = &mt('No changes made to self-creation settings');
10414:         }
10415:     } else {
10416:         $resulttext = '<span class="LC_error">'.
10417:             &mt('An error occurred: [_1]',$putresult).'</span>';
10418:     }
10419:     if ($warningmsg ne '') {
10420:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
10421:     }
10422:     return $resulttext;
10423: }
10424: 
10425: sub process_captcha {
10426:     my ($container,$changes,$newsettings,$current) = @_;
10427:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH') || (ref($current) eq 'HASH'));
10428:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
10429:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
10430:         $newsettings->{'captcha'} = 'original';
10431:     }
10432:     if ($current->{'captcha'} ne $newsettings->{'captcha'}) {
10433:         if ($container eq 'cancreate') {
10434:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
10435:                 push(@{$changes->{'cancreate'}},'captcha');
10436:             } elsif (!defined($changes->{'cancreate'})) {
10437:                 $changes->{'cancreate'} = ['captcha'];
10438:             }
10439:         } else {
10440:             $changes->{'captcha'} = 1;
10441:         }
10442:     }
10443:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
10444:     if ($newsettings->{'captcha'} eq 'recaptcha') {
10445:         $newpub = $env{'form.'.$container.'_recaptchapub'};
10446:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
10447:         $newpub =~ s/[^\w\-]//g;
10448:         $newpriv =~ s/[^\w\-]//g;
10449:         $newsettings->{'recaptchakeys'} = {
10450:                                              public  => $newpub,
10451:                                              private => $newpriv,
10452:                                           };
10453:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
10454:         $newversion =~ s/\D//g;
10455:         if ($newversion ne '2') {
10456:             $newversion = 1;
10457:         }
10458:         $newsettings->{'recaptchaversion'} = $newversion;
10459:     }
10460:     if (ref($current->{'recaptchakeys'}) eq 'HASH') {
10461:         $currpub = $current->{'recaptchakeys'}{'public'};
10462:         $currpriv = $current->{'recaptchakeys'}{'private'};
10463:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
10464:             $newsettings->{'recaptchakeys'} = {
10465:                                                  public  => '',
10466:                                                  private => '',
10467:                                               }
10468:         }
10469:     }
10470:     if ($current->{'captcha'} eq 'recaptcha') {
10471:         $currversion = $current->{'recaptchaversion'};
10472:         if ($currversion ne '2') {
10473:             $currversion = 1;
10474:         }
10475:     }
10476:     if ($currversion ne $newversion) {
10477:         if ($container eq 'cancreate') {
10478:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
10479:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
10480:             } elsif (!defined($changes->{'cancreate'})) {
10481:                 $changes->{'cancreate'} = ['recaptchaversion'];
10482:             }
10483:         } else {
10484:             $changes->{'recaptchaversion'} = 1;
10485:         }
10486:     }
10487:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
10488:         if ($container eq 'cancreate') {
10489:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
10490:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
10491:             } elsif (!defined($changes->{'cancreate'})) {
10492:                 $changes->{'cancreate'} = ['recaptchakeys'];
10493:             }
10494:         } else {
10495:             $changes->{'recaptchakeys'} = 1;
10496:         }
10497:     }
10498:     return;
10499: }
10500: 
10501: sub modify_usermodification {
10502:     my ($dom,%domconfig) = @_;
10503:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
10504:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
10505:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
10506:             if ($key eq 'selfcreate') {
10507:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
10508:             } else {  
10509:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
10510:             }
10511:         }
10512:     }
10513:     my @contexts = ('author','course');
10514:     my %context_title = (
10515:                            author => 'In author context',
10516:                            course => 'In course context',
10517:                         );
10518:     my @fields = ('lastname','firstname','middlename','generation',
10519:                   'permanentemail','id');
10520:     my %roles = (
10521:                   author => ['ca','aa'],
10522:                   course => ['st','ep','ta','in','cr'],
10523:                 );
10524:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
10525:     foreach my $context (@contexts) {
10526:         foreach my $role (@{$roles{$context}}) {
10527:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
10528:             foreach my $item (@fields) {
10529:                 if (grep(/^\Q$item\E$/,@modifiable)) {
10530:                     $modifyhash{$context}{$role}{$item} = 1;
10531:                 } else {
10532:                     $modifyhash{$context}{$role}{$item} = 0;
10533:                 }
10534:             }
10535:         }
10536:         if (ref($curr_usermodification{$context}) eq 'HASH') {
10537:             foreach my $role (@{$roles{$context}}) {
10538:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
10539:                     foreach my $field (@fields) {
10540:                         if ($modifyhash{$context}{$role}{$field} ne 
10541:                                 $curr_usermodification{$context}{$role}{$field}) {
10542:                             push(@{$changes{$context}},$role);
10543:                             last;
10544:                         }
10545:                     }
10546:                 }
10547:             }
10548:         } else {
10549:             foreach my $context (@contexts) {
10550:                 foreach my $role (@{$roles{$context}}) {
10551:                     push(@{$changes{$context}},$role);
10552:                 }
10553:             }
10554:         }
10555:     }
10556:     my %usermodification_hash =  (
10557:                                    usermodification => \%modifyhash,
10558:                                  );
10559:     my $putresult = &Apache::lonnet::put_dom('configuration',
10560:                                              \%usermodification_hash,$dom);
10561:     if ($putresult eq 'ok') {
10562:         if (keys(%changes) > 0) {
10563:             $resulttext = &mt('Changes made: ').'<ul>';
10564:             foreach my $context (@contexts) {
10565:                 if (ref($changes{$context}) eq 'ARRAY') {
10566:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
10567:                     if (ref($changes{$context}) eq 'ARRAY') {
10568:                         foreach my $role (@{$changes{$context}}) {
10569:                             my $rolename;
10570:                             if ($role eq 'cr') {
10571:                                 $rolename = &mt('Custom');
10572:                             } else {
10573:                                 $rolename = &Apache::lonnet::plaintext($role);
10574:                             }
10575:                             my @modifiable;
10576:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
10577:                             foreach my $field (@fields) {
10578:                                 if ($modifyhash{$context}{$role}{$field}) {
10579:                                     push(@modifiable,$fieldtitles{$field});
10580:                                 }
10581:                             }
10582:                             if (@modifiable > 0) {
10583:                                 $resulttext .= join(', ',@modifiable);
10584:                             } else {
10585:                                 $resulttext .= &mt('none'); 
10586:                             }
10587:                             $resulttext .= '</li>';
10588:                         }
10589:                         $resulttext .= '</ul></li>';
10590:                     }
10591:                 }
10592:             }
10593:             $resulttext .= '</ul>';
10594:         } else {
10595:             $resulttext = &mt('No changes made to user modification settings');
10596:         }
10597:     } else {
10598:         $resulttext = '<span class="LC_error">'.
10599:             &mt('An error occurred: [_1]',$putresult).'</span>';
10600:     }
10601:     return $resulttext;
10602: }
10603: 
10604: sub modify_defaults {
10605:     my ($dom,$lastactref,%domconfig) = @_;
10606:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
10607:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
10608:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def','portal_def');
10609:     my @authtypes = ('internal','krb4','krb5','localauth');
10610:     foreach my $item (@items) {
10611:         $newvalues{$item} = $env{'form.'.$item};
10612:         if ($item eq 'auth_def') {
10613:             if ($newvalues{$item} ne '') {
10614:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
10615:                     push(@errors,$item);
10616:                 }
10617:             }
10618:         } elsif ($item eq 'lang_def') {
10619:             if ($newvalues{$item} ne '') {
10620:                 if ($newvalues{$item} =~ /^(\w+)/) {
10621:                     my $langcode = $1;
10622:                     if ($langcode ne 'x_chef') {
10623:                         if (code2language($langcode) eq '') {
10624:                             push(@errors,$item);
10625:                         }
10626:                     }
10627:                 } else {
10628:                     push(@errors,$item);
10629:                 }
10630:             }
10631:         } elsif ($item eq 'timezone_def') {
10632:             if ($newvalues{$item} ne '') {
10633:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
10634:                     push(@errors,$item);   
10635:                 }
10636:             }
10637:         } elsif ($item eq 'datelocale_def') {
10638:             if ($newvalues{$item} ne '') {
10639:                 my @datelocale_ids = DateTime::Locale->ids();
10640:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
10641:                     push(@errors,$item);
10642:                 }
10643:             }
10644:         } elsif ($item eq 'portal_def') {
10645:             if ($newvalues{$item} ne '') {
10646:                 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])\/?$/) {
10647:                     push(@errors,$item);
10648:                 }
10649:             }
10650:         }
10651:         if (grep(/^\Q$item\E$/,@errors)) {
10652:             $newvalues{$item} = $domdefaults{$item};
10653:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
10654:             $changes{$item} = 1;
10655:         }
10656:         $domdefaults{$item} = $newvalues{$item};
10657:     }
10658:     my %defaults_hash = (
10659:                          defaults => \%newvalues,
10660:                         );
10661:     my $title = &defaults_titles();
10662: 
10663:     my $currinststatus;
10664:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
10665:         $currinststatus = $domconfig{'inststatus'};
10666:     } else {
10667:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
10668:         $currinststatus = {
10669:                              inststatustypes => $usertypes,
10670:                              inststatusorder => $types,
10671:                              inststatusguest => [],
10672:                           };
10673:     }
10674:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
10675:     my @allpos;
10676:     my %guests;
10677:     my %alltypes;
10678:     my ($currtitles,$currguests,$currorder);
10679:     if (ref($currinststatus) eq 'HASH') {
10680:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
10681:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
10682:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
10683:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
10684:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
10685:                     }
10686:                 }
10687:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
10688:                     my $position = $env{'form.inststatus_pos_'.$type};
10689:                     $position =~ s/\D+//g;
10690:                     $allpos[$position] = $type;
10691:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
10692:                     $alltypes{$type} =~ s/`//g;
10693:                     if ($env{'form.inststatus_guest_'.$type}) {
10694:                         $guests{$type} = 1;
10695:                     }
10696:                 }
10697:             }
10698:             if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
10699:                 $currguests = join(',',@{$currinststatus->{'inststatusguest'}});
10700:             }
10701:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
10702:             $currtitles =~ s/,$//;
10703:         }
10704:     }
10705:     if ($env{'form.addinststatus'}) {
10706:         my $newtype = $env{'form.addinststatus'};
10707:         $newtype =~ s/\W//g;
10708:         unless (exists($alltypes{$newtype})) {
10709:             if ($env{'form.addinststatus_guest'}) {
10710:                 $guests{$newtype} = 1;
10711:             }
10712:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
10713:             $alltypes{$newtype} =~ s/`//g; 
10714:             my $position = $env{'form.addinststatus_pos'};
10715:             $position =~ s/\D+//g;
10716:             if ($position ne '') {
10717:                 $allpos[$position] = $newtype;
10718:             }
10719:         }
10720:     }
10721:     my (@orderedstatus,@orderedguests);
10722:     foreach my $type (@allpos) {
10723:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
10724:             push(@orderedstatus,$type);
10725:             if ($guests{$type}) {
10726:                 push(@orderedguests,$type);
10727:             }
10728:         }
10729:     }
10730:     foreach my $type (keys(%alltypes)) {
10731:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
10732:             delete($alltypes{$type});
10733:         }
10734:     }
10735:     $defaults_hash{'inststatus'} = {
10736:                                      inststatustypes => \%alltypes,
10737:                                      inststatusorder => \@orderedstatus,
10738:                                      inststatusguest => \@orderedguests,
10739:                                    };
10740:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
10741:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
10742:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
10743:         }
10744:     }
10745:     if ($currorder ne join(',',@orderedstatus)) {
10746:         $changes{'inststatus'}{'inststatusorder'} = 1;
10747:     }
10748:     if ($currguests ne join(',',@orderedguests)) {
10749:         $changes{'inststatus'}{'inststatusguest'} = 1;
10750:     }
10751:     my $newtitles;
10752:     foreach my $item (@orderedstatus) {
10753:         $newtitles .= $alltypes{$item}.',';
10754:     }
10755:     $newtitles =~ s/,$//;
10756:     if ($currtitles ne $newtitles) {
10757:         $changes{'inststatus'}{'inststatustypes'} = 1;
10758:     }
10759:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
10760:                                              $dom);
10761:     if ($putresult eq 'ok') {
10762:         if (keys(%changes) > 0) {
10763:             $resulttext = &mt('Changes made:').'<ul>';
10764:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
10765:             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";
10766:             foreach my $item (sort(keys(%changes))) {
10767:                 if ($item eq 'inststatus') {
10768:                     if (ref($changes{'inststatus'}) eq 'HASH') {
10769:                         if (($changes{'inststatus'}{'inststatustypes'}) || $changes{'inststatus'}{'inststatusorder'}) {
10770:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
10771:                             foreach my $type (@orderedstatus) { 
10772:                                 $resulttext .= $alltypes{$type}.', ';
10773:                             }
10774:                             $resulttext =~ s/, $//;
10775:                             $resulttext .= '</li>';
10776:                         }
10777:                         if ($changes{'inststatus'}{'inststatusguest'}) {
10778:                             $resulttext .= '<li>'; 
10779:                             if (@orderedguests) {
10780:                                 $resulttext .= &mt('Types assignable to "non-institutional" usernames set to:').' ';
10781:                                 foreach my $type (@orderedguests) {
10782:                                     $resulttext .= $alltypes{$type}.', ';
10783:                                 }
10784:                                 $resulttext =~ s/, $//;
10785:                             } else {
10786:                                 $resulttext .= &mt('Types assignable to "non-institutional" usernames set to none.');
10787:                             }
10788:                             $resulttext .= '</li>';
10789:                         }
10790:                     }
10791:                 } else {
10792:                     my $value = $env{'form.'.$item};
10793:                     if ($value eq '') {
10794:                         $value = &mt('none');
10795:                     } elsif ($item eq 'auth_def') {
10796:                         my %authnames = &authtype_names();
10797:                         my %shortauth = (
10798:                                           internal   => 'int',
10799:                                           krb4       => 'krb4',
10800:                                           krb5       => 'krb5',
10801:                                           localauth  => 'loc',
10802:                         );
10803:                         $value = $authnames{$shortauth{$value}};
10804:                     }
10805:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
10806:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
10807:                 }
10808:             }
10809:             $resulttext .= '</ul>';
10810:             $mailmsgtext .= "\n";
10811:             my $cachetime = 24*60*60;
10812:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
10813:             if (ref($lastactref) eq 'HASH') {
10814:                 $lastactref->{'domdefaults'} = 1;
10815:             }
10816:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
10817:                 my $notify = 1;
10818:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
10819:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
10820:                         $notify = 0;
10821:                     }
10822:                 }
10823:                 if ($notify) {
10824:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
10825:                                                "LON-CAPA Domain Settings Change - $dom",
10826:                                                $mailmsgtext);
10827:                 }
10828:             }
10829:         } else {
10830:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
10831:         }
10832:     } else {
10833:         $resulttext = '<span class="LC_error">'.
10834:             &mt('An error occurred: [_1]',$putresult).'</span>';
10835:     }
10836:     if (@errors > 0) {
10837:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
10838:         foreach my $item (@errors) {
10839:             $resulttext .= ' "'.$title->{$item}.'",';
10840:         }
10841:         $resulttext =~ s/,$//;
10842:     }
10843:     return $resulttext;
10844: }
10845: 
10846: sub modify_scantron {
10847:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
10848:     my ($resulttext,%confhash,%changes,$errors);
10849:     my $custom = 'custom.tab';
10850:     my $default = 'default.tab';
10851:     my $servadm = $r->dir_config('lonAdmEMail');
10852:     my ($configuserok,$author_ok,$switchserver) = 
10853:         &config_check($dom,$confname,$servadm);
10854:     if ($env{'form.scantronformat.filename'} ne '') {
10855:         my $error;
10856:         if ($configuserok eq 'ok') {
10857:             if ($switchserver) {
10858:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
10859:             } else {
10860:                 if ($author_ok eq 'ok') {
10861:                     my ($result,$scantronurl) =
10862:                         &publishlogo($r,'upload','scantronformat',$dom,
10863:                                      $confname,'scantron','','',$custom);
10864:                     if ($result eq 'ok') {
10865:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
10866:                         $changes{'scantronformat'} = 1;
10867:                     } else {
10868:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
10869:                     }
10870:                 } else {
10871:                     $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);
10872:                 }
10873:             }
10874:         } else {
10875:             $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);
10876:         }
10877:         if ($error) {
10878:             &Apache::lonnet::logthis($error);
10879:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10880:         }
10881:     }
10882:     if (ref($domconfig{'scantron'}) eq 'HASH') {
10883:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
10884:             if ($env{'form.scantronformat_del'}) {
10885:                 $confhash{'scantron'}{'scantronformat'} = '';
10886:                 $changes{'scantronformat'} = 1;
10887:             }
10888:         }
10889:     }
10890:     if (keys(%confhash) > 0) {
10891:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
10892:                                                  $dom);
10893:         if ($putresult eq 'ok') {
10894:             if (keys(%changes) > 0) {
10895:                 if (ref($confhash{'scantron'}) eq 'HASH') {
10896:                     $resulttext = &mt('Changes made:').'<ul>';
10897:                     if ($confhash{'scantron'}{'scantronformat'} eq '') {
10898:                         $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
10899:                     } else {
10900:                         $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
10901:                     }
10902:                     $resulttext .= '</ul>';
10903:                 } else {
10904:                     $resulttext = &mt('Changes made to bubblesheet format file.');
10905:                 }
10906:                 $resulttext .= '</ul>';
10907:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
10908:                 if (ref($lastactref) eq 'HASH') {
10909:                     $lastactref->{'domainconfig'} = 1;
10910:                 }
10911:             } else {
10912:                 $resulttext = &mt('No changes made to bubblesheet format file');
10913:             }
10914:         } else {
10915:             $resulttext = '<span class="LC_error">'.
10916:                 &mt('An error occurred: [_1]',$putresult).'</span>';
10917:         }
10918:     } else {
10919:         $resulttext = &mt('No changes made to bubblesheet format file'); 
10920:     }
10921:     if ($errors) {
10922:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
10923:                        $errors.'</ul>';
10924:     }
10925:     return $resulttext;
10926: }
10927: 
10928: sub modify_coursecategories {
10929:     my ($dom,$lastactref,%domconfig) = @_;
10930:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
10931:         $cathash);
10932:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
10933:     my @catitems = ('unauth','auth');
10934:     my @cattypes = ('std','domonly','codesrch','none');
10935:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
10936:         $cathash = $domconfig{'coursecategories'}{'cats'};
10937:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
10938:             $changes{'togglecats'} = 1;
10939:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
10940:         }
10941:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
10942:             $changes{'categorize'} = 1;
10943:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
10944:         }
10945:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
10946:             $changes{'togglecatscomm'} = 1;
10947:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
10948:         }
10949:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
10950:             $changes{'categorizecomm'} = 1;
10951:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
10952: 
10953:         }
10954:         if ($domconfig{'coursecategories'}{'togglecatsplace'} ne $env{'form.togglecatsplace'}) {
10955:             $changes{'togglecatsplace'} = 1;
10956:             $domconfig{'coursecategories'}{'togglecatsplace'} = $env{'form.togglecatsplace'};
10957:         }
10958:         if ($domconfig{'coursecategories'}{'categorizeplace'} ne $env{'form.categorizeplace'}) {
10959:             $changes{'categorizeplace'} = 1;
10960:             $domconfig{'coursecategories'}{'categorizeplace'} = $env{'form.categorizeplace'};
10961:         }
10962:         foreach my $item (@catitems) {
10963:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
10964:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
10965:                     $changes{$item} = 1;
10966:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
10967:                 }
10968:             }
10969:         }
10970:     } else {
10971:         $changes{'togglecats'} = 1;
10972:         $changes{'categorize'} = 1;
10973:         $changes{'togglecatscomm'} = 1;
10974:         $changes{'categorizecomm'} = 1;
10975:         $changes{'togglecatsplace'} = 1;
10976:         $changes{'categorizeplace'} = 1;
10977:         $domconfig{'coursecategories'} = {
10978:                                              togglecats => $env{'form.togglecats'},
10979:                                              categorize => $env{'form.categorize'},
10980:                                              togglecatscomm => $env{'form.togglecatscomm'},
10981:                                              categorizecomm => $env{'form.categorizecomm'},
10982:                                              togglecatsplace => $env{'form.togglecatsplace'},
10983:                                              categorizeplace => $env{'form.categorizeplace'},
10984:                                          };
10985:         foreach my $item (@catitems) {
10986:             if ($env{'form.coursecat_'.$item} ne 'std') {
10987:                 $changes{$item} = 1;
10988:             }
10989:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
10990:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
10991:             }
10992:         }
10993:     }
10994:     if (ref($cathash) eq 'HASH') {
10995:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
10996:             push (@deletecategory,'instcode::0');
10997:         }
10998:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
10999:             push(@deletecategory,'communities::0');
11000:         }
11001:         if (($domconfig{'coursecategories'}{'cats'}{'placement::0'} ne '')  && ($env{'form.placement'} == 0)) {
11002:             push(@deletecategory,'placement::0');
11003:         }
11004:     }
11005:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
11006:     if (ref($cathash) eq 'HASH') {
11007:         if (@deletecategory > 0) {
11008:             #FIXME Need to remove category from all courses using a deleted category 
11009:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
11010:             foreach my $item (@deletecategory) {
11011:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
11012:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
11013:                     $deletions{$item} = 1;
11014:                     &recurse_cat_deletes($item,$cathash,\%deletions);
11015:                 }
11016:             }
11017:         }
11018:         foreach my $item (keys(%{$cathash})) {
11019:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
11020:             if ($cathash->{$item} ne $env{'form.'.$item}) {
11021:                 $reorderings{$item} = 1;
11022:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
11023:             }
11024:             if ($env{'form.addcategory_name_'.$item} ne '') {
11025:                 my $newcat = $env{'form.addcategory_name_'.$item};
11026:                 my $newdepth = $depth+1;
11027:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
11028:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
11029:                 $adds{$newitem} = 1; 
11030:             }
11031:             if ($env{'form.subcat_'.$item} ne '') {
11032:                 my $newcat = $env{'form.subcat_'.$item};
11033:                 my $newdepth = $depth+1;
11034:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
11035:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
11036:                 $adds{$newitem} = 1;
11037:             }
11038:         }
11039:     }
11040:     if ($env{'form.instcode'} eq '1') {
11041:         if (ref($cathash) eq 'HASH') {
11042:             my $newitem = 'instcode::0';
11043:             if ($cathash->{$newitem} eq '') {  
11044:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
11045:                 $adds{$newitem} = 1;
11046:             }
11047:         } else {
11048:             my $newitem = 'instcode::0';
11049:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
11050:             $adds{$newitem} = 1;
11051:         }
11052:     }
11053:     if ($env{'form.communities'} eq '1') {
11054:         if (ref($cathash) eq 'HASH') {
11055:             my $newitem = 'communities::0';
11056:             if ($cathash->{$newitem} eq '') {
11057:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
11058:                 $adds{$newitem} = 1;
11059:             }
11060:         } else {
11061:             my $newitem = 'communities::0';
11062:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
11063:             $adds{$newitem} = 1;
11064:         }
11065:     }
11066:     if ($env{'form.placement'} eq '1') {
11067:         if (ref($cathash) eq 'HASH') {
11068:             my $newitem = 'placement::0';
11069:             if ($cathash->{$newitem} eq '') {
11070:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
11071:                 $adds{$newitem} = 1;
11072:             }
11073:         } else {
11074:             my $newitem = 'placement::0';
11075:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
11076:             $adds{$newitem} = 1;
11077:         }
11078:     }
11079:     if ($env{'form.addcategory_name'} ne '') {
11080:         if (($env{'form.addcategory_name'} ne 'instcode') &&
11081:             ($env{'form.addcategory_name'} ne 'communities') &&
11082:             ($env{'form.addcategory_name'} ne 'placement')) {
11083:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
11084:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
11085:             $adds{$newitem} = 1;
11086:         }
11087:     }
11088:     my $putresult;
11089:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
11090:         if (keys(%deletions) > 0) {
11091:             foreach my $key (keys(%deletions)) {
11092:                 if ($predelallitems{$key} ne '') {
11093:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
11094:                 }
11095:             }
11096:         }
11097:         my (@chkcats,@chktrails,%chkallitems);
11098:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
11099:         if (ref($chkcats[0]) eq 'ARRAY') {
11100:             my $depth = 0;
11101:             my $chg = 0;
11102:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
11103:                 my $name = $chkcats[0][$i];
11104:                 my $item;
11105:                 if ($name eq '') {
11106:                     $chg ++;
11107:                 } else {
11108:                     $item = &escape($name).'::0';
11109:                     if ($chg) {
11110:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
11111:                     }
11112:                     $depth ++; 
11113:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
11114:                     $depth --;
11115:                 }
11116:             }
11117:         }
11118:     }
11119:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
11120:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
11121:         if ($putresult eq 'ok') {
11122:             my %title = (
11123:                          togglecats     => 'Show/Hide a course in catalog',
11124:                          categorize     => 'Assign a category to a course',
11125:                          togglecatscomm => 'Show/Hide a community in catalog',
11126:                          categorizecomm => 'Assign a category to a community',
11127:                         );
11128:             my %level = (
11129:                          dom  => 'set in Domain ("Modify Course/Community")',
11130:                          crs  => 'set in Course ("Course Configuration")',
11131:                          comm => 'set in Community ("Community Configuration")',
11132:                          none     => 'No catalog',
11133:                          std      => 'Standard catalog',
11134:                          domonly  => 'Domain-only catalog',
11135:                          codesrch => 'Code search form',
11136:                         );
11137:             $resulttext = &mt('Changes made:').'<ul>';
11138:             if ($changes{'togglecats'}) {
11139:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
11140:             }
11141:             if ($changes{'categorize'}) {
11142:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
11143:             }
11144:             if ($changes{'togglecatscomm'}) {
11145:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
11146:             }
11147:             if ($changes{'categorizecomm'}) {
11148:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
11149:             }
11150:             if ($changes{'unauth'}) {
11151:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
11152:             }
11153:             if ($changes{'auth'}) {
11154:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
11155:             }
11156:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
11157:                 my $cathash;
11158:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
11159:                     $cathash = $domconfig{'coursecategories'}{'cats'};
11160:                 } else {
11161:                     $cathash = {};
11162:                 } 
11163:                 my (@cats,@trails,%allitems);
11164:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
11165:                 if (keys(%deletions) > 0) {
11166:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
11167:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
11168:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
11169:                     }
11170:                     $resulttext .= '</ul></li>';
11171:                 }
11172:                 if (keys(%reorderings) > 0) {
11173:                     my %sort_by_trail;
11174:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
11175:                     foreach my $key (keys(%reorderings)) {
11176:                         if ($allitems{$key} ne '') {
11177:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
11178:                         }
11179:                     }
11180:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
11181:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
11182:                     }
11183:                     $resulttext .= '</ul></li>';
11184:                 }
11185:                 if (keys(%adds) > 0) {
11186:                     my %sort_by_trail;
11187:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
11188:                     foreach my $key (keys(%adds)) {
11189:                         if ($allitems{$key} ne '') {
11190:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
11191:                         }
11192:                     }
11193:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
11194:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
11195:                     }
11196:                     $resulttext .= '</ul></li>';
11197:                 }
11198:             }
11199:             $resulttext .= '</ul>';
11200:             if ($changes{'unauth'} || $changes{'auth'}) {
11201:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11202:                 if ($changes{'auth'}) {
11203:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
11204:                 }
11205:                 if ($changes{'unauth'}) {
11206:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
11207:                 }
11208:                 my $cachetime = 24*60*60;
11209:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
11210:                 if (ref($lastactref) eq 'HASH') {
11211:                     $lastactref->{'domdefaults'} = 1;
11212:                 }
11213:             }
11214:         } else {
11215:             $resulttext = '<span class="LC_error">'.
11216:                           &mt('An error occurred: [_1]',$putresult).'</span>';
11217:         }
11218:     } else {
11219:         $resulttext = &mt('No changes made to course and community categories');
11220:     }
11221:     return $resulttext;
11222: }
11223: 
11224: sub modify_serverstatuses {
11225:     my ($dom,%domconfig) = @_;
11226:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
11227:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
11228:         %currserverstatus = %{$domconfig{'serverstatuses'}};
11229:     }
11230:     my @pages = &serverstatus_pages();
11231:     foreach my $type (@pages) {
11232:         $newserverstatus{$type}{'namedusers'} = '';
11233:         $newserverstatus{$type}{'machines'} = '';
11234:         if (defined($env{'form.'.$type.'_namedusers'})) {
11235:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
11236:             my @okusers;
11237:             foreach my $user (@users) {
11238:                 my ($uname,$udom) = split(/:/,$user);
11239:                 if (($udom =~ /^$match_domain$/) &&   
11240:                     (&Apache::lonnet::domain($udom)) &&
11241:                     ($uname =~ /^$match_username$/)) {
11242:                     if (!grep(/^\Q$user\E/,@okusers)) {
11243:                         push(@okusers,$user);
11244:                     }
11245:                 }
11246:             }
11247:             if (@okusers > 0) {
11248:                  @okusers = sort(@okusers);
11249:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
11250:             }
11251:         }
11252:         if (defined($env{'form.'.$type.'_machines'})) {
11253:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
11254:             my @okmachines;
11255:             foreach my $ip (@machines) {
11256:                 my @parts = split(/\./,$ip);
11257:                 next if (@parts < 4);
11258:                 my $badip = 0;
11259:                 for (my $i=0; $i<4; $i++) {
11260:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
11261:                         $badip = 1;
11262:                         last;
11263:                     }
11264:                 }
11265:                 if (!$badip) {
11266:                     push(@okmachines,$ip);     
11267:                 }
11268:             }
11269:             @okmachines = sort(@okmachines);
11270:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
11271:         }
11272:     }
11273:     my %serverstatushash =  (
11274:                                 serverstatuses => \%newserverstatus,
11275:                             );
11276:     foreach my $type (@pages) {
11277:         foreach my $setting ('namedusers','machines') {
11278:             my (@current,@new);
11279:             if (ref($currserverstatus{$type}) eq 'HASH') {
11280:                 if ($currserverstatus{$type}{$setting} ne '') { 
11281:                     @current = split(/,/,$currserverstatus{$type}{$setting});
11282:                 }
11283:             }
11284:             if ($newserverstatus{$type}{$setting} ne '') {
11285:                 @new = split(/,/,$newserverstatus{$type}{$setting});
11286:             }
11287:             if (@current > 0) {
11288:                 if (@new > 0) {
11289:                     foreach my $item (@current) {
11290:                         if (!grep(/^\Q$item\E$/,@new)) {
11291:                             $changes{$type}{$setting} = 1;
11292:                             last;
11293:                         }
11294:                     }
11295:                     foreach my $item (@new) {
11296:                         if (!grep(/^\Q$item\E$/,@current)) {
11297:                             $changes{$type}{$setting} = 1;
11298:                             last;
11299:                         }
11300:                     }
11301:                 } else {
11302:                     $changes{$type}{$setting} = 1;
11303:                 }
11304:             } elsif (@new > 0) {
11305:                 $changes{$type}{$setting} = 1;
11306:             }
11307:         }
11308:     }
11309:     if (keys(%changes) > 0) {
11310:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
11311:         my $putresult = &Apache::lonnet::put_dom('configuration',
11312:                                                  \%serverstatushash,$dom);
11313:         if ($putresult eq 'ok') {
11314:             $resulttext .= &mt('Changes made:').'<ul>';
11315:             foreach my $type (@pages) {
11316:                 if (ref($changes{$type}) eq 'HASH') {
11317:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
11318:                     if ($changes{$type}{'namedusers'}) {
11319:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
11320:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
11321:                         } else {
11322:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
11323:                         }
11324:                     }
11325:                     if ($changes{$type}{'machines'}) {
11326:                         if ($newserverstatus{$type}{'machines'} eq '') {
11327:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
11328:                         } else {
11329:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
11330:                         }
11331: 
11332:                     }
11333:                     $resulttext .= '</ul></li>';
11334:                 }
11335:             }
11336:             $resulttext .= '</ul>';
11337:         } else {
11338:             $resulttext = '<span class="LC_error">'.
11339:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
11340: 
11341:         }
11342:     } else {
11343:         $resulttext = &mt('No changes made to access to server status pages');
11344:     }
11345:     return $resulttext;
11346: }
11347: 
11348: sub modify_helpsettings {
11349:     my ($r,$dom,$confname,%domconfig) = @_;
11350:     my ($resulttext,$errors,%changes,%helphash);
11351:     my %defaultchecked = ('submitbugs' => 'on');
11352:     my @offon = ('off','on');
11353:     my @toggles = ('submitbugs');
11354:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
11355:         foreach my $item (@toggles) {
11356:             if ($defaultchecked{$item} eq 'on') { 
11357:                 if ($domconfig{'helpsettings'}{$item} eq '') {
11358:                     if ($env{'form.'.$item} eq '0') {
11359:                         $changes{$item} = 1;
11360:                     }
11361:                 } elsif ($domconfig{'helpsettings'}{$item} ne $env{'form.'.$item}) {
11362:                     $changes{$item} = 1;
11363:                 }
11364:             } elsif ($defaultchecked{$item} eq 'off') {
11365:                 if ($domconfig{'helpsettings'}{$item} eq '') {
11366:                     if ($env{'form.'.$item} eq '1') {
11367:                         $changes{$item} = 1;
11368:                     }
11369:                 } elsif ($domconfig{'helpsettings'}{$item} ne $env{'form.'.$item}) {
11370:                     $changes{$item} = 1;
11371:                 }
11372:             }
11373:             if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
11374:                 $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
11375:             }
11376:         }
11377:     }
11378:     my $putresult;
11379:     if (keys(%changes) > 0) {
11380:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
11381:         if ($putresult eq 'ok') {
11382:             $resulttext = &mt('Changes made:').'<ul>';
11383:             foreach my $item (sort(keys(%changes))) {
11384:                 if ($item eq 'submitbugs') {
11385:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
11386:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
11387:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
11388:                 }
11389:             }
11390:             $resulttext .= '</ul>';
11391:         } else {
11392:             $resulttext = &mt('No changes made to help settings');
11393:             $errors .= '<li><span class="LC_error">'.
11394:                        &mt('An error occurred storing the settings: [_1]',
11395:                            $putresult).'</span></li>';
11396:         }
11397:     }
11398:     if ($errors) {
11399:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
11400:                        $errors.'</ul>';
11401:     }
11402:     return $resulttext;
11403: }
11404: 
11405: sub modify_coursedefaults {
11406:     my ($dom,$lastactref,%domconfig) = @_;
11407:     my ($resulttext,$errors,%changes,%defaultshash);
11408:     my %defaultchecked = (
11409:                            'canuse_pdfforms' => 'off',
11410:                            'uselcmath'       => 'on',
11411:                            'usejsme'         => 'on'
11412:                          );
11413:     my @toggles = ('canuse_pdfforms','uselcmath','usejsme');
11414:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
11415:                    'uploadquota_community','uploadquota_textbook','uploadquota_placement');
11416:     my @types = ('official','unofficial','community','textbook','placement');
11417:     my %staticdefaults = (
11418:                            anonsurvey_threshold => 10,
11419:                            uploadquota          => 500,
11420:                            postsubmit           => 60,
11421:                          );
11422: 
11423:     $defaultshash{'coursedefaults'} = {};
11424: 
11425:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
11426:         if ($domconfig{'coursedefaults'} eq '') {
11427:             $domconfig{'coursedefaults'} = {};
11428:         }
11429:     }
11430: 
11431:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
11432:         foreach my $item (@toggles) {
11433:             if ($defaultchecked{$item} eq 'on') {
11434:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
11435:                     ($env{'form.'.$item} eq '0')) {
11436:                     $changes{$item} = 1;
11437:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
11438:                     $changes{$item} = 1;
11439:                 }
11440:             } elsif ($defaultchecked{$item} eq 'off') {
11441:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
11442:                     ($env{'form.'.$item} eq '1')) {
11443:                     $changes{$item} = 1;
11444:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
11445:                     $changes{$item} = 1;
11446:                 }
11447:             }
11448:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
11449:         }
11450:         foreach my $item (@numbers) {
11451:             my ($currdef,$newdef);
11452:             $newdef = $env{'form.'.$item};
11453:             if ($item eq 'anonsurvey_threshold') {
11454:                 $currdef = $domconfig{'coursedefaults'}{$item};
11455:                 $newdef =~ s/\D//g;
11456:                 if ($newdef eq '' || $newdef < 1) {
11457:                     $newdef = 1;
11458:                 }
11459:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
11460:             } else {
11461:                 my ($type) = ($item =~ /^\Quploadquota_\E(\w+)$/);
11462:                 if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
11463:                     $currdef = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
11464:                 }
11465:                 $newdef =~ s/[^\w.\-]//g;
11466:                 $defaultshash{'coursedefaults'}{'uploadquota'}{$type} = $newdef;
11467:             }
11468:             if ($currdef ne $newdef) {
11469:                 my $staticdef;
11470:                 if ($item eq 'anonsurvey_threshold') {
11471:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
11472:                         $changes{$item} = 1;
11473:                     }
11474:                 } else {
11475:                     unless (($currdef eq '') && ($newdef == $staticdefaults{'uploadquota'})) {
11476:                         $changes{'uploadquota'} = 1;
11477:                     }
11478:                 }
11479:             }
11480:         }
11481:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
11482:         my @currclonecode;
11483:         if (ref($currclone) eq 'HASH') {
11484:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
11485:                 @currclonecode = @{$currclone->{'instcode'}};
11486:             }
11487:         }
11488:         my $newclone;
11489:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) { 
11490:             $newclone = $env{'form.canclone'};
11491:         }
11492:         if ($newclone eq 'instcode') {
11493:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
11494:             my (%codedefaults,@code_order,@clonecode);
11495:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
11496:                                                     \@code_order);
11497:             foreach my $item (@code_order) {
11498:                 if (grep(/^\Q$item\E$/,@newcodes)) {
11499:                     push(@clonecode,$item);
11500:                 }
11501:             }
11502:             if (@clonecode) {
11503:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
11504:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
11505:                 if (@diffs) {
11506:                     $changes{'canclone'} = 1;
11507:                 }
11508:             } else {
11509:                 $newclone eq '';
11510:             }
11511:         } elsif ($newclone ne '') {
11512:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone; 
11513:         } 
11514:         if ($newclone ne $currclone) {
11515:             $changes{'canclone'} = 1;
11516:         }
11517:         my %credits;
11518:         foreach my $type (@types) {
11519:             unless ($type eq 'community') {
11520:                 $credits{$type} = $env{'form.'.$type.'_credits'};
11521:                 $credits{$type} =~ s/[^\d.]+//g;
11522:             }
11523:         }
11524:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
11525:             ($env{'form.coursecredits'} eq '1')) {
11526:             $changes{'coursecredits'} = 1;
11527:             foreach my $type (keys(%credits)) {
11528:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
11529:             }
11530:         } else {
11531:             if ($env{'form.coursecredits'} eq '1') { 
11532:                 foreach my $type (@types) {
11533:                     unless ($type eq 'community') {
11534:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {        
11535:                             $changes{'coursecredits'} = 1;
11536:                         }
11537:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
11538:                     }
11539:                 }
11540:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
11541:                 foreach my $type (@types) {
11542:                     unless ($type eq 'community') {
11543:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
11544:                             $changes{'coursecredits'} = 1;
11545:                             last;
11546:                         }
11547:                     }
11548:                 }
11549:             }
11550:         }
11551:         if ($env{'form.postsubmit'} eq '1') {
11552:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
11553:             my %currtimeout;
11554:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
11555:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
11556:                     $changes{'postsubmit'} = 1;
11557:                 }
11558:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
11559:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
11560:                 }
11561:             } else {
11562:                 $changes{'postsubmit'} = 1;
11563:             }
11564:             foreach my $type (@types) {
11565:                 my $timeout = $env{'form.'.$type.'_timeout'};
11566:                 $timeout =~ s/\D//g;
11567:                 if ($timeout == $staticdefaults{'postsubmit'}) {
11568:                     $timeout = '';
11569:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
11570:                     $timeout = '0';
11571:                 }
11572:                 unless ($timeout eq '') {
11573:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
11574:                 }
11575:                 if (exists($currtimeout{$type})) {
11576:                     if ($timeout ne $currtimeout{$type}) {
11577:                         $changes{'postsubmit'} = 1; 
11578:                     }
11579:                 } elsif ($timeout ne '') {
11580:                     $changes{'postsubmit'} = 1;
11581:                 }
11582:             }
11583:         } else {
11584:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
11585:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
11586:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
11587:                     $changes{'postsubmit'} = 1;
11588:                 }
11589:             } else {
11590:                 $changes{'postsubmit'} = 1;
11591:             }
11592:         }
11593:     }
11594:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
11595:                                              $dom);
11596:     if ($putresult eq 'ok') {
11597:         if (keys(%changes) > 0) {
11598:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
11599:             if (($changes{'canuse_pdfforms'}) || ($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
11600:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
11601:                 ($changes{'canclone'})) {
11602:                 foreach my $item ('canuse_pdfforms','uselcmath','usejsme') { 
11603:                     if ($changes{$item}) {
11604:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
11605:                     }
11606:                 } 
11607:                 if ($changes{'coursecredits'}) {
11608:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
11609:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
11610:                             $domdefaults{$type.'credits'} =
11611:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
11612:                         }
11613:                     }
11614:                 }
11615:                 if ($changes{'postsubmit'}) {
11616:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
11617:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
11618:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
11619:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
11620:                                 $domdefaults{$type.'postsubtimeout'} =
11621:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
11622:                             }
11623:                         }
11624:                     }
11625:                 }
11626:                 if ($changes{'uploadquota'}) {
11627:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
11628:                         foreach my $type (@types) {
11629:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
11630:                         }
11631:                     }
11632:                 }
11633:                 if ($changes{'canclone'}) {
11634:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
11635:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
11636:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
11637:                             if (@clonecodes) {
11638:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
11639:                             }
11640:                         }
11641:                     } else {
11642:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
11643:                     }
11644:                 }
11645:                 my $cachetime = 24*60*60;
11646:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
11647:                 if (ref($lastactref) eq 'HASH') {
11648:                     $lastactref->{'domdefaults'} = 1;
11649:                 }
11650:             }
11651:             $resulttext = &mt('Changes made:').'<ul>';
11652:             foreach my $item (sort(keys(%changes))) {
11653:                 if ($item eq 'canuse_pdfforms') {
11654:                     if ($env{'form.'.$item} eq '1') {
11655:                         $resulttext .= '<li>'.&mt("Course/Community users can create/upload PDF forms set to 'on'").'</li>';
11656:                     } else {
11657:                         $resulttext .= '<li>'.&mt('Course/Community users can create/upload PDF forms set to "off"').'</li>';
11658:                     }
11659:                 } elsif ($item eq 'uselcmath') {
11660:                     if ($env{'form.'.$item} eq '1') {
11661:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
11662:                     } else {
11663:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
11664:                     }
11665:                 } elsif ($item eq 'usejsme') {
11666:                     if ($env{'form.'.$item} eq '1') {
11667:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
11668:                     } else {
11669:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>'; 
11670:                     }
11671:                 } elsif ($item eq 'anonsurvey_threshold') {
11672:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
11673:                 } elsif ($item eq 'uploadquota') {
11674:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
11675:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
11676:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
11677:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
11678:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
11679:                                        '<li>'.&mt('Placement tests: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'placement'}.'</b>').'</li>'. 
11680:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
11681:                                        '</ul>'.
11682:                                        '</li>';
11683:                     } else {
11684:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
11685:                     }
11686:                 } elsif ($item eq 'postsubmit') {
11687:                     if ($domdefaults{'postsubmit'} eq 'off') {
11688:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
11689:                     } else {
11690:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
11691:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') { 
11692:                             $resulttext .= &mt('durations:').'<ul>';
11693:                             foreach my $type (@types) {
11694:                                 $resulttext .= '<li>';
11695:                                 my $timeout;
11696:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
11697:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
11698:                                 }
11699:                                 my $display;
11700:                                 if ($timeout eq '0') {
11701:                                     $display = &mt('unlimited');
11702:                                 } elsif ($timeout eq '') {
11703:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
11704:                                 } else {
11705:                                     $display = &mt('[quant,_1,second]',$timeout);
11706:                                 }
11707:                                 if ($type eq 'community') {
11708:                                     $resulttext .= &mt('Communities');
11709:                                 } elsif ($type eq 'official') {
11710:                                     $resulttext .= &mt('Official courses');
11711:                                 } elsif ($type eq 'unofficial') {
11712:                                     $resulttext .= &mt('Unofficial courses');
11713:                                 } elsif ($type eq 'textbook') {
11714:                                     $resulttext .= &mt('Textbook courses');
11715:                                 } elsif ($type eq 'placement') {
11716:                                     $resulttext .= &mt('Placement tests');
11717:                                 }
11718:                                 $resulttext .= ' -- '.$display.'</li>';
11719:                             }
11720:                             $resulttext .= '</ul>';
11721:                         }
11722:                         $resulttext .= '</li>';    
11723:                     }
11724:                 } elsif ($item eq 'coursecredits') {
11725:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
11726:                         if (($domdefaults{'officialcredits'} eq '') &&
11727:                             ($domdefaults{'unofficialcredits'} eq '') &&
11728:                             ($domdefaults{'textbookcredits'} eq '')) {
11729:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
11730:                         } else {
11731:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
11732:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
11733:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
11734:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
11735:                                            '</ul>'.
11736:                                            '</li>';
11737:                         }
11738:                     } else {
11739:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
11740:                     }
11741:                 } elsif ($item eq 'canclone') {
11742:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
11743:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
11744:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
11745:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
11746:                         }
11747:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
11748:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
11749:                     } else {
11750:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>'; 
11751:                     }
11752:                 }
11753:             }
11754:             $resulttext .= '</ul>';
11755:         } else {
11756:             $resulttext = &mt('No changes made to course defaults');
11757:         }
11758:     } else {
11759:         $resulttext = '<span class="LC_error">'.
11760:             &mt('An error occurred: [_1]',$putresult).'</span>';
11761:     }
11762:     return $resulttext;
11763: }
11764: 
11765: sub modify_selfenrollment {
11766:     my ($dom,$lastactref,%domconfig) = @_;
11767:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
11768:     my @types = ('official','unofficial','community','textbook','placement');
11769:     my %titles = &tool_titles();
11770:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
11771:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
11772:     $ordered{'default'} = ['types','registered','approval','limit'];
11773: 
11774:     my (%roles,%shown,%toplevel);
11775:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
11776: 
11777:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
11778:         if ($domconfig{'selfenrollment'} eq '') {
11779:             $domconfig{'selfenrollment'} = {};
11780:         }
11781:     }
11782:     %toplevel = (
11783:                   admin      => 'Configuration Rights',
11784:                   default    => 'Default settings',
11785:                   validation => 'Validation of self-enrollment requests',
11786:                 );
11787:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
11788: 
11789:     if (ref($ordered{'admin'}) eq 'ARRAY') {
11790:         foreach my $item (@{$ordered{'admin'}}) {
11791:             foreach my $type (@types) {
11792:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
11793:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
11794:                 } else {
11795:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
11796:                 }
11797:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
11798:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
11799:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
11800:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
11801:                             push(@{$changes{'admin'}{$type}},$item);
11802:                         }
11803:                     } else {
11804:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
11805:                             push(@{$changes{'admin'}{$type}},$item);
11806:                         }
11807:                     }
11808:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
11809:                     push(@{$changes{'admin'}{$type}},$item);
11810:                 }
11811:             }
11812:         }
11813:     }
11814: 
11815:     foreach my $item (@{$ordered{'default'}}) {
11816:         foreach my $type (@types) {
11817:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
11818:             if ($item eq 'types') {
11819:                 unless (($value eq 'all') || ($value eq 'dom')) {
11820:                     $value = '';
11821:                 }
11822:             } elsif ($item eq 'registered') {
11823:                 unless ($value eq '1') {
11824:                     $value = 0;
11825:                 }
11826:             } elsif ($item eq 'approval') {
11827:                 unless ($value =~ /^[012]$/) {
11828:                     $value = 0;
11829:                 }
11830:             } else {
11831:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
11832:                     $value = 'none';
11833:                 }
11834:             }
11835:             $selfenrollhash{'default'}{$type}{$item} = $value;
11836:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
11837:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
11838:                     if ($selfenrollhash{'default'}{$type}{$item} ne
11839:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
11840:                          push(@{$changes{'default'}{$type}},$item);
11841:                     }
11842:                 } else {
11843:                     push(@{$changes{'default'}{$type}},$item);
11844:                 }
11845:             } else {
11846:                 push(@{$changes{'default'}{$type}},$item);
11847:             }
11848:             if ($item eq 'limit') {
11849:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
11850:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
11851:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
11852:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
11853:                     }
11854:                 } else {
11855:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
11856:                 }
11857:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
11858:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
11859:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
11860:                          push(@{$changes{'default'}{$type}},'cap');
11861:                     }
11862:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
11863:                     push(@{$changes{'default'}{$type}},'cap');
11864:                 }
11865:             }
11866:         }
11867:     }
11868: 
11869:     foreach my $item (@{$itemsref}) {
11870:         if ($item eq 'fields') {
11871:             my @changed;
11872:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
11873:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
11874:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
11875:             }
11876:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
11877:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
11878:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
11879:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
11880:                 } else {
11881:                     @changed = @{$selfenrollhash{'validation'}{$item}};
11882:                 }
11883:             } else {
11884:                 @changed = @{$selfenrollhash{'validation'}{$item}};
11885:             }
11886:             if (@changed) {
11887:                 if ($selfenrollhash{'validation'}{$item}) { 
11888:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
11889:                 } else {
11890:                     $changes{'validation'}{$item} = &mt('None');
11891:                 }
11892:             }
11893:         } else {
11894:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
11895:             if ($item eq 'markup') {
11896:                if ($env{'form.selfenroll_validation_'.$item}) {
11897:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
11898:                }
11899:             }
11900:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
11901:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
11902:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
11903:                 }
11904:             }
11905:         }
11906:     }
11907: 
11908:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
11909:                                              $dom);
11910:     if ($putresult eq 'ok') {
11911:         if (keys(%changes) > 0) {
11912:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
11913:             $resulttext = &mt('Changes made:').'<ul>';
11914:             foreach my $key ('admin','default','validation') {
11915:                 if (ref($changes{$key}) eq 'HASH') {
11916:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
11917:                     if ($key eq 'validation') {
11918:                         foreach my $item (@{$itemsref}) {
11919:                             if (exists($changes{$key}{$item})) {
11920:                                 if ($item eq 'markup') {
11921:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
11922:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
11923:                                 } else {  
11924:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
11925:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
11926:                                 }
11927:                             }
11928:                         }
11929:                     } else {
11930:                         foreach my $type (@types) {
11931:                             if ($type eq 'community') {
11932:                                 $roles{'1'} = &mt('Community personnel');
11933:                             } else {
11934:                                 $roles{'1'} = &mt('Course personnel');
11935:                             }
11936:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
11937:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
11938:                                     if ($key eq 'admin') {
11939:                                         my @mgrdc = ();
11940:                                         if (ref($ordered{$key}) eq 'ARRAY') {
11941:                                             foreach my $item (@{$ordered{'admin'}}) {
11942:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
11943:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
11944:                                                         push(@mgrdc,$item);
11945:                                                     }
11946:                                                 }
11947:                                             }
11948:                                             if (@mgrdc) {
11949:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
11950:                                             } else {
11951:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
11952:                                             }
11953:                                         }
11954:                                     } else {
11955:                                         if (ref($ordered{$key}) eq 'ARRAY') {
11956:                                             foreach my $item (@{$ordered{$key}}) {
11957:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
11958:                                                     $domdefaults{$type.'selfenroll'.$item} =
11959:                                                         $selfenrollhash{$key}{$type}{$item};
11960:                                                 }
11961:                                             }
11962:                                         }
11963:                                     }
11964:                                 }
11965:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
11966:                                 foreach my $item (@{$ordered{$key}}) {
11967:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
11968:                                         $resulttext .= '<li>';
11969:                                         if ($key eq 'admin') {
11970:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
11971:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
11972:                                         } else {
11973:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
11974:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
11975:                                         }
11976:                                         $resulttext .= '</li>';
11977:                                     }
11978:                                 }
11979:                                 $resulttext .= '</ul></li>';
11980:                             }
11981:                         }
11982:                         $resulttext .= '</ul></li>'; 
11983:                     }
11984:                 }
11985:                 if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
11986:                     my $cachetime = 24*60*60;
11987:                     &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
11988:                     if (ref($lastactref) eq 'HASH') {
11989:                         $lastactref->{'domdefaults'} = 1;
11990:                     }
11991:                 }
11992:             }
11993:             $resulttext .= '</ul>';
11994:         } else {
11995:             $resulttext = &mt('No changes made to self-enrollment settings');
11996:         }
11997:     } else {
11998:         $resulttext = '<span class="LC_error">'.
11999:             &mt('An error occurred: [_1]',$putresult).'</span>';
12000:     }
12001:     return $resulttext;
12002: }
12003: 
12004: sub modify_usersessions {
12005:     my ($dom,$lastactref,%domconfig) = @_;
12006:     my @hostingtypes = ('version','excludedomain','includedomain');
12007:     my @offloadtypes = ('primary','default');
12008:     my %types = (
12009:                   remote => \@hostingtypes,
12010:                   hosted => \@hostingtypes,
12011:                   spares => \@offloadtypes,
12012:                 );
12013:     my @prefixes = ('remote','hosted','spares');
12014:     my @lcversions = &Apache::lonnet::all_loncaparevs();
12015:     my (%by_ip,%by_location,@intdoms);
12016:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
12017:     my @locations = sort(keys(%by_location));
12018:     my (%defaultshash,%changes);
12019:     foreach my $prefix (@prefixes) {
12020:         $defaultshash{'usersessions'}{$prefix} = {};
12021:     }
12022:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12023:     my $resulttext;
12024:     my %iphost = &Apache::lonnet::get_iphost();
12025:     foreach my $prefix (@prefixes) {
12026:         next if ($prefix eq 'spares');
12027:         foreach my $type (@{$types{$prefix}}) {
12028:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
12029:             if ($type eq 'version') {
12030:                 my $value = $env{'form.'.$prefix.'_'.$type};
12031:                 my $okvalue;
12032:                 if ($value ne '') {
12033:                     if (grep(/^\Q$value\E$/,@lcversions)) {
12034:                         $okvalue = $value;
12035:                     }
12036:                 }
12037:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
12038:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
12039:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
12040:                             if ($inuse == 0) {
12041:                                 $changes{$prefix}{$type} = 1;
12042:                             } else {
12043:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
12044:                                     $changes{$prefix}{$type} = 1;
12045:                                 }
12046:                                 if ($okvalue ne '') {
12047:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
12048:                                 } 
12049:                             }
12050:                         } else {
12051:                             if (($inuse == 1) && ($okvalue ne '')) {
12052:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
12053:                                 $changes{$prefix}{$type} = 1;
12054:                             }
12055:                         }
12056:                     } else {
12057:                         if (($inuse == 1) && ($okvalue ne '')) {
12058:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
12059:                             $changes{$prefix}{$type} = 1;
12060:                         }
12061:                     }
12062:                 } else {
12063:                     if (($inuse == 1) && ($okvalue ne '')) {
12064:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
12065:                         $changes{$prefix}{$type} = 1;
12066:                     }
12067:                 }
12068:             } else {
12069:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
12070:                 my @okvals;
12071:                 foreach my $val (@vals) {
12072:                     if ($val =~ /:/) {
12073:                         my @items = split(/:/,$val);
12074:                         foreach my $item (@items) {
12075:                             if (ref($by_location{$item}) eq 'ARRAY') {
12076:                                 push(@okvals,$item);
12077:                             }
12078:                         }
12079:                     } else {
12080:                         if (ref($by_location{$val}) eq 'ARRAY') {
12081:                             push(@okvals,$val);
12082:                         }
12083:                     }
12084:                 }
12085:                 @okvals = sort(@okvals);
12086:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
12087:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
12088:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
12089:                             if ($inuse == 0) {
12090:                                 $changes{$prefix}{$type} = 1; 
12091:                             } else {
12092:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
12093:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
12094:                                 if (@changed > 0) {
12095:                                     $changes{$prefix}{$type} = 1;
12096:                                 }
12097:                             }
12098:                         } else {
12099:                             if ($inuse == 1) {
12100:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
12101:                                 $changes{$prefix}{$type} = 1;
12102:                             }
12103:                         } 
12104:                     } else {
12105:                         if ($inuse == 1) {
12106:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
12107:                             $changes{$prefix}{$type} = 1;
12108:                         }
12109:                     }
12110:                 } else {
12111:                     if ($inuse == 1) {
12112:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
12113:                         $changes{$prefix}{$type} = 1;
12114:                     }
12115:                 }
12116:             }
12117:         }
12118:     }
12119: 
12120:     my @alldoms = &Apache::lonnet::all_domains();
12121:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
12122:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
12123:     my $savespares;
12124: 
12125:     foreach my $lonhost (sort(keys(%servers))) {
12126:         my $serverhomeID =
12127:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
12128:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
12129:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
12130:         my %spareschg;
12131:         foreach my $type (@{$types{'spares'}}) {
12132:             my @okspares;
12133:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
12134:             foreach my $server (@checked) {
12135:                 if (&Apache::lonnet::hostname($server) ne '') {
12136:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
12137:                         unless (grep(/^\Q$server\E$/,@okspares)) {
12138:                             push(@okspares,$server);
12139:                         }
12140:                     }
12141:                 }
12142:             }
12143:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
12144:             my $newspare;
12145:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
12146:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
12147:                     $newspare = $new;
12148:                 }
12149:             }
12150:             my @spares;
12151:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
12152:                 @spares = sort(@okspares,$newspare);
12153:             } else {
12154:                 @spares = sort(@okspares);
12155:             }
12156:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
12157:             if (ref($spareid{$lonhost}) eq 'HASH') {
12158:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
12159:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
12160:                     if (@diffs > 0) {
12161:                         $spareschg{$type} = 1;
12162:                     }
12163:                 }
12164:             }
12165:         }
12166:         if (keys(%spareschg) > 0) {
12167:             $changes{'spares'}{$lonhost} = \%spareschg;
12168:         }
12169:     }
12170:     $defaultshash{'usersessions'}{'offloadnow'} = {};
12171:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
12172:     my @okoffload;
12173:     if (@offloadnow) {
12174:         foreach my $server (@offloadnow) {
12175:             if (&Apache::lonnet::hostname($server) ne '') {
12176:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
12177:                     push(@okoffload,$server);
12178:                 }
12179:             }
12180:         }
12181:         if (@okoffload) {
12182:             foreach my $lonhost (@okoffload) {
12183:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
12184:             }
12185:         }
12186:     }
12187:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
12188:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
12189:             if (ref($changes{'spares'}) eq 'HASH') {
12190:                 if (keys(%{$changes{'spares'}}) > 0) {
12191:                     $savespares = 1;
12192:                 }
12193:             }
12194:         } else {
12195:             $savespares = 1;
12196:         }
12197:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
12198:             foreach my $lonhost (keys(%{$domconfig{'usersessions'}{'offloadnow'}})) {
12199:                 unless ($defaultshash{'usersessions'}{'offloadnow'}{$lonhost}) {
12200:                     $changes{'offloadnow'} = 1;
12201:                     last;
12202:                 }
12203:             }
12204:             unless ($changes{'offloadnow'}) {
12205:                 foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{'offloadnow'}})) { 
12206:                     unless ($domconfig{'usersessions'}{'offloadnow'}{$lonhost}) {
12207:                         $changes{'offloadnow'} = 1;
12208:                         last;
12209:                     }
12210:                 }
12211:             }
12212:         } elsif (@okoffload) {
12213:             $changes{'offloadnow'} = 1;
12214:         }
12215:     } elsif (@okoffload) {
12216:         $changes{'offloadnow'} = 1;
12217:     }
12218:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
12219:     if ((keys(%changes) > 0) || ($savespares)) {
12220:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
12221:                                                  $dom);
12222:         if ($putresult eq 'ok') {
12223:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
12224:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
12225:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
12226:                 }
12227:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
12228:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
12229:                 }
12230:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
12231:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
12232:                 }
12233:             }
12234:             my $cachetime = 24*60*60;
12235:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
12236:             if (ref($lastactref) eq 'HASH') {
12237:                 $lastactref->{'domdefaults'} = 1;
12238:             }
12239:             if (keys(%changes) > 0) {
12240:                 my %lt = &usersession_titles();
12241:                 $resulttext = &mt('Changes made:').'<ul>';
12242:                 foreach my $prefix (@prefixes) {
12243:                     if (ref($changes{$prefix}) eq 'HASH') {
12244:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
12245:                         if ($prefix eq 'spares') {
12246:                             if (ref($changes{$prefix}) eq 'HASH') {
12247:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
12248:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
12249:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
12250:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
12251:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
12252:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
12253:                                         foreach my $type (@{$types{$prefix}}) {
12254:                                             if ($changes{$prefix}{$lonhost}{$type}) {
12255:                                                 my $offloadto = &mt('None');
12256:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
12257:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
12258:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
12259:                                                     }
12260:                                                 }
12261:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
12262:                                             }
12263:                                         }
12264:                                     }
12265:                                     $resulttext .= '</li>';
12266:                                 }
12267:                             }
12268:                         } else {
12269:                             foreach my $type (@{$types{$prefix}}) {
12270:                                 if (defined($changes{$prefix}{$type})) {
12271:                                     my $newvalue;
12272:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
12273:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
12274:                                             if ($type eq 'version') {
12275:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
12276:                                             } elsif (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
12277:                                                 if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
12278:                                                     $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
12279:                                                 }
12280:                                             }
12281:                                         }
12282:                                     }
12283:                                     if ($newvalue eq '') {
12284:                                         if ($type eq 'version') {
12285:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
12286:                                         } else {
12287:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
12288:                                         }
12289:                                     } else {
12290:                                         if ($type eq 'version') {
12291:                                             $newvalue .= ' '.&mt('(or later)'); 
12292:                                         }
12293:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
12294:                                     }
12295:                                 }
12296:                             }
12297:                         }
12298:                         $resulttext .= '</ul>';
12299:                     }
12300:                 }
12301:                 if ($changes{'offloadnow'}) {
12302:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
12303:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
12304:                             $resulttext .= '<li>'.&mt('Switch active users on next access, for server(s):').'<ul>';
12305:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
12306:                                 $resulttext .= '<li>'.$lonhost.'</li>';
12307:                             }
12308:                             $resulttext .= '</ul>';
12309:                         } else {
12310:                             $resulttext .= '<li>'.&mt('No servers now set to switch active users on next access.');
12311:                         }
12312:                     } else {
12313:                         $resulttext .= '<li>'.&mt('No servers now set to switch active users on next access.').'</li>';
12314:                     }
12315:                 }
12316:                 $resulttext .= '</ul>';
12317:             } else {
12318:                 $resulttext = $nochgmsg;
12319:             }
12320:         } else {
12321:             $resulttext = '<span class="LC_error">'.
12322:                           &mt('An error occurred: [_1]',$putresult).'</span>';
12323:         }
12324:     } else {
12325:         $resulttext = $nochgmsg;
12326:     }
12327:     return $resulttext;
12328: }
12329: 
12330: sub modify_loadbalancing {
12331:     my ($dom,%domconfig) = @_;
12332:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
12333:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
12334:     my ($othertitle,$usertypes,$types) =
12335:         &Apache::loncommon::sorted_inst_types($dom);
12336:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
12337:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
12338:     my @sparestypes = ('primary','default');
12339:     my %typetitles = &sparestype_titles();
12340:     my $resulttext;
12341:     my (%currbalancer,%currtargets,%currrules,%existing);
12342:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
12343:         %existing = %{$domconfig{'loadbalancing'}};
12344:     }
12345:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
12346:                               \%currtargets,\%currrules);
12347:     my ($saveloadbalancing,%defaultshash,%changes);
12348:     my ($alltypes,$othertypes,$titles) =
12349:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
12350:     my %ruletitles = &offloadtype_text();
12351:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
12352:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
12353:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
12354:         if ($balancer eq '') {
12355:             next;
12356:         }
12357:         if (!exists($servers{$balancer})) {
12358:             if (exists($currbalancer{$balancer})) {
12359:                 push(@{$changes{'delete'}},$balancer);
12360:             }
12361:             next;
12362:         }
12363:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
12364:             push(@{$changes{'delete'}},$balancer);
12365:             next;
12366:         }
12367:         if (!exists($currbalancer{$balancer})) {
12368:             push(@{$changes{'add'}},$balancer);
12369:         }
12370:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
12371:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
12372:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
12373:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
12374:             $saveloadbalancing = 1;
12375:         }
12376:         foreach my $sparetype (@sparestypes) {
12377:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
12378:             my @offloadto;
12379:             foreach my $target (@targets) {
12380:                 if (($servers{$target}) && ($target ne $balancer)) {
12381:                     if ($sparetype eq 'default') {
12382:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
12383:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
12384:                         }
12385:                     }
12386:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
12387:                         push(@offloadto,$target);
12388:                     }
12389:                 }
12390:                 $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
12391:             }
12392:         }
12393:         if (ref($currtargets{$balancer}) eq 'HASH') {
12394:             foreach my $sparetype (@sparestypes) {
12395:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
12396:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
12397:                     if (@targetdiffs > 0) {
12398:                         $changes{'curr'}{$balancer}{'targets'} = 1;
12399:                     }
12400:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
12401:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
12402:                         $changes{'curr'}{$balancer}{'targets'} = 1;
12403:                     }
12404:                 }
12405:             }
12406:         } else {
12407:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
12408:                 foreach my $sparetype (@sparestypes) {
12409:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
12410:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
12411:                             $changes{'curr'}{$balancer}{'targets'} = 1;
12412:                         }
12413:                     }
12414:                 }
12415:             }
12416:         }
12417:         my $ishomedom;
12418:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
12419:             $ishomedom = 1;
12420:         }
12421:         if (ref($alltypes) eq 'ARRAY') {
12422:             foreach my $type (@{$alltypes}) {
12423:                 my $rule;
12424:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
12425:                          (!$ishomedom)) {
12426:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
12427:                 }
12428:                 if ($rule eq 'specific') {
12429:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
12430:                     if (exists($servers{$specifiedhost})) { 
12431:                         $rule = $specifiedhost;
12432:                     }
12433:                 }
12434:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
12435:                 if (ref($currrules{$balancer}) eq 'HASH') {
12436:                     if ($rule ne $currrules{$balancer}{$type}) {
12437:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
12438:                     }
12439:                 } elsif ($rule ne '') {
12440:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
12441:                 }
12442:             }
12443:         }
12444:     }
12445:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
12446:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
12447:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
12448:             $defaultshash{'loadbalancing'} = {};
12449:         }
12450:         my $putresult = &Apache::lonnet::put_dom('configuration',
12451:                                                  \%defaultshash,$dom);
12452:         if ($putresult eq 'ok') {
12453:             if (keys(%changes) > 0) {
12454:                 my %toupdate;
12455:                 if (ref($changes{'delete'}) eq 'ARRAY') {
12456:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
12457:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
12458:                         $toupdate{$balancer} = 1;
12459:                     }
12460:                 }
12461:                 if (ref($changes{'add'}) eq 'ARRAY') {
12462:                     foreach my $balancer (sort(@{$changes{'add'}})) {
12463:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
12464:                         $toupdate{$balancer} = 1;
12465:                     }
12466:                 }
12467:                 if (ref($changes{'curr'}) eq 'HASH') {
12468:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
12469:                         $toupdate{$balancer} = 1;
12470:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
12471:                             if ($changes{'curr'}{$balancer}{'targets'}) {
12472:                                 my %offloadstr;
12473:                                 foreach my $sparetype (@sparestypes) {
12474:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
12475:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
12476:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
12477:                                         }
12478:                                     }
12479:                                 }
12480:                                 if (keys(%offloadstr) == 0) {
12481:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
12482:                                 } else {
12483:                                     my $showoffload;
12484:                                     foreach my $sparetype (@sparestypes) {
12485:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
12486:                                         if (defined($offloadstr{$sparetype})) {
12487:                                             $showoffload .= $offloadstr{$sparetype};
12488:                                         } else {
12489:                                             $showoffload .= &mt('None');
12490:                                         }
12491:                                         $showoffload .= ('&nbsp;'x3);
12492:                                     }
12493:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
12494:                                 }
12495:                             }
12496:                         }
12497:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
12498:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
12499:                                 foreach my $type (@{$alltypes}) {
12500:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
12501:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
12502:                                         my $balancetext;
12503:                                         if ($rule eq '') {
12504:                                             $balancetext =  $ruletitles{'default'};
12505:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
12506:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) { 
12507:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
12508:                                                 foreach my $sparetype (@sparestypes) {
12509:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
12510:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
12511:                                                     }
12512:                                                 }
12513:                                                 foreach my $item (@{$alltypes}) {
12514:                                                     next if ($item =~  /^_LC_ipchange/);
12515:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
12516:                                                     if ($hasrule eq 'homeserver') {
12517:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
12518:                                                     } else {
12519:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
12520:                                                             if ($servers{$hasrule}) {
12521:                                                                 $toupdate{$hasrule} = 1;
12522:                                                             }
12523:                                                         }
12524:                                                     }
12525:                                                 }
12526:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
12527:                                                     $balancetext =  $ruletitles{$rule};
12528:                                                 } else {
12529:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
12530:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
12531:                                                     if ($receiver) {
12532:                                                         $toupdate{$receiver};
12533:                                                     }
12534:                                                 }
12535:                                             } else {
12536:                                                 $balancetext =  $ruletitles{$rule};
12537:                                             }
12538:                                         } else {
12539:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
12540:                                         }
12541:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
12542:                                     }
12543:                                 }
12544:                             }
12545:                         }
12546:                         if (keys(%toupdate)) {
12547:                             my %thismachine;
12548:                             my $updatedhere;
12549:                             my $cachetime = 60*60*24;
12550:                             map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
12551:                             foreach my $lonhost (keys(%toupdate)) {
12552:                                 if ($thismachine{$lonhost}) {
12553:                                     unless ($updatedhere) {
12554:                                         &Apache::lonnet::do_cache_new('loadbalancing',$dom,
12555:                                                                       $defaultshash{'loadbalancing'},
12556:                                                                       $cachetime);
12557:                                         $updatedhere = 1;
12558:                                     }
12559:                                 } else {
12560:                                     my $cachekey = &escape('loadbalancing').':'.&escape($dom);
12561:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
12562:                                 }
12563:                             }
12564:                         }
12565:                     }
12566:                 }
12567:                 if ($resulttext ne '') {
12568:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
12569:                 } else {
12570:                     $resulttext = $nochgmsg;
12571:                 }
12572:             } else {
12573:                 $resulttext = $nochgmsg;
12574:             }
12575:         } else {
12576:             $resulttext = '<span class="LC_error">'.
12577:                           &mt('An error occurred: [_1]',$putresult).'</span>';
12578:         }
12579:     } else {
12580:         $resulttext = $nochgmsg;
12581:     }
12582:     return $resulttext;
12583: }
12584: 
12585: sub recurse_check {
12586:     my ($chkcats,$categories,$depth,$name) = @_;
12587:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
12588:         my $chg = 0;
12589:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
12590:             my $category = $chkcats->[$depth]{$name}[$j];
12591:             my $item;
12592:             if ($category eq '') {
12593:                 $chg ++;
12594:             } else {
12595:                 my $deeper = $depth + 1;
12596:                 $item = &escape($category).':'.&escape($name).':'.$depth;
12597:                 if ($chg) {
12598:                     $categories->{$item} -= $chg;
12599:                 }
12600:                 &recurse_check($chkcats,$categories,$deeper,$category);
12601:                 $deeper --;
12602:             }
12603:         }
12604:     }
12605:     return;
12606: }
12607: 
12608: sub recurse_cat_deletes {
12609:     my ($item,$coursecategories,$deletions) = @_;
12610:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
12611:     my $subdepth = $depth + 1;
12612:     if (ref($coursecategories) eq 'HASH') {
12613:         foreach my $subitem (keys(%{$coursecategories})) {
12614:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
12615:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
12616:                 delete($coursecategories->{$subitem});
12617:                 $deletions->{$subitem} = 1;
12618:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
12619:             }
12620:         }
12621:     }
12622:     return;
12623: }
12624: 
12625: sub get_active_dcs {
12626:     my ($dom) = @_;
12627:     my $now = time;
12628:     my %dompersonnel = &Apache::lonnet::get_domain_roles($dom,['dc'],$now,$now);
12629:     my %domcoords;
12630:     my $numdcs = 0;
12631:     foreach my $server (keys(%dompersonnel)) {
12632:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
12633:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
12634:             $domcoords{$uname.':'.$udom} = $dompersonnel{$server}{$user};
12635:         }
12636:     }
12637:     return %domcoords;
12638: }
12639: 
12640: sub active_dc_picker {
12641:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
12642:     my %domcoords = &get_active_dcs($dom);
12643:     my @domcoord = keys(%domcoords);
12644:     if (keys(%currhash)) {
12645:         foreach my $dc (keys(%currhash)) {
12646:             unless (exists($domcoords{$dc})) {
12647:                 push(@domcoord,$dc);
12648:             }
12649:         }
12650:     }
12651:     @domcoord = sort(@domcoord);
12652:     my $numdcs = scalar(@domcoord);
12653:     my $rows = 0;
12654:     my $table;
12655:     if ($numdcs > 1) {
12656:         $table = '<table>';
12657:         for (my $i=0; $i<@domcoord; $i++) {
12658:             my $rem = $i%($numinrow);
12659:             if ($rem == 0) {
12660:                 if ($i > 0) {
12661:                     $table .= '</tr>';
12662:                 }
12663:                 $table .= '<tr>';
12664:                 $rows ++;
12665:             }
12666:             my $check = '';
12667:             if ($inputtype eq 'radio') {
12668:                 if (keys(%currhash) == 0) {
12669:                     if (!$i) {
12670:                         $check = ' checked="checked"';
12671:                     }
12672:                 } elsif (exists($currhash{$domcoord[$i]})) {
12673:                     $check = ' checked="checked"';
12674:                 }
12675:             } else {
12676:                 if (exists($currhash{$domcoord[$i]})) {
12677:                     $check = ' checked="checked"';
12678:                 }
12679:             }
12680:             if ($i == @domcoord - 1) {
12681:                 my $colsleft = $numinrow - $rem;
12682:                 if ($colsleft > 1) {
12683:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
12684:                 } else {
12685:                     $table .= '<td class="LC_left_item">';
12686:                 }
12687:             } else {
12688:                 $table .= '<td class="LC_left_item">';
12689:             }
12690:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
12691:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
12692:             $table .= '<span class="LC_nobreak"><label>'.
12693:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
12694:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
12695:             if ($user ne $dcname.':'.$dcdom) {
12696:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
12697:             }
12698:             $table .= '</label></span></td>';
12699:         }
12700:         $table .= '</tr></table>';
12701:     } elsif ($numdcs == 1) {
12702:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
12703:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
12704:         if ($inputtype eq 'radio') {
12705:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
12706:             if ($user ne $dcname.':'.$dcdom) {
12707:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
12708:             }
12709:         } else {
12710:             my $check;
12711:             if (exists($currhash{$domcoord[0]})) {
12712:                 $check = ' checked="checked"';
12713:             }
12714:             $table = '<span class="LC_nobreak"><label>'.
12715:                      '<input type="checkbox" name="'.$name.'" '.
12716:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
12717:             if ($user ne $dcname.':'.$dcdom) {
12718:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
12719:             }
12720:             $table .= '</label></span>';
12721:             $rows ++;
12722:         }
12723:     }
12724:     return ($numdcs,$table,$rows);
12725: }
12726: 
12727: sub usersession_titles {
12728:     return &Apache::lonlocal::texthash(
12729:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
12730:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
12731:                spares => 'Servers offloaded to, when busy',
12732:                version => 'LON-CAPA version requirement',
12733:                excludedomain => 'Allow all, but exclude specific domains',
12734:                includedomain => 'Deny all, but include specific domains',
12735:                primary => 'Primary (checked first)',
12736:                default => 'Default',
12737:            );
12738: }
12739: 
12740: sub id_for_thisdom {
12741:     my (%servers) = @_;
12742:     my %altids;
12743:     foreach my $server (keys(%servers)) {
12744:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
12745:         if ($serverhome ne $server) {
12746:             $altids{$serverhome} = $server;
12747:         }
12748:     }
12749:     return %altids;
12750: }
12751: 
12752: sub count_servers {
12753:     my ($currbalancer,%servers) = @_;
12754:     my (@spares,$numspares);
12755:     foreach my $lonhost (sort(keys(%servers))) {
12756:         next if ($currbalancer eq $lonhost);
12757:         push(@spares,$lonhost);
12758:     }
12759:     if ($currbalancer) {
12760:         $numspares = scalar(@spares);
12761:     } else {
12762:         $numspares = scalar(@spares) - 1;
12763:     }
12764:     return ($numspares,@spares);
12765: }
12766: 
12767: sub lonbalance_targets_js {
12768:     my ($dom,$types,$servers,$settings) = @_;
12769:     my $select = &mt('Select');
12770:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
12771:     if (ref($servers) eq 'HASH') {
12772:         $alltargets = join("','",sort(keys(%{$servers})));
12773:         my @homedoms;
12774:         foreach my $server (sort(keys(%{$servers}))) {
12775:             if (&Apache::lonnet::host_domain($server) eq $dom) {
12776:                 push(@homedoms,'1');
12777:             } else {
12778:                 push(@homedoms,'0');
12779:             }
12780:         }
12781:         $allishome = join("','",@homedoms);
12782:     }
12783:     if (ref($types) eq 'ARRAY') {
12784:         if (@{$types} > 0) {
12785:             @alltypes = @{$types};
12786:         }
12787:     }
12788:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
12789:     $allinsttypes = join("','",@alltypes);
12790:     my (%currbalancer,%currtargets,%currrules,%existing);
12791:     if (ref($settings) eq 'HASH') {
12792:         %existing = %{$settings};
12793:     }
12794:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
12795:                               \%currtargets,\%currrules);
12796:     my $balancers = join("','",sort(keys(%currbalancer)));
12797:     return <<"END";
12798: 
12799: <script type="text/javascript">
12800: // <![CDATA[
12801: 
12802: currBalancers = new Array('$balancers');
12803: 
12804: function toggleTargets(balnum) {
12805:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
12806:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
12807:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
12808:     var prevbalancer = prevhostitem.value;
12809:     var baltotal = document.getElementById('loadbalancing_total').value;
12810:     prevhostitem.value = balancer;
12811:     if (prevbalancer != '') {
12812:         var prevIdx = currBalancers.indexOf(prevbalancer);
12813:         if (prevIdx != -1) {
12814:             currBalancers.splice(prevIdx,1);
12815:         }
12816:     }
12817:     if (balancer == '') {
12818:         hideSpares(balnum);
12819:     } else {
12820:         var currIdx = currBalancers.indexOf(balancer);
12821:         if (currIdx == -1) {
12822:             currBalancers.push(balancer);
12823:         }
12824:         var homedoms = new Array('$allishome');
12825:         var ishomedom = homedoms[lonhostitem.selectedIndex];
12826:         showSpares(balancer,ishomedom,balnum);
12827:     }
12828:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
12829:     return;
12830: }
12831: 
12832: function showSpares(balancer,ishomedom,balnum) {
12833:     var alltargets = new Array('$alltargets');
12834:     var insttypes = new Array('$allinsttypes');
12835:     var offloadtypes = new Array('primary','default');
12836: 
12837:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
12838:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
12839:  
12840:     for (var i=0; i<offloadtypes.length; i++) {
12841:         var count = 0;
12842:         for (var j=0; j<alltargets.length; j++) {
12843:             if (alltargets[j] != balancer) {
12844:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
12845:                 item.value = alltargets[j];
12846:                 item.style.textAlign='left';
12847:                 item.style.textFace='normal';
12848:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
12849:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
12850:                     item.disabled = '';
12851:                 } else {
12852:                     item.disabled = 'disabled';
12853:                     item.checked = false;
12854:                 }
12855:                 count ++;
12856:             }
12857:         }
12858:     }
12859:     for (var k=0; k<insttypes.length; k++) {
12860:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
12861:             if (ishomedom == 1) {
12862:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
12863:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
12864:             } else {
12865:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
12866:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
12867:             }
12868:         } else {
12869:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
12870:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
12871:         }
12872:         if ((insttypes[k] != '_LC_external') && 
12873:             ((insttypes[k] != '_LC_internetdom') ||
12874:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
12875:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
12876:             item.options.length = 0;
12877:             item.options[0] = new Option("","",true,true);
12878:             var idx = 0;
12879:             for (var m=0; m<alltargets.length; m++) {
12880:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
12881:                     idx ++;
12882:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
12883:                 }
12884:             }
12885:         }
12886:     }
12887:     return;
12888: }
12889: 
12890: function hideSpares(balnum) {
12891:     var alltargets = new Array('$alltargets');
12892:     var insttypes = new Array('$allinsttypes');
12893:     var offloadtypes = new Array('primary','default');
12894: 
12895:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
12896:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
12897: 
12898:     var total = alltargets.length - 1;
12899:     for (var i=0; i<offloadtypes; i++) {
12900:         for (var j=0; j<total; j++) {
12901:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
12902:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
12903:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
12904:         }
12905:     }
12906:     for (var k=0; k<insttypes.length; k++) {
12907:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
12908:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
12909:         if (insttypes[k] != '_LC_external') {
12910:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
12911:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
12912:         }
12913:     }
12914:     return;
12915: }
12916: 
12917: function checkOffloads(item,balnum,type) {
12918:     var alltargets = new Array('$alltargets');
12919:     var offloadtypes = new Array('primary','default');
12920:     if (item.checked) {
12921:         var total = alltargets.length - 1;
12922:         var other;
12923:         if (type == offloadtypes[0]) {
12924:             other = offloadtypes[1];
12925:         } else {
12926:             other = offloadtypes[0];
12927:         }
12928:         for (var i=0; i<total; i++) {
12929:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
12930:             if (server == item.value) {
12931:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
12932:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
12933:                 }
12934:             }
12935:         }
12936:     }
12937:     return;
12938: }
12939: 
12940: function singleServerToggle(balnum,type) {
12941:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
12942:     if (offloadtoSelIdx == 0) {
12943:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
12944:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
12945: 
12946:     } else {
12947:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
12948:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
12949:     }
12950:     return;
12951: }
12952: 
12953: function balanceruleChange(formname,balnum,type) {
12954:     if (type == '_LC_external') {
12955:         return;
12956:     }
12957:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
12958:     for (var i=0; i<typesRules.length; i++) {
12959:         if (formname.elements[typesRules[i]].checked) {
12960:             if (formname.elements[typesRules[i]].value != 'specific') {
12961:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
12962:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
12963:             } else {
12964:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
12965:             }
12966:         }
12967:     }
12968:     return;
12969: }
12970: 
12971: function balancerDeleteChange(balnum) {
12972:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
12973:     var baltotal = document.getElementById('loadbalancing_total').value;
12974:     var addtarget;
12975:     var removetarget;
12976:     var action = 'delete';
12977:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
12978:         var lonhost = hostitem.value;
12979:         var currIdx = currBalancers.indexOf(lonhost);
12980:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
12981:             if (currIdx != -1) {
12982:                 currBalancers.splice(currIdx,1);
12983:             }
12984:             addtarget = lonhost;
12985:         } else {
12986:             if (currIdx == -1) {
12987:                 currBalancers.push(lonhost);
12988:             }
12989:             removetarget = lonhost;
12990:             action = 'undelete';
12991:         }
12992:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
12993:     }
12994:     return;
12995: }
12996: 
12997: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
12998:     if (baltotal > 1) {
12999:         var offloadtypes = new Array('primary','default');
13000:         var alltargets = new Array('$alltargets');
13001:         var insttypes = new Array('$allinsttypes');
13002:         for (var i=0; i<baltotal; i++) {
13003:             if (i != balnum) {
13004:                 for (var j=0; j<offloadtypes.length; j++) {
13005:                     var total = alltargets.length - 1;
13006:                     for (var k=0; k<total; k++) {
13007:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
13008:                         var server = serveritem.value;
13009:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
13010:                             if (server == addtarget) {
13011:                                 serveritem.disabled = '';
13012:                             }
13013:                         }
13014:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
13015:                             if (server == removetarget) {
13016:                                 serveritem.disabled = 'disabled';
13017:                                 serveritem.checked = false;
13018:                             }
13019:                         }
13020:                     }
13021:                 }
13022:                 for (var j=0; j<insttypes.length; j++) {
13023:                     if (insttypes[j] != '_LC_external') {
13024:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
13025:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
13026:                             var currSel = singleserver.selectedIndex;
13027:                             var currVal = singleserver.options[currSel].value;
13028:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
13029:                                 var numoptions = singleserver.options.length;
13030:                                 var needsnew = 1;
13031:                                 for (var k=0; k<numoptions; k++) {
13032:                                     if (singleserver.options[k] == addtarget) {
13033:                                         needsnew = 0;
13034:                                         break;
13035:                                     }
13036:                                 }
13037:                                 if (needsnew == 1) {
13038:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
13039:                                 }
13040:                             }
13041:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
13042:                                 singleserver.options.length = 0;
13043:                                 if ((currVal) && (currVal != removetarget)) {
13044:                                     singleserver.options[0] = new Option("","",false,false);
13045:                                 } else {
13046:                                     singleserver.options[0] = new Option("","",true,true);
13047:                                 }
13048:                                 var idx = 0;
13049:                                 for (var m=0; m<alltargets.length; m++) {
13050:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
13051:                                         idx ++;
13052:                                         if (currVal == alltargets[m]) {
13053:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
13054:                                         } else {
13055:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
13056:                                         }
13057:                                     }
13058:                                 }
13059:                             }
13060:                         }
13061:                     }
13062:                 }
13063:             }
13064:         }
13065:     }
13066:     return;
13067: }
13068: 
13069: // ]]>
13070: </script>
13071: 
13072: END
13073: }
13074: 
13075: sub new_spares_js {
13076:     my @sparestypes = ('primary','default');
13077:     my $types = join("','",@sparestypes);
13078:     my $select = &mt('Select');
13079:     return <<"END";
13080: 
13081: <script type="text/javascript">
13082: // <![CDATA[
13083: 
13084: function updateNewSpares(formname,lonhost) {
13085:     var types = new Array('$types');
13086:     var include = new Array();
13087:     var exclude = new Array();
13088:     for (var i=0; i<types.length; i++) {
13089:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
13090:         for (var j=0; j<spareboxes.length; j++) {
13091:             if (formname.elements[spareboxes[j]].checked) {
13092:                 exclude.push(formname.elements[spareboxes[j]].value);
13093:             } else {
13094:                 include.push(formname.elements[spareboxes[j]].value);
13095:             }
13096:         }
13097:     }
13098:     for (var i=0; i<types.length; i++) {
13099:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
13100:         var selIdx = newSpare.selectedIndex;
13101:         var currnew = newSpare.options[selIdx].value;
13102:         var okSpares = new Array();
13103:         for (var j=0; j<newSpare.options.length; j++) {
13104:             var possible = newSpare.options[j].value;
13105:             if (possible != '') {
13106:                 if (exclude.indexOf(possible) == -1) {
13107:                     okSpares.push(possible);
13108:                 } else {
13109:                     if (currnew == possible) {
13110:                         selIdx = 0;
13111:                     }
13112:                 }
13113:             }
13114:         }
13115:         for (var k=0; k<include.length; k++) {
13116:             if (okSpares.indexOf(include[k]) == -1) {
13117:                 okSpares.push(include[k]);
13118:             }
13119:         }
13120:         okSpares.sort();
13121:         newSpare.options.length = 0;
13122:         if (selIdx == 0) {
13123:             newSpare.options[0] = new Option("$select","",true,true);
13124:         } else {
13125:             newSpare.options[0] = new Option("$select","",false,false);
13126:         }
13127:         for (var m=0; m<okSpares.length; m++) {
13128:             var idx = m+1;
13129:             var selThis = 0;
13130:             if (selIdx != 0) {
13131:                 if (okSpares[m] == currnew) {
13132:                     selThis = 1;
13133:                 }
13134:             }
13135:             if (selThis == 1) {
13136:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
13137:             } else {
13138:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
13139:             }
13140:         }
13141:     }
13142:     return;
13143: }
13144: 
13145: function checkNewSpares(lonhost,type) {
13146:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
13147:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
13148:     if (chosen != '') { 
13149:         var othertype;
13150:         var othernewSpare;
13151:         if (type == 'primary') {
13152:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
13153:         }
13154:         if (type == 'default') {
13155:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
13156:         }
13157:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
13158:             othernewSpare.selectedIndex = 0;
13159:         }
13160:     }
13161:     return;
13162: }
13163: 
13164: // ]]>
13165: </script>
13166: 
13167: END
13168: 
13169: }
13170: 
13171: sub common_domprefs_js {
13172:     return <<"END";
13173: 
13174: <script type="text/javascript">
13175: // <![CDATA[
13176: 
13177: function getIndicesByName(formname,item) {
13178:     var group = new Array();
13179:     for (var i=0;i<formname.elements.length;i++) {
13180:         if (formname.elements[i].name == item) {
13181:             group.push(formname.elements[i].id);
13182:         }
13183:     }
13184:     return group;
13185: }
13186: 
13187: // ]]>
13188: </script>
13189: 
13190: END
13191: 
13192: }
13193: 
13194: sub recaptcha_js {
13195:     my %lt = &captcha_phrases();
13196:     return <<"END";
13197: 
13198: <script type="text/javascript">
13199: // <![CDATA[
13200: 
13201: function updateCaptcha(caller,context) {
13202:     var privitem;
13203:     var pubitem;
13204:     var privtext;
13205:     var pubtext;
13206:     var versionitem;
13207:     var versiontext;
13208:     if (document.getElementById(context+'_recaptchapub')) {
13209:         pubitem = document.getElementById(context+'_recaptchapub');
13210:     } else {
13211:         return;
13212:     }
13213:     if (document.getElementById(context+'_recaptchapriv')) {
13214:         privitem = document.getElementById(context+'_recaptchapriv');
13215:     } else {
13216:         return;
13217:     }
13218:     if (document.getElementById(context+'_recaptchapubtxt')) {
13219:         pubtext = document.getElementById(context+'_recaptchapubtxt');
13220:     } else {
13221:         return;
13222:     }
13223:     if (document.getElementById(context+'_recaptchaprivtxt')) {
13224:         privtext = document.getElementById(context+'_recaptchaprivtxt');
13225:     } else {
13226:         return;
13227:     }
13228:     if (document.getElementById(context+'_recaptchaversion')) {
13229:         versionitem = document.getElementById(context+'_recaptchaversion');
13230:     } else {
13231:         return;
13232:     }
13233:     if (document.getElementById(context+'_recaptchavertxt')) {
13234:         versiontext = document.getElementById(context+'_recaptchavertxt');
13235:     } else {
13236:         return;
13237:     }
13238:     if (caller.checked) {
13239:         if (caller.value == 'recaptcha') {
13240:             pubitem.type = 'text';
13241:             privitem.type = 'text';
13242:             pubitem.size = '40';
13243:             privitem.size = '40';
13244:             pubtext.innerHTML = "$lt{'pub'}";
13245:             privtext.innerHTML = "$lt{'priv'}";
13246:             versionitem.type = 'text';
13247:             versionitem.size = '3';
13248:             versiontext.innerHTML = "$lt{'ver'}"; 
13249:         } else {
13250:             pubitem.type = 'hidden';
13251:             privitem.type = 'hidden';
13252:             versionitem.type = 'hidden';
13253:             pubtext.innerHTML = '';
13254:             privtext.innerHTML = '';
13255:             versiontext.innerHTML = '';
13256:         }
13257:     }
13258:     return;
13259: }
13260: 
13261: // ]]>
13262: </script>
13263: 
13264: END
13265: 
13266: }
13267: 
13268: sub toggle_display_js {
13269:     return <<"END";
13270: 
13271: <script type="text/javascript">
13272: // <![CDATA[
13273: 
13274: function toggleDisplay(domForm,caller) {
13275:     if (document.getElementById(caller)) {
13276:         var divitem = document.getElementById(caller);
13277:         var optionsElement = domForm.coursecredits;
13278:         var checkval = 1;
13279:         var dispval = 'block';
13280:         if (caller == 'emailoptions') {
13281:             optionsElement = domForm.cancreate_email; 
13282:         }
13283:         if (caller == 'studentsubmission') {
13284:             optionsElement = domForm.postsubmit;
13285:         }
13286:         if (caller == 'cloneinstcode') {
13287:             optionsElement = domForm.canclone;
13288:             checkval = 'instcode';
13289:         }
13290:         if (optionsElement.length) {
13291:             var currval;
13292:             for (var i=0; i<optionsElement.length; i++) {
13293:                 if (optionsElement[i].checked) {
13294:                    currval = optionsElement[i].value;
13295:                 }
13296:             }
13297:             if (currval == checkval) {
13298:                 divitem.style.display = dispval;
13299:             } else {
13300:                 divitem.style.display = 'none';
13301:             }
13302:         }
13303:     }
13304:     return;
13305: }
13306: 
13307: // ]]>
13308: </script>
13309: 
13310: END
13311: 
13312: }
13313: 
13314: sub captcha_phrases {
13315:     return &Apache::lonlocal::texthash (
13316:                  priv => 'Private key',
13317:                  pub  => 'Public key',
13318:                  original  => 'original (CAPTCHA)',
13319:                  recaptcha => 'successor (ReCAPTCHA)',
13320:                  notused   => 'unused',
13321:                  ver => 'ReCAPTCHA version (1 or 2)', 
13322:     );
13323: }
13324: 
13325: sub devalidate_remote_domconfs {
13326:     my ($dom,$cachekeys) = @_;
13327:     return unless (ref($cachekeys) eq 'HASH');
13328:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
13329:     my %thismachine;
13330:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
13331:     my @posscached = ('domainconfig','domdefaults','ltitools');
13332:     if (keys(%servers)) {
13333:         foreach my $server (keys(%servers)) {
13334:             next if ($thismachine{$server});
13335:             my @cached;
13336:             foreach my $name (@posscached) {
13337:                 if ($cachekeys->{$name}) {
13338:                     push(@cached,&escape($name).':'.&escape($dom));
13339:                 }
13340:             }
13341:             if (@cached) {
13342:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
13343:             }
13344:         }
13345:     }
13346:     return;
13347: }
13348: 
13349: 1;

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