File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.160.6.78: download - view: text, annotated - select for diffs
Tue Jan 24 00:19:15 2017 UTC (7 years, 4 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.160: preferred, unified
- For 2.11
  - Backport  1.286, 1.288, 1.289

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.160.6.78 2017/01/24 00:19:15 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: #
   29: ###############################################################
   30: ##############################################################
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::domainprefs.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40: Handles configuration of a LON-CAPA domain.  
   41: 
   42: This is part of the LearningOnline Network with CAPA project
   43: described at http://www.lon-capa.org.
   44: 
   45: 
   46: =head1 OVERVIEW
   47: 
   48: Each institution using LON-CAPA will typically have a single domain designated 
   49: for use by individuals affiliated with the institution.  Accordingly, each domain
   50: may define a default set of logos and a color scheme which can be used to "brand"
   51: the LON-CAPA instance. In addition, an institution will typically have a language
   52: and timezone which are used for the majority of courses.
   53: 
   54: LON-CAPA provides a mechanism to display and modify these defaults, as well as a 
   55: host of other domain-wide settings which determine the types of functionality
   56: available to users and courses in the domain.
   57: 
   58: There is also a mechanism to configure cataloging of courses in the domain, and
   59: controls on the operation of automated processes which govern such things as
   60: roster updates, user directory updates and processing of course requests.
   61: 
   62: The domain coordination manual which is built dynamically on install/update of 
   63: LON-CAPA from the relevant help items provides more information about domain 
   64: configuration.
   65: 
   66: Most of the domain settings are stored in the configuration.db GDBM file which is
   67: housed on the primary library server for the domain in /home/httpd/lonUsers/$dom,
   68: where $dom is the domain.  The configuration.db stores settings in a number of 
   69: frozen hashes of hashes.  In a few cases, domain information must be uploaded to
   70: the domain as files (e.g., image files for logos etc., or plain text files for
   71: bubblesheet formats).  In this case the domainprefs.pm must be running in a user
   72: session hosted on the primary library server in the domain, as these files are 
   73: stored in author space belonging to a special $dom-domainconfig user.   
   74: 
   75: domainprefs.pm in combination with lonconfigsettings.pm will retrieve and display
   76: the current settings, and provides an interface to make modifications.
   77: 
   78: =head1 SUBROUTINES
   79: 
   80: =over
   81: 
   82: =item print_quotas()
   83: 
   84: Inputs: 4 
   85: 
   86: $dom,$settings,$rowtotal,$action.
   87: 
   88: $dom is the domain, $settings is a reference to a hash of current settings for
   89: the current context, $rowtotal is a reference to the scalar used to record the 
   90: number of rows displayed on the page, and $action is the context (quotas, 
   91: requestcourses or requestauthor).
   92: 
   93: The print_quotas routine was orginally created to display/store information
   94: about default quota sizes for portfolio spaces for the different types of 
   95: institutional affiliation in the domain (e.g., Faculty, Staff, Student etc.), 
   96: but is now also used to manage availability of user tools: 
   97: i.e., blogs, aboutme page, and portfolios, and the course request tool,
   98: used by course owners to request creation of a course, and to display/store
   99: default quota sizes for Authoring Spaces.
  100: 
  101: Outputs: 1
  102: 
  103: $datatable  - HTML containing form elements which allow settings to be changed. 
  104: 
  105: In the case of course requests, radio buttons are displayed for each institutional
  106: affiliate type (and also default, and _LC_adv) for each of the course types 
  107: (official, unofficial, community, and textbook).  In each case the radio buttons 
  108: allow the selection of one of four values:
  109: 
  110: 0, approval, validate, autolimit=N (where N is blank, or a positive integer).
  111: which have the following effects:
  112: 
  113: 0
  114: 
  115: =over
  116: 
  117: - course requests are not allowed for this course types/affiliation
  118: 
  119: =back
  120: 
  121: approval 
  122: 
  123: =over 
  124: 
  125: - course requests must be approved by a Doman Coordinator in the 
  126: course's domain
  127: 
  128: =back
  129: 
  130: validate 
  131: 
  132: =over
  133: 
  134: - an institutional validation (e.g., check requestor is instructor
  135: of record) needs to be passed before the course will be created.  The required
  136: validation is in localenroll.pm on the primary library server for the course 
  137: domain.
  138: 
  139: =back
  140: 
  141: autolimit 
  142: 
  143: =over
  144:  
  145: - course requests will be processed automatically up to a limit of
  146: N requests for the course type for the particular requestor.
  147: If N is undefined, there is no limit to the number of course requests
  148: which a course owner may submit and have processed automatically. 
  149: 
  150: =back
  151: 
  152: =item modify_quotas() 
  153: 
  154: =back
  155: 
  156: =cut
  157: 
  158: package Apache::domainprefs;
  159: 
  160: use strict;
  161: use Apache::Constants qw(:common :http);
  162: use Apache::lonnet;
  163: use Apache::loncommon();
  164: use Apache::lonhtmlcommon();
  165: use Apache::lonlocal;
  166: use Apache::lonmsg();
  167: use Apache::lonconfigsettings;
  168: use Apache::lonuserutils();
  169: use Apache::loncoursequeueadmin();
  170: use LONCAPA qw(:DEFAULT :match);
  171: use LONCAPA::Enrollment;
  172: use LONCAPA::lonauthcgi();
  173: use File::Copy;
  174: use Locale::Language;
  175: use DateTime::TimeZone;
  176: use DateTime::Locale;
  177: 
  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'],$dom);
  220:     my @prefs_order = ('rolecolors','login','defaults','quotas','autoenroll',
  221:                        'autoupdate','autocreate','directorysrch','contacts',
  222:                        'usercreation','selfcreation','usermodification','scantron',
  223:                        'requestcourses','requestauthor','coursecategories',
  224:                        'serverstatuses','helpsettings','coursedefaults',
  225:                        'selfenrollment','usersessions');
  226:     my %existing;
  227:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  228:         %existing = %{$domconfig{'loadbalancing'}};
  229:     }
  230:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  231:         push(@prefs_order,'loadbalancing');
  232:     }
  233:     my %prefs = (
  234:         'rolecolors' =>
  235:                    { text => 'Default color schemes',
  236:                      help => 'Domain_Configuration_Color_Schemes',
  237:                      header => [{col1 => 'Student Settings',
  238:                                  col2 => '',},
  239:                                 {col1 => 'Coordinator Settings',
  240:                                  col2 => '',},
  241:                                 {col1 => 'Author Settings',
  242:                                  col2 => '',},
  243:                                 {col1 => 'Administrator Settings',
  244:                                  col2 => '',}],
  245:                       print => \&print_rolecolors,
  246:                       modify => \&modify_rolecolors,
  247:                     },
  248:         'login' =>
  249:                     { text => 'Log-in page options',
  250:                       help => 'Domain_Configuration_Login_Page',
  251:                       header => [{col1 => 'Log-in Page Items',
  252:                                   col2 => '',},
  253:                                  {col1 => 'Log-in Help',
  254:                                   col2 => 'Value'},
  255:                                  {col1 => 'Custom HTML in document head',
  256:                                   col2 => 'Value'}],
  257:                       print => \&print_login,
  258:                       modify => \&modify_login,
  259:                     },
  260:         'defaults' => 
  261:                     { text => 'Default authentication/language/timezone/portal/types',
  262:                       help => 'Domain_Configuration_LangTZAuth',
  263:                       header => [{col1 => 'Setting',
  264:                                   col2 => 'Value'},
  265:                                  {col1 => 'Institutional user types',
  266:                                   col2 => 'Assignable to e-mail usernames'}],
  267:                       print => \&print_defaults,
  268:                       modify => \&modify_defaults,
  269:                     },
  270:         'quotas' => 
  271:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  272:                       help => 'Domain_Configuration_Quotas',
  273:                       header => [{col1 => 'User affiliation',
  274:                                   col2 => 'Available tools',
  275:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  276:                       print => \&print_quotas,
  277:                       modify => \&modify_quotas,
  278:                     },
  279:         'autoenroll' =>
  280:                    { text => 'Auto-enrollment settings',
  281:                      help => 'Domain_Configuration_Auto_Enrollment',
  282:                      header => [{col1 => 'Configuration setting',
  283:                                  col2 => 'Value(s)'}],
  284:                      print => \&print_autoenroll,
  285:                      modify => \&modify_autoenroll,
  286:                    },
  287:         'autoupdate' => 
  288:                    { text => 'Auto-update settings',
  289:                      help => 'Domain_Configuration_Auto_Updates',
  290:                      header => [{col1 => 'Setting',
  291:                                  col2 => 'Value',},
  292:                                 {col1 => 'Setting',
  293:                                  col2 => 'Affiliation'},
  294:                                 {col1 => 'User population',
  295:                                  col2 => 'Updatable user data'}],
  296:                      print => \&print_autoupdate,
  297:                      modify => \&modify_autoupdate,
  298:                   },
  299:         'autocreate' => 
  300:                   { text => 'Auto-course creation settings',
  301:                      help => 'Domain_Configuration_Auto_Creation',
  302:                      header => [{col1 => 'Configuration Setting',
  303:                                  col2 => 'Value',}],
  304:                      print => \&print_autocreate,
  305:                      modify => \&modify_autocreate,
  306:                   },
  307:         'directorysrch' => 
  308:                   { text => 'Directory searches',
  309:                     help => 'Domain_Configuration_InstDirectory_Search',
  310:                     header => [{col1 => 'Institutional Directory Setting',
  311:                                 col2 => 'Value',},
  312:                                {col1 => 'LON-CAPA Directory Setting',
  313:                                 col2 => 'Value',}],
  314:                     print => \&print_directorysrch,
  315:                     modify => \&modify_directorysrch,
  316:                   },
  317:         'contacts' =>
  318:                   { text => 'E-mail addresses and helpform',
  319:                     help => 'Domain_Configuration_Contact_Info',
  320:                     header => [{col1 => 'Default e-mail addresses',
  321:                                 col2 => 'Value',},
  322:                                {col1 => 'Recipient(s) for notifications',
  323:                                 col2 => 'Value',},
  324:                                {col1 => 'Ask helpdesk form settings',
  325:                                 col2 => 'Value',},],
  326:                     print => \&print_contacts,
  327:                     modify => \&modify_contacts,
  328:                   },
  329:         'usercreation' => 
  330:                   { text => 'User creation',
  331:                     help => 'Domain_Configuration_User_Creation',
  332:                     header => [{col1 => 'Format rule type',
  333:                                 col2 => 'Format rules in force'},
  334:                                {col1 => 'User account creation',
  335:                                 col2 => 'Usernames which may be created',},
  336:                                {col1 => 'Context',
  337:                                 col2 => 'Assignable authentication types'}],
  338:                     print => \&print_usercreation,
  339:                     modify => \&modify_usercreation,
  340:                   },
  341:         'selfcreation' => 
  342:                   { text => 'Users self-creating accounts',
  343:                     help => 'Domain_Configuration_Self_Creation', 
  344:                     header => [{col1 => 'Self-creation with institutional username',
  345:                                 col2 => 'Enabled?'},
  346:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  347:                                 col2 => 'Information user can enter'},
  348:                                {col1 => 'Self-creation with e-mail as username',
  349:                                 col2 => 'Settings'}],
  350:                     print => \&print_selfcreation,
  351:                     modify => \&modify_selfcreation,
  352:                   },
  353:         'usermodification' =>
  354:                   { text => 'User modification',
  355:                     help => 'Domain_Configuration_User_Modification',
  356:                     header => [{col1 => 'Target user has role',
  357:                                 col2 => 'User information updatable in author context'},
  358:                                {col1 => 'Target user has role',
  359:                                 col2 => 'User information updatable in course context'}],
  360:                     print => \&print_usermodification,
  361:                     modify => \&modify_usermodification,
  362:                   },
  363:         'scantron' =>
  364:                   { text => 'Bubblesheet format file',
  365:                     help => 'Domain_Configuration_Scantron_Format',
  366:                     header => [ {col1 => 'Item',
  367:                                  col2 => '',
  368:                               }],
  369:                     print => \&print_scantron,
  370:                     modify => \&modify_scantron,
  371:                   },
  372:         'requestcourses' => 
  373:                  {text => 'Request creation of courses',
  374:                   help => 'Domain_Configuration_Request_Courses',
  375:                   header => [{col1 => 'User affiliation',
  376:                               col2 => 'Availability/Processing of requests',},
  377:                              {col1 => 'Setting',
  378:                               col2 => 'Value'},
  379:                              {col1 => 'Available textbooks',
  380:                               col2 => ''},
  381:                              {col1 => 'Available templates',
  382:                               col2 => ''},
  383:                              {col1 => 'Validation (not official courses)',
  384:                               col2 => 'Value'},],
  385:                   print => \&print_quotas,
  386:                   modify => \&modify_quotas,
  387:                  },
  388:         'requestauthor' =>
  389:                  {text => 'Request Authoring Space',
  390:                   help => 'Domain_Configuration_Request_Author',
  391:                   header => [{col1 => 'User affiliation',
  392:                               col2 => 'Availability/Processing of requests',},
  393:                              {col1 => 'Setting',
  394:                               col2 => 'Value'}],
  395:                   print => \&print_quotas,
  396:                   modify => \&modify_quotas,
  397:                  },
  398:         'coursecategories' =>
  399:                   { text => 'Cataloging of courses/communities',
  400:                     help => 'Domain_Configuration_Cataloging_Courses',
  401:                     header => [{col1 => 'Catalog type/availability',
  402:                                 col2 => '',},
  403:                                {col1 => 'Category settings for standard catalog',
  404:                                 col2 => '',},
  405:                                {col1 => 'Categories',
  406:                                 col2 => '',
  407:                                }],
  408:                     print => \&print_coursecategories,
  409:                     modify => \&modify_coursecategories,
  410:                   },
  411:         'serverstatuses' =>
  412:                  {text   => 'Access to server status pages',
  413:                   help   => 'Domain_Configuration_Server_Status',
  414:                   header => [{col1 => 'Status Page',
  415:                               col2 => 'Other named users',
  416:                               col3 => 'Specific IPs',
  417:                             }],
  418:                   print => \&print_serverstatuses,
  419:                   modify => \&modify_serverstatuses,
  420:                  },
  421:         'helpsettings' =>
  422:                  {text   => 'Support settings',
  423:                   help   => 'Domain_Configuration_Help_Settings',
  424:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  425:                               col2 => 'Value'},
  426:                              {col1 => 'Helpdesk Roles',
  427:                               col2 => 'Settings'},],
  428:                   print  => \&print_helpsettings,
  429:                   modify => \&modify_helpsettings,
  430:                  },
  431:         'coursedefaults' => 
  432:                  {text => 'Course/Community defaults',
  433:                   help => 'Domain_Configuration_Course_Defaults',
  434:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  435:                               col2 => 'Value',},
  436:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  437:                               col2 => 'Value',},],
  438:                   print => \&print_coursedefaults,
  439:                   modify => \&modify_coursedefaults,
  440:                  },
  441:         'selfenrollment' => 
  442:                  {text   => 'Self-enrollment in Course/Community',
  443:                   help   => 'Domain_Configuration_Selfenrollment',
  444:                   header => [{col1 => 'Configuration Rights',
  445:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  446:                              {col1 => 'Defaults',
  447:                               col2 => 'Value'},
  448:                              {col1 => 'Self-enrollment validation (optional)',
  449:                               col2 => 'Value'},],
  450:                   print => \&print_selfenrollment,
  451:                   modify => \&modify_selfenrollment,
  452:                  },
  453:         'usersessions' =>
  454:                  {text  => 'User session hosting/offloading',
  455:                   help  => 'Domain_Configuration_User_Sessions',
  456:                   header => [{col1 => 'Domain server',
  457:                               col2 => 'Servers to offload sessions to when busy'},
  458:                              {col1 => 'Hosting of users from other domains',
  459:                               col2 => 'Rules'},
  460:                              {col1 => "Hosting domain's own users elsewhere",
  461:                               col2 => 'Rules'}],
  462:                   print => \&print_usersessions,
  463:                   modify => \&modify_usersessions,
  464:                  },
  465:         'loadbalancing' =>
  466:                  {text  => 'Dedicated Load Balancer(s)',
  467:                   help  => 'Domain_Configuration_Load_Balancing',
  468:                   header => [{col1 => 'Balancers',
  469:                               col2 => 'Default destinations',
  470:                               col3 => 'User affiliation',
  471:                               col4 => 'Overrides'},
  472:                             ],
  473:                   print => \&print_loadbalancing,
  474:                   modify => \&modify_loadbalancing,
  475:                  },
  476:     );
  477:     if (keys(%servers) > 1) {
  478:         $prefs{'login'}  = { text   => 'Log-in page options',
  479:                              help   => 'Domain_Configuration_Login_Page',
  480:                             header => [{col1 => 'Log-in Service',
  481:                                         col2 => 'Server Setting',},
  482:                                        {col1 => 'Log-in Page Items',
  483:                                         col2 => ''},
  484:                                        {col1 => 'Log-in Help',
  485:                                         col2 => 'Value'},
  486:                                        {col1 => 'Custom HTML in document head',
  487:                                         col2 => 'Value'}],
  488:                             print => \&print_login,
  489:                             modify => \&modify_login,
  490:                            };
  491:     }
  492: 
  493:     my @roles = ('student','coordinator','author','admin');
  494:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  495:     &Apache::lonhtmlcommon::add_breadcrumb
  496:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  497:       text=>"Settings to display/modify"});
  498:     my $confname = $dom.'-domainconfig';
  499: 
  500:     if ($phase eq 'process') {
  501:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  502:                                                               \%prefs,\%domconfig,$confname,\@roles);
  503:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  504:             $r->rflush();
  505:             &devalidate_remote_domconfs($dom,$result);
  506:         }
  507:     } elsif ($phase eq 'display') {
  508:         my $js = &recaptcha_js().
  509:                  &toggle_display_js();
  510:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  511:             my ($othertitle,$usertypes,$types) =
  512:                 &Apache::loncommon::sorted_inst_types($dom);
  513:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  514:                                           $domconfig{'loadbalancing'}).
  515:                    &new_spares_js().
  516:                    &common_domprefs_js().
  517:                    &Apache::loncommon::javascript_array_indexof();
  518:         }
  519:         if (grep(/^requestcourses$/,@actions)) {
  520:             my $javascript_validations;
  521:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  522:             $js .= <<END;
  523: <script type="text/javascript">
  524: $javascript_validations
  525: </script>
  526: $coursebrowserjs
  527: END
  528:         }
  529:         if (grep(/^contacts$/,@actions)) {
  530:             $js .= &contacts_javascript();
  531:         }
  532:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  533:     } else {
  534: # check if domconfig user exists for the domain.
  535:         my $servadm = $r->dir_config('lonAdmEMail');
  536:         my ($configuserok,$author_ok,$switchserver) =
  537:             &config_check($dom,$confname,$servadm);
  538:         unless ($configuserok eq 'ok') {
  539:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  540:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  541:                           $confname).
  542:                       '<br />'
  543:             );
  544:             if ($switchserver) {
  545:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  546:                           '<br />'.
  547:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  548:                           '<br />'.
  549:                           &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).
  550:                           '<br />'.
  551:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  552:                 );
  553:             } else {
  554:                 $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.').
  555:                           '<br />'.
  556:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  557:                 );
  558:             }
  559:             $r->print(&Apache::loncommon::end_page());
  560:             return OK;
  561:         }
  562:         if (keys(%domconfig) == 0) {
  563:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  564:             my @ids=&Apache::lonnet::current_machine_ids();
  565:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  566:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  567:                 my @loginimages = ('img','logo','domlogo','login');
  568:                 my $custom_img_count = 0;
  569:                 foreach my $img (@loginimages) {
  570:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  571:                         $custom_img_count ++;
  572:                     }
  573:                 }
  574:                 foreach my $role (@roles) {
  575:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  576:                         $custom_img_count ++;
  577:                     }
  578:                 }
  579:                 if ($custom_img_count > 0) {
  580:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  581:                     my $switch_server = &check_switchserver($dom,$confname);
  582:                     $r->print(
  583:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  584:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  585:     &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 />'.
  586:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  587:                     if ($switch_server) {
  588:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  589:                     }
  590:                     $r->print(&Apache::loncommon::end_page());
  591:                     return OK;
  592:                 }
  593:             }
  594:         }
  595:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  596:     }
  597:     return OK;
  598: }
  599: 
  600: sub process_changes {
  601:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  602:     my %domconfig;
  603:     if (ref($values) eq 'HASH') {
  604:         %domconfig = %{$values};
  605:     }
  606:     my $output;
  607:     if ($action eq 'login') {
  608:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  609:     } elsif ($action eq 'rolecolors') {
  610:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  611:                                      $lastactref,%domconfig);
  612:     } elsif ($action eq 'quotas') {
  613:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  614:     } elsif ($action eq 'autoenroll') {
  615:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  616:     } elsif ($action eq 'autoupdate') {
  617:         $output = &modify_autoupdate($dom,%domconfig);
  618:     } elsif ($action eq 'autocreate') {
  619:         $output = &modify_autocreate($dom,%domconfig);
  620:     } elsif ($action eq 'directorysrch') {
  621:         $output = &modify_directorysrch($dom,%domconfig);
  622:     } elsif ($action eq 'usercreation') {
  623:         $output = &modify_usercreation($dom,%domconfig);
  624:     } elsif ($action eq 'selfcreation') {
  625:         $output = &modify_selfcreation($dom,%domconfig);
  626:     } elsif ($action eq 'usermodification') {
  627:         $output = &modify_usermodification($dom,%domconfig);
  628:     } elsif ($action eq 'contacts') {
  629:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  630:     } elsif ($action eq 'defaults') {
  631:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  632:     } elsif ($action eq 'scantron') {
  633:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  634:     } elsif ($action eq 'coursecategories') {
  635:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  636:     } elsif ($action eq 'serverstatuses') {
  637:         $output = &modify_serverstatuses($dom,%domconfig);
  638:     } elsif ($action eq 'requestcourses') {
  639:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  640:     } elsif ($action eq 'requestauthor') {
  641:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  642:     } elsif ($action eq 'helpsettings') {
  643:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  644:     } elsif ($action eq 'coursedefaults') {
  645:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  646:     } elsif ($action eq 'selfenrollment') {
  647:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  648:     } elsif ($action eq 'usersessions') {
  649:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  650:     } elsif ($action eq 'loadbalancing') {
  651:         $output = &modify_loadbalancing($dom,%domconfig);
  652:     }
  653:     return $output;
  654: }
  655: 
  656: sub print_config_box {
  657:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  658:     my $rowtotal = 0;
  659:     my $output;
  660:     if ($action eq 'coursecategories') {
  661:         $output = &coursecategories_javascript($settings);
  662:     } elsif ($action eq 'defaults') {
  663:         $output = &defaults_javascript($settings); 
  664:     } elsif ($action eq 'helpsettings') {
  665:         my (%privs,%levelscurrent);
  666:         my %full=();
  667:         my %levels=(
  668:                      course => {},
  669:                      domain => {},
  670:                      system => {},
  671:                    );
  672:         my $context = 'domain';
  673:         my $crstype = 'Course';
  674:         my $formname = 'display';
  675:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  676:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  677:         $output =
  678:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full,
  679:                                                       \@templateroles);
  680:     }
  681:     $output .=
  682:          '<table class="LC_nested_outer">
  683:           <tr>
  684:            <th align="left" valign="middle"><span class="LC_nobreak">'.
  685:            &mt($item->{text}).'&nbsp;'.
  686:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  687:           '</tr>';
  688:     $rowtotal ++;
  689:     my $numheaders = 1;
  690:     if (ref($item->{'header'}) eq 'ARRAY') {
  691:         $numheaders = scalar(@{$item->{'header'}});
  692:     }
  693:     if ($numheaders > 1) {
  694:         my $colspan = '';
  695:         my $rightcolspan = '';
  696:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  697:             ($action eq 'directorysrch') ||
  698:             (($action eq 'login') && ($numheaders < 4))) {
  699:             $colspan = ' colspan="2"';
  700:         }
  701:         if ($action eq 'usersessions') {
  702:             $rightcolspan = ' colspan="3"'; 
  703:         }
  704:         $output .= '
  705:           <tr>
  706:            <td>
  707:             <table class="LC_nested">
  708:              <tr class="LC_info_row">
  709:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  710:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  711:              </tr>';
  712:         $rowtotal ++;
  713:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  714:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  715:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'directorysrch') ||
  716:             ($action eq 'helpsettings') || ($action eq 'contacts')) {
  717:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  718:         } elsif ($action eq 'coursecategories') {
  719:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  720:         } elsif ($action eq 'login') {
  721:             if ($numheaders == 4) {
  722:                 $colspan = ' colspan="2"';
  723:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  724:             } else {
  725:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  726:             }
  727:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  728:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  729:         } elsif ($action eq 'rolecolors') {
  730:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  731:         }
  732:         $output .= '
  733:            </table>
  734:           </td>
  735:          </tr>
  736:          <tr>
  737:            <td>
  738:             <table class="LC_nested">
  739:              <tr class="LC_info_row">
  740:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  741:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  742:              </tr>';
  743:             $rowtotal ++;
  744:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  745:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  746:             ($action eq 'usersessions') || ($action eq 'coursecategories') ||
  747:             ($action eq 'contacts')) {
  748:             if ($action eq 'coursecategories') {
  749:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  750:                 $colspan = ' colspan="2"';
  751:             } else {
  752:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  753:             }
  754:             $output .= '
  755:            </table>
  756:           </td>
  757:          </tr>
  758:          <tr>
  759:            <td>
  760:             <table class="LC_nested">
  761:              <tr class="LC_info_row">
  762:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  763:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  764:              </tr>'."\n";
  765:             if ($action eq 'coursecategories') {
  766:                 $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
  767:             } else {
  768:                 $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  769:             }
  770:             $rowtotal ++;
  771:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
  772:                  ($action eq 'defaults') || ($action eq 'directorysrch') ||
  773:                  ($action eq 'helpsettings')) {
  774:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  775:         } elsif ($action eq 'login') {
  776:             if ($numheaders == 4) {
  777:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
  778:            </table>
  779:           </td>
  780:          </tr>
  781:          <tr>
  782:            <td>
  783:             <table class="LC_nested">
  784:              <tr class="LC_info_row">
  785:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  786:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
  787:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  788:                 $rowtotal ++;
  789:             } else {
  790:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  791:             }
  792:             $output .= '
  793:            </table>
  794:           </td>
  795:          </tr>
  796:          <tr>
  797:            <td>
  798:             <table class="LC_nested">
  799:              <tr class="LC_info_row">';
  800:             if ($numheaders == 4) {
  801:                 $output .= '
  802:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  803:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  804:              </tr>';
  805:             } else {
  806:                 $output .= '
  807:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  808:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  809:              </tr>';
  810:             }
  811:             $rowtotal ++;
  812:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal);
  813:         } elsif ($action eq 'requestcourses') {
  814:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
  815:             $rowtotal ++;
  816:             $output .= &print_studentcode($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'}->[2]->{'col1'}).'</td>
  825:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
  826:                        &textbookcourses_javascript($settings).
  827:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
  828:             </table>
  829:            </td>
  830:           </tr>
  831:          <tr>
  832:            <td>
  833:             <table class="LC_nested">
  834:              <tr class="LC_info_row">
  835:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  836:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
  837:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
  838:             </table>
  839:            </td>
  840:           </tr>
  841:           <tr>
  842:            <td>
  843:             <table class="LC_nested">
  844:              <tr class="LC_info_row">
  845:               <td class="LC_left_item"'.$colspan.' valign="top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
  846:               <td class="LC_right_item" valign="top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
  847:              </tr>'.
  848:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
  849:         } elsif ($action eq 'requestauthor') {
  850:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
  851:             $rowtotal ++;
  852:         } elsif ($action eq 'rolecolors') {
  853:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
  854:            </table>
  855:           </td>
  856:          </tr>
  857:          <tr>
  858:            <td>
  859:             <table class="LC_nested">
  860:              <tr class="LC_info_row">
  861:               <td class="LC_left_item"'.$colspan.' valign="top">'.
  862:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
  863:               <td class="LC_right_item" valign="top">'.
  864:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
  865:              </tr>'.
  866:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
  867:            </table>
  868:           </td>
  869:          </tr>
  870:          <tr>
  871:            <td>
  872:             <table class="LC_nested">
  873:              <tr class="LC_info_row">
  874:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  875:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  876:              </tr>'.
  877:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
  878:             $rowtotal += 2;
  879:         }
  880:     } else {
  881:         $output .= '
  882:           <tr>
  883:            <td>
  884:             <table class="LC_nested">
  885:              <tr class="LC_info_row">';
  886:         if ($action eq 'login') {
  887:             $output .= '  
  888:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
  889:         } elsif ($action eq 'serverstatuses') {
  890:             $output .= '
  891:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).
  892:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
  893: 
  894:         } else {
  895:             $output .= '
  896:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
  897:         }
  898:         if (defined($item->{'header'}->[0]->{'col3'})) {
  899:             $output .= '<td class="LC_left_item" valign="top">'.
  900:                        &mt($item->{'header'}->[0]->{'col2'});
  901:             if ($action eq 'serverstatuses') {
  902:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
  903:             } 
  904:         } else {
  905:             $output .= '<td class="LC_right_item" valign="top">'.
  906:                        &mt($item->{'header'}->[0]->{'col2'});
  907:         }
  908:         $output .= '</td>';
  909:         if ($item->{'header'}->[0]->{'col3'}) {
  910:             if (defined($item->{'header'}->[0]->{'col4'})) {
  911:                 $output .= '<td class="LC_left_item" valign="top">'.
  912:                             &mt($item->{'header'}->[0]->{'col3'});
  913:             } else {
  914:                 $output .= '<td class="LC_right_item" valign="top">'.
  915:                            &mt($item->{'header'}->[0]->{'col3'});
  916:             }
  917:             if ($action eq 'serverstatuses') {
  918:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
  919:             }
  920:             $output .= '</td>';
  921:         }
  922:         if ($item->{'header'}->[0]->{'col4'}) {
  923:             $output .= '<td class="LC_right_item" valign="top">'.
  924:                        &mt($item->{'header'}->[0]->{'col4'});
  925:         }
  926:         $output .= '</tr>';
  927:         $rowtotal ++;
  928:         if ($action eq 'quotas') {
  929:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  930:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
  931:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing')) {
  932:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
  933:         } elsif ($action eq 'scantron') {
  934:             $output .= &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
  935:         }
  936:     }
  937:     $output .= '
  938:    </table>
  939:   </td>
  940:  </tr>
  941: </table><br />';
  942:     return ($output,$rowtotal);
  943: }
  944: 
  945: sub print_login {
  946:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
  947:     my ($css_class,$datatable);
  948:     my %choices = &login_choices();
  949: 
  950:     if ($caller eq 'service') {
  951:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
  952:         my $choice = $choices{'disallowlogin'};
  953:         $css_class = ' class="LC_odd_row"';
  954:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
  955:                       '<td align="right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
  956:                       '<th>'.$choices{'server'}.'</th>'.
  957:                       '<th>'.$choices{'serverpath'}.'</th>'.
  958:                       '<th>'.$choices{'custompath'}.'</th>'.
  959:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
  960:         my %disallowed;
  961:         if (ref($settings) eq 'HASH') {
  962:             if (ref($settings->{'loginvia'}) eq 'HASH') {
  963:                %disallowed = %{$settings->{'loginvia'}};
  964:             }
  965:         }
  966:         foreach my $lonhost (sort(keys(%servers))) {
  967:             my $direct = 'selected="selected"';
  968:             if (ref($disallowed{$lonhost}) eq 'HASH') {
  969:                 if ($disallowed{$lonhost}{'server'} ne '') {
  970:                     $direct = '';
  971:                 }
  972:             }
  973:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
  974:                           '<td><select name="'.$lonhost.'_server">'.
  975:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
  976:                           '</option>';
  977:             foreach my $hostid (sort(keys(%servers))) {
  978:                 next if ($servers{$hostid} eq $servers{$lonhost});
  979:                 my $selected = '';
  980:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
  981:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
  982:                         $selected = 'selected="selected"';
  983:                     }
  984:                 }
  985:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
  986:                               $servers{$hostid}.'</option>';
  987:             }
  988:             $datatable .= '</select></td>'.
  989:                           '<td><select name="'.$lonhost.'_serverpath">';
  990:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
  991:                 my $pathname = $path;
  992:                 if ($path eq 'custom') {
  993:                     $pathname = &mt('Custom Path').' ->';
  994:                 }
  995:                 my $selected = '';
  996:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
  997:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
  998:                         $selected = 'selected="selected"';
  999:                     }
 1000:                 } elsif ($path eq '') {
 1001:                     $selected = 'selected="selected"';
 1002:                 }
 1003:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1004:             }
 1005:             $datatable .= '</select></td>';
 1006:             my ($custom,$exempt);
 1007:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1008:                 $custom = $disallowed{$lonhost}{'custompath'};
 1009:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1010:             }
 1011:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1012:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1013:                           '</tr>';
 1014:         }
 1015:         $datatable .= '</table></td></tr>';
 1016:         return $datatable;
 1017:     } elsif ($caller eq 'page') {
 1018:         my %defaultchecked = ( 
 1019:                                'coursecatalog' => 'on',
 1020:                                'helpdesk'      => 'on',
 1021:                                'adminmail'     => 'off',
 1022:                                'newuser'       => 'off',
 1023:                              );
 1024:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1025:         my (%checkedon,%checkedoff);
 1026:         foreach my $item (@toggles) {
 1027:             if ($defaultchecked{$item} eq 'on') { 
 1028:                 $checkedon{$item} = ' checked="checked" ';
 1029:                 $checkedoff{$item} = ' ';
 1030:             } elsif ($defaultchecked{$item} eq 'off') {
 1031:                 $checkedoff{$item} = ' checked="checked" ';
 1032:                 $checkedon{$item} = ' ';
 1033:             }
 1034:         }
 1035:         my @images = ('img','logo','domlogo','login');
 1036:         my @logintext = ('textcol','bgcol');
 1037:         my @bgs = ('pgbg','mainbg','sidebg');
 1038:         my @links = ('link','alink','vlink');
 1039:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1040:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1041:         my (%is_custom,%designs);
 1042:         my %defaults = (
 1043:                        font => $defaultdesign{'login.font'},
 1044:                        );
 1045:         foreach my $item (@images) {
 1046:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1047:             $defaults{'showlogo'}{$item} = 1;
 1048:         }
 1049:         foreach my $item (@bgs) {
 1050:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1051:         }
 1052:         foreach my $item (@logintext) {
 1053:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1054:         }
 1055:         foreach my $item (@links) {
 1056:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1057:         }
 1058:         if (ref($settings) eq 'HASH') {
 1059:             foreach my $item (@toggles) {
 1060:                 if ($settings->{$item} eq '1') {
 1061:                     $checkedon{$item} =  ' checked="checked" ';
 1062:                     $checkedoff{$item} = ' ';
 1063:                 } elsif ($settings->{$item} eq '0') {
 1064:                     $checkedoff{$item} =  ' checked="checked" ';
 1065:                     $checkedon{$item} = ' ';
 1066:                 }
 1067:             }
 1068:             foreach my $item (@images) {
 1069:                 if (defined($settings->{$item})) {
 1070:                     $designs{$item} = $settings->{$item};
 1071:                     $is_custom{$item} = 1;
 1072:                 }
 1073:                 if (defined($settings->{'showlogo'}{$item})) {
 1074:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1075:                 }
 1076:             }
 1077:             foreach my $item (@logintext) {
 1078:                 if ($settings->{$item} ne '') {
 1079:                     $designs{'logintext'}{$item} = $settings->{$item};
 1080:                     $is_custom{$item} = 1;
 1081:                 }
 1082:             }
 1083:             if ($settings->{'font'} ne '') {
 1084:                 $designs{'font'} = $settings->{'font'};
 1085:                 $is_custom{'font'} = 1;
 1086:             }
 1087:             foreach my $item (@bgs) {
 1088:                 if ($settings->{$item} ne '') {
 1089:                     $designs{'bgs'}{$item} = $settings->{$item};
 1090:                     $is_custom{$item} = 1;
 1091:                 }
 1092:             }
 1093:             foreach my $item (@links) {
 1094:                 if ($settings->{$item} ne '') {
 1095:                     $designs{'links'}{$item} = $settings->{$item};
 1096:                     $is_custom{$item} = 1;
 1097:                 }
 1098:             }
 1099:         } else {
 1100:             if ($designhash{$dom.'.login.font'} ne '') {
 1101:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1102:                 $is_custom{'font'} = 1;
 1103:             }
 1104:             foreach my $item (@images) {
 1105:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1106:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1107:                     $is_custom{$item} = 1;
 1108:                 }
 1109:             }
 1110:             foreach my $item (@bgs) {
 1111:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1112:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1113:                     $is_custom{$item} = 1;
 1114:                 }
 1115:             }
 1116:             foreach my $item (@links) {
 1117:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1118:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1119:                     $is_custom{$item} = 1;
 1120:                 }
 1121:             }
 1122:         }
 1123:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1124:                                                       logo => 'Institution Logo',
 1125:                                                       domlogo => 'Domain Logo',
 1126:                                                       login => 'Login box');
 1127:         my $itemcount = 1;
 1128:         foreach my $item (@toggles) {
 1129:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1130:             $datatable .=  
 1131:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1132:                 '</td><td>'.
 1133:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1134:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1135:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1136:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1137:                 '</tr>';
 1138:             $itemcount ++;
 1139:         }
 1140:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1141:         $datatable .= '</tr></table></td></tr>';
 1142:     } elsif ($caller eq 'help') {
 1143:         my ($defaulturl,$defaulttype,%url,%type,%lt,%langchoices);
 1144:         my $switchserver = &check_switchserver($dom,$confname);
 1145:         my $itemcount = 1;
 1146:         $defaulturl = '/adm/loginproblems.html';
 1147:         $defaulttype = 'default';
 1148:         %lt = &Apache::lonlocal::texthash (
 1149:                      del     => 'Delete?',
 1150:                      rep     => 'Replace:',
 1151:                      upl     => 'Upload:',
 1152:                      default => 'Default',
 1153:                      custom  => 'Custom',
 1154:                                              );
 1155:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1156:         my @currlangs;
 1157:         if (ref($settings) eq 'HASH') {
 1158:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1159:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1160:                     next if ($settings->{'helpurl'}{$key} eq '');
 1161:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1162:                     $type{$key} = 'custom';
 1163:                     unless ($key eq 'nolang') {
 1164:                         push(@currlangs,$key);
 1165:                     }
 1166:                 }
 1167:             } elsif ($settings->{'helpurl'} ne '') {
 1168:                 $type{'nolang'} = 'custom';
 1169:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1170:             }
 1171:         }
 1172:         foreach my $lang ('nolang',sort(@currlangs)) {
 1173:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1174:             $datatable .= '<tr'.$css_class.'>';
 1175:             if ($url{$lang} eq '') {
 1176:                 $url{$lang} = $defaulturl;
 1177:             }
 1178:             if ($type{$lang} eq '') {
 1179:                 $type{$lang} = $defaulttype;
 1180:             }
 1181:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1182:             if ($lang eq 'nolang') {
 1183:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1184:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1185:             } else {
 1186:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1187:                                   $langchoices{$lang},
 1188:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1189:             }
 1190:             $datatable .= '</span></td>'."\n".
 1191:                           '<td class="LC_left_item">';
 1192:             if ($type{$lang} eq 'custom') {
 1193:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1194:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1195:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1196:             } else {
 1197:                 $datatable .= $lt{'upl'};
 1198:             }
 1199:             $datatable .='<br />';
 1200:             if ($switchserver) {
 1201:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1202:             } else {
 1203:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1204:             }
 1205:             $datatable .= '</td></tr>';
 1206:             $itemcount ++;
 1207:         }
 1208:         my @addlangs;
 1209:         foreach my $lang (sort(keys(%langchoices))) {
 1210:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1211:             push(@addlangs,$lang);
 1212:         }
 1213:         if (@addlangs > 0) {
 1214:             my %toadd;
 1215:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1216:             $toadd{''} = &mt('Select');
 1217:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1218:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1219:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1220:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1221:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1222:             if ($switchserver) {
 1223:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1224:             } else {
 1225:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1226:             }
 1227:             $datatable .= '</td></tr>';
 1228:             $itemcount ++;
 1229:         }
 1230:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1231:     } elsif ($caller eq 'headtag') {
 1232:         my %domservers = &Apache::lonnet::get_servers($dom);
 1233:         my $choice = $choices{'headtag'};
 1234:         $css_class = ' class="LC_odd_row"';
 1235:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1236:                       '<td align="left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1237:                       '<th>'.$choices{'current'}.'</th>'.
 1238:                       '<th>'.$choices{'action'}.'</th>'.
 1239:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1240:         my (%currurls,%currexempt);
 1241:         if (ref($settings) eq 'HASH') {
 1242:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1243:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1244:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1245:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1246:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1247:                     }
 1248:                 }
 1249:             }
 1250:         }
 1251:         my %lt = &Apache::lonlocal::texthash(
 1252:                                                del  => 'Delete?',
 1253:                                                rep  => 'Replace:',
 1254:                                                upl  => 'Upload:',
 1255:                                                curr => 'View contents',
 1256:                                                none => 'None',
 1257:         );
 1258:         my $switchserver = &check_switchserver($dom,$confname);
 1259:         foreach my $lonhost (sort(keys(%domservers))) {
 1260:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1261:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1262:             if ($currurls{$lonhost}) {
 1263:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1264:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1265:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1266:                               '">'.$lt{'curr'}.'</a></td>'.
 1267:                               '<td><span class="LC_nobreak"><label>'.
 1268:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1269:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1270:             } else {
 1271:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1272:             }
 1273:             $datatable .='<br />';
 1274:             if ($switchserver) {
 1275:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1276:             } else {
 1277:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1278:             }
 1279:             $datatable .= '</td><td><input type="textbox" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1280:         }
 1281:         $datatable .= '</table></td></tr>';
 1282:     }
 1283:     return $datatable;
 1284: }
 1285: 
 1286: sub login_choices {
 1287:     my %choices =
 1288:         &Apache::lonlocal::texthash (
 1289:             coursecatalog => 'Display Course/Community Catalog link?',
 1290:             adminmail     => "Display Administrator's E-mail Address?",
 1291:             helpdesk      => 'Display "Contact Helpdesk" link',
 1292:             disallowlogin => "Login page requests redirected",
 1293:             hostid        => "Server",
 1294:             server        => "Redirect to:",
 1295:             serverpath    => "Path",
 1296:             custompath    => "Custom", 
 1297:             exempt        => "Exempt IP(s)",
 1298:             directlogin   => "No redirect",
 1299:             newuser       => "Link to create a user account",
 1300:             img           => "Header",
 1301:             logo          => "Main Logo",
 1302:             domlogo       => "Domain Logo",
 1303:             login         => "Log-in Header", 
 1304:             textcol       => "Text color",
 1305:             bgcol         => "Box color",
 1306:             bgs           => "Background colors",
 1307:             links         => "Link colors",
 1308:             font          => "Font color",
 1309:             pgbg          => "Header",
 1310:             mainbg        => "Page",
 1311:             sidebg        => "Login box",
 1312:             link          => "Link",
 1313:             alink         => "Active link",
 1314:             vlink         => "Visited link",
 1315:             headtag       => "Custom markup",
 1316:             action        => "Action",
 1317:             current       => "Current",
 1318:         );
 1319:     return %choices;
 1320: }
 1321: 
 1322: sub print_rolecolors {
 1323:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1324:     my %choices = &color_font_choices();
 1325:     my @bgs = ('pgbg','tabbg','sidebg');
 1326:     my @links = ('link','alink','vlink');
 1327:     my @images = ('img');
 1328:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1329:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1330:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1331:     my (%is_custom,%designs);
 1332:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1333:     if (ref($settings) eq 'HASH') {
 1334:         if (ref($settings->{$role}) eq 'HASH') {
 1335:             if ($settings->{$role}->{'img'} ne '') {
 1336:                 $designs{'img'} = $settings->{$role}->{'img'};
 1337:                 $is_custom{'img'} = 1;
 1338:             }
 1339:             if ($settings->{$role}->{'font'} ne '') {
 1340:                 $designs{'font'} = $settings->{$role}->{'font'};
 1341:                 $is_custom{'font'} = 1;
 1342:             }
 1343:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1344:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1345:                 $is_custom{'fontmenu'} = 1;
 1346:             }
 1347:             foreach my $item (@bgs) {
 1348:                 if ($settings->{$role}->{$item} ne '') {
 1349:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1350:                     $is_custom{$item} = 1;
 1351:                 }
 1352:             }
 1353:             foreach my $item (@links) {
 1354:                 if ($settings->{$role}->{$item} ne '') {
 1355:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1356:                     $is_custom{$item} = 1;
 1357:                 }
 1358:             }
 1359:         }
 1360:     } else {
 1361:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1362:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1363:             $is_custom{'img'} = 1;
 1364:         }
 1365:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1366:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1367:             $is_custom{'fontmenu'} = 1; 
 1368:         }
 1369:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1370:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1371:             $is_custom{'font'} = 1;
 1372:         }
 1373:         foreach my $item (@bgs) {
 1374:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1375:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1376:                 $is_custom{$item} = 1;
 1377:             
 1378:             }
 1379:         }
 1380:         foreach my $item (@links) {
 1381:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1382:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1383:                 $is_custom{$item} = 1;
 1384:             }
 1385:         }
 1386:     }
 1387:     my $itemcount = 1;
 1388:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 1389:     $datatable .= '</tr></table></td></tr>';
 1390:     return $datatable;
 1391: }
 1392: 
 1393: sub role_defaults {
 1394:     my ($role,$bgs,$links,$images,$logintext) = @_;
 1395:     my %defaults;
 1396:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 1397:         return %defaults;
 1398:     }
 1399:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1400:     if ($role eq 'login') {
 1401:         %defaults = (
 1402:                        font => $defaultdesign{$role.'.font'},
 1403:                     );
 1404:         if (ref($logintext) eq 'ARRAY') {
 1405:             foreach my $item (@{$logintext}) {
 1406:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 1407:             }
 1408:         }
 1409:         foreach my $item (@{$images}) {
 1410:             $defaults{'showlogo'}{$item} = 1;
 1411:         }
 1412:     } else {
 1413:         %defaults = (
 1414:                        img => $defaultdesign{$role.'.img'},
 1415:                        font => $defaultdesign{$role.'.font'},
 1416:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 1417:                     );
 1418:     }
 1419:     foreach my $item (@{$bgs}) {
 1420:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 1421:     }
 1422:     foreach my $item (@{$links}) {
 1423:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 1424:     }
 1425:     foreach my $item (@{$images}) {
 1426:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 1427:     }
 1428:     return %defaults;
 1429: }
 1430: 
 1431: sub display_color_options {
 1432:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 1433:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 1434:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1435:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1436:     my $datatable = '<tr'.$css_class.'>'.
 1437:         '<td>'.$choices->{'font'}.'</td>';
 1438:     if (!$is_custom->{'font'}) {
 1439:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span id="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 1440:     } else {
 1441:         $datatable .= '<td>&nbsp;</td>';
 1442:     }
 1443:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 1444: 
 1445:     $datatable .= '<td><span class="LC_nobreak">'.
 1446:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 1447:                   ' value="'.$current_color.'" />&nbsp;'.
 1448:                   '&nbsp;</td></tr>';
 1449:     unless ($role eq 'login') { 
 1450:         $datatable .= '<tr'.$css_class.'>'.
 1451:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 1452:         if (!$is_custom->{'fontmenu'}) {
 1453:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span id="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 1454:         } else {
 1455:             $datatable .= '<td>&nbsp;</td>';
 1456:         }
 1457: 	$current_color = $designs->{'fontmenu'} ?
 1458: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 1459:         $datatable .= '<td><span class="LC_nobreak">'.
 1460:                       '<input class="colorchooser" type="text" size="10" name="'
 1461: 		      .$role.'_fontmenu"'.
 1462:                       ' value="'.$current_color.'" />&nbsp;'.
 1463:                       '&nbsp;</td></tr>';
 1464:     }
 1465:     my $switchserver = &check_switchserver($dom,$confname);
 1466:     foreach my $img (@{$images}) {
 1467: 	$itemcount ++;
 1468:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1469:         $datatable .= '<tr'.$css_class.'>'.
 1470:                       '<td>'.$choices->{$img};
 1471:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors);
 1472:         if ($role eq 'login') {
 1473:             if ($img eq 'login') {
 1474:                 $login_hdr_pick =
 1475:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 1476:                 $logincolors =
 1477:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 1478:                                        $designs,$defaults);
 1479:             } elsif ($img ne 'domlogo') {
 1480:                 $datatable.= &logo_display_options($img,$defaults,$designs);
 1481:             }
 1482:         }
 1483:         $datatable .= '</td>';
 1484:         if ($designs->{$img} ne '') {
 1485:             $imgfile = $designs->{$img};
 1486: 	    $img_import = ($imgfile =~ m{^/adm/});
 1487:         } else {
 1488:             $imgfile = $defaults->{$img};
 1489:         }
 1490:         if ($imgfile) {
 1491:             my ($showfile,$fullsize);
 1492:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 1493:                 my $urldir = $1;
 1494:                 my $filename = $2;
 1495:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 1496:                 if (@info) {
 1497:                     my $thumbfile = 'tn-'.$filename;
 1498:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 1499:                     if (@thumb) {
 1500:                         $showfile = $urldir.'/'.$thumbfile;
 1501:                     } else {
 1502:                         $showfile = $imgfile;
 1503:                     }
 1504:                 } else {
 1505:                     $showfile = '';
 1506:                 }
 1507:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 1508:                 $showfile = $imgfile;
 1509:                 my $imgdir = $1;
 1510:                 my $filename = $2;
 1511:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 1512:                     $showfile = "/$imgdir/tn-".$filename;
 1513:                 } else {
 1514:                     my $input = $londocroot.$imgfile;
 1515:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 1516:                     if (!-e $output) {
 1517:                         my ($width,$height) = &thumb_dimensions();
 1518:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 1519:                         if ($fullwidth ne '' && $fullheight ne '') {
 1520:                             if ($fullwidth > $width && $fullheight > $height) { 
 1521:                                 my $size = $width.'x'.$height;
 1522:                                 system("convert -sample $size $input $output");
 1523:                                 $showfile = "/$imgdir/tn-".$filename;
 1524:                             }
 1525:                         }
 1526:                     }
 1527:                 }
 1528:             }
 1529:             if ($showfile) {
 1530:                 if ($showfile =~ m{^/(adm|res)/}) {
 1531:                     if ($showfile =~ m{^/res/}) {
 1532:                         my $local_showfile =
 1533:                             &Apache::lonnet::filelocation('',$showfile);
 1534:                         &Apache::lonnet::repcopy($local_showfile);
 1535:                     }
 1536:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 1537:                 }
 1538:                 if ($imgfile) {
 1539:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 1540:                         if ($imgfile =~ m{^/res/}) {
 1541:                             my $local_imgfile =
 1542:                                 &Apache::lonnet::filelocation('',$imgfile);
 1543:                             &Apache::lonnet::repcopy($local_imgfile);
 1544:                         }
 1545:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 1546:                     } else {
 1547:                         $fullsize = $imgfile;
 1548:                     }
 1549:                 }
 1550:                 $datatable .= '<td>';
 1551:                 if ($img eq 'login') {
 1552:                     $datatable .= $login_hdr_pick;
 1553:                 } 
 1554:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 1555:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 1556:             } else {
 1557:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1558:                               &mt('Upload:').'<br />';
 1559:             }
 1560:         } else {
 1561:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1562:                           &mt('Upload:').'<br />';
 1563:         }
 1564:         if ($switchserver) {
 1565:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1566:         } else {
 1567:             if ($img ne 'login') { # suppress file selection for Log-in header
 1568:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 1569:             }
 1570:         }
 1571:         $datatable .= '</td></tr>';
 1572:     }
 1573:     $itemcount ++;
 1574:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1575:     $datatable .= '<tr'.$css_class.'>'.
 1576:                   '<td>'.$choices->{'bgs'}.'</td>';
 1577:     my $bgs_def;
 1578:     foreach my $item (@{$bgs}) {
 1579:         if (!$is_custom->{$item}) {
 1580:             $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>';
 1581:         }
 1582:     }
 1583:     if ($bgs_def) {
 1584:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 1585:     } else {
 1586:         $datatable .= '<td>&nbsp;</td>';
 1587:     }
 1588:     $datatable .= '<td class="LC_right_item">'.
 1589:                   '<table border="0"><tr>';
 1590: 
 1591:     foreach my $item (@{$bgs}) {
 1592:         $datatable .= '<td align="center">'.$choices->{$item};
 1593: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 1594:         if ($designs->{'bgs'}{$item}) {
 1595:             $datatable .= '&nbsp;';
 1596:         }
 1597:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 1598:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 1599:     }
 1600:     $datatable .= '</tr></table></td></tr>';
 1601:     $itemcount ++;
 1602:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1603:     $datatable .= '<tr'.$css_class.'>'.
 1604:                   '<td>'.$choices->{'links'}.'</td>';
 1605:     my $links_def;
 1606:     foreach my $item (@{$links}) {
 1607:         if (!$is_custom->{$item}) {
 1608:             $links_def .= '<td>'.$choices->{$item}.'<br /><span id="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 1609:         }
 1610:     }
 1611:     if ($links_def) {
 1612:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 1613:     } else {
 1614:         $datatable .= '<td>&nbsp;</td>';
 1615:     }
 1616:     $datatable .= '<td class="LC_right_item">'.
 1617:                   '<table border="0"><tr>';
 1618:     foreach my $item (@{$links}) {
 1619: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 1620:         $datatable .= '<td align="center">'.$choices->{$item}."\n";
 1621:         if ($designs->{'links'}{$item}) {
 1622:             $datatable.='&nbsp;';
 1623:         }
 1624:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 1625:                       '" /></td>';
 1626:     }
 1627:     $$rowtotal += $itemcount;
 1628:     return $datatable;
 1629: }
 1630: 
 1631: sub logo_display_options {
 1632:     my ($img,$defaults,$designs) = @_;
 1633:     my $checkedon;
 1634:     if (ref($defaults) eq 'HASH') {
 1635:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 1636:             if ($defaults->{'showlogo'}{$img}) {
 1637:                 $checkedon = 'checked="checked" ';     
 1638:             }
 1639:         } 
 1640:     }
 1641:     if (ref($designs) eq 'HASH') {
 1642:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 1643:             if (defined($designs->{'showlogo'}{$img})) {
 1644:                 if ($designs->{'showlogo'}{$img} == 0) {
 1645:                     $checkedon = '';
 1646:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 1647:                     $checkedon = 'checked="checked" ';
 1648:                 }
 1649:             }
 1650:         }
 1651:     }
 1652:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 1653:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 1654:            &mt('show').'</label>'."\n";
 1655: }
 1656: 
 1657: sub login_header_options  {
 1658:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 1659:     my $output = '';
 1660:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 1661:         $output .= &mt('Text default(s):').'<br />';
 1662:         if (!$is_custom->{'textcol'}) {
 1663:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 1664:                        '&nbsp;&nbsp;&nbsp;';
 1665:         }
 1666:         if (!$is_custom->{'bgcol'}) {
 1667:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 1668:                        '<span id="css_'.$role.'_font" style="background-color: '.
 1669:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 1670:         }
 1671:         $output .= '<br />';
 1672:     }
 1673:     $output .='<br />';
 1674:     return $output;
 1675: }
 1676: 
 1677: sub login_text_colors {
 1678:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 1679:     my $color_menu = '<table border="0"><tr>';
 1680:     foreach my $item (@{$logintext}) {
 1681:         $color_menu .= '<td align="center">'.$choices->{$item};
 1682:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 1683:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 1684:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 1685:     }
 1686:     $color_menu .= '</tr></table><br />';
 1687:     return $color_menu;
 1688: }
 1689: 
 1690: sub image_changes {
 1691:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 1692:     my $output;
 1693:     if ($img eq 'login') {
 1694:             # suppress image for Log-in header
 1695:     } elsif (!$is_custom) {
 1696:         if ($img ne 'domlogo') {
 1697:             $output .= &mt('Default image:').'<br />';
 1698:         } else {
 1699:             $output .= &mt('Default in use:').'<br />';
 1700:         }
 1701:     }
 1702:     if ($img eq 'login') { # suppress image for Log-in header
 1703:         $output .= '<td>'.$logincolors;
 1704:     } else {
 1705:         if ($img_import) {
 1706:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 1707:         }
 1708:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 1709:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 1710:         if ($is_custom) {
 1711:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 1712:                        '<input type="checkbox" name="'.
 1713:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 1714:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 1715:         } else {
 1716:             $output .= '<td valign="middle">'.$logincolors.&mt('Upload:').'<br />';
 1717:         }
 1718:     }
 1719:     return $output;
 1720: }
 1721: 
 1722: sub print_quotas {
 1723:     my ($dom,$settings,$rowtotal,$action) = @_;
 1724:     my $context;
 1725:     if ($action eq 'quotas') {
 1726:         $context = 'tools';
 1727:     } else {
 1728:         $context = $action;
 1729:     }
 1730:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 1731:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 1732:     my $typecount = 0;
 1733:     my ($css_class,%titles);
 1734:     if ($context eq 'requestcourses') {
 1735:         @usertools = ('official','unofficial','community','textbook');
 1736:         @options =('norequest','approval','validate','autolimit');
 1737:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 1738:         %titles = &courserequest_titles();
 1739:     } elsif ($context eq 'requestauthor') {
 1740:         @usertools = ('author');
 1741:         @options = ('norequest','approval','automatic');
 1742:         %titles = &authorrequest_titles();
 1743:     } else {
 1744:         @usertools = ('aboutme','blog','webdav','portfolio');
 1745:         %titles = &tool_titles();
 1746:     }
 1747:     if (ref($types) eq 'ARRAY') {
 1748:         foreach my $type (@{$types}) {
 1749:             my ($currdefquota,$currauthorquota);
 1750:             unless (($context eq 'requestcourses') ||
 1751:                     ($context eq 'requestauthor')) {
 1752:                 if (ref($settings) eq 'HASH') {
 1753:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 1754:                         $currdefquota = $settings->{defaultquota}->{$type};
 1755:                     } else {
 1756:                         $currdefquota = $settings->{$type};
 1757:                     }
 1758:                     if (ref($settings->{authorquota}) eq 'HASH') {
 1759:                         $currauthorquota = $settings->{authorquota}->{$type};
 1760:                     }
 1761:                 }
 1762:             }
 1763:             if (defined($usertypes->{$type})) {
 1764:                 $typecount ++;
 1765:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 1766:                 $datatable .= '<tr'.$css_class.'>'.
 1767:                               '<td>'.$usertypes->{$type}.'</td>'.
 1768:                               '<td class="LC_left_item">';
 1769:                 if ($context eq 'requestcourses') {
 1770:                     $datatable .= '<table><tr>';
 1771:                 }
 1772:                 my %cell;  
 1773:                 foreach my $item (@usertools) {
 1774:                     if ($context eq 'requestcourses') {
 1775:                         my ($curroption,$currlimit);
 1776:                         if (ref($settings) eq 'HASH') {
 1777:                             if (ref($settings->{$item}) eq 'HASH') {
 1778:                                 $curroption = $settings->{$item}->{$type};
 1779:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 1780:                                     $currlimit = $1; 
 1781:                                 }
 1782:                             }
 1783:                         }
 1784:                         if (!$curroption) {
 1785:                             $curroption = 'norequest';
 1786:                         }
 1787:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 1788:                         foreach my $option (@options) {
 1789:                             my $val = $option;
 1790:                             if ($option eq 'norequest') {
 1791:                                 $val = 0;  
 1792:                             }
 1793:                             if ($option eq 'validate') {
 1794:                                 my $canvalidate = 0;
 1795:                                 if (ref($validations{$item}) eq 'HASH') { 
 1796:                                     if ($validations{$item}{$type}) {
 1797:                                         $canvalidate = 1;
 1798:                                     }
 1799:                                 }
 1800:                                 next if (!$canvalidate);
 1801:                             }
 1802:                             my $checked = '';
 1803:                             if ($option eq $curroption) {
 1804:                                 $checked = ' checked="checked"';
 1805:                             } elsif ($option eq 'autolimit') {
 1806:                                 if ($curroption =~ /^autolimit/) {
 1807:                                     $checked = ' checked="checked"';
 1808:                                 }                       
 1809:                             } 
 1810:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 1811:                                   '<input type="radio" name="crsreq_'.$item.
 1812:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 1813:                                   $titles{$option}.'</label>';
 1814:                             if ($option eq 'autolimit') {
 1815:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 1816:                                                 $item.'_limit_'.$type.'" size="1" '.
 1817:                                                 'value="'.$currlimit.'" />';
 1818:                             }
 1819:                             $cell{$item} .= '</span> ';
 1820:                             if ($option eq 'autolimit') {
 1821:                                 $cell{$item} .= $titles{'unlimited'};
 1822:                             }
 1823:                         }
 1824:                     } elsif ($context eq 'requestauthor') {
 1825:                         my $curroption;
 1826:                         if (ref($settings) eq 'HASH') {
 1827:                             $curroption = $settings->{$type};
 1828:                         }
 1829:                         if (!$curroption) {
 1830:                             $curroption = 'norequest';
 1831:                         }
 1832:                         foreach my $option (@options) {
 1833:                             my $val = $option;
 1834:                             if ($option eq 'norequest') {
 1835:                                 $val = 0;
 1836:                             }
 1837:                             my $checked = '';
 1838:                             if ($option eq $curroption) {
 1839:                                 $checked = ' checked="checked"';
 1840:                             }
 1841:                             $datatable .= '<span class="LC_nobreak"><label>'.
 1842:                                   '<input type="radio" name="authorreq_'.$type.
 1843:                                   '" value="'.$val.'"'.$checked.' />'.
 1844:                                   $titles{$option}.'</label></span>&nbsp; ';
 1845:                         }
 1846:                     } else {
 1847:                         my $checked = 'checked="checked" ';
 1848:                         if (ref($settings) eq 'HASH') {
 1849:                             if (ref($settings->{$item}) eq 'HASH') {
 1850:                                 if ($settings->{$item}->{$type} == 0) {
 1851:                                     $checked = '';
 1852:                                 } elsif ($settings->{$item}->{$type} == 1) {
 1853:                                     $checked =  'checked="checked" ';
 1854:                                 }
 1855:                             }
 1856:                         }
 1857:                         $datatable .= '<span class="LC_nobreak"><label>'.
 1858:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 1859:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 1860:                                       '</label></span>&nbsp; ';
 1861:                     }
 1862:                 }
 1863:                 if ($context eq 'requestcourses') {
 1864:                     $datatable .= '</tr><tr>';
 1865:                     foreach my $item (@usertools) {
 1866:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 1867:                     }
 1868:                     $datatable .= '</tr></table>';
 1869:                 }
 1870:                 $datatable .= '</td>';
 1871:                 unless (($context eq 'requestcourses') ||
 1872:                         ($context eq 'requestauthor')) {
 1873:                     $datatable .= 
 1874:                               '<td class="LC_right_item">'.
 1875:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 1876:                               '<input type="text" name="quota_'.$type.
 1877:                               '" value="'.$currdefquota.
 1878:                               '" size="5" /></span>'.('&nbsp;' x 2).
 1879:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 1880:                               '<input type="text" name="authorquota_'.$type.
 1881:                               '" value="'.$currauthorquota.
 1882:                               '" size="5" /></span></td>';
 1883:                 }
 1884:                 $datatable .= '</tr>';
 1885:             }
 1886:         }
 1887:     }
 1888:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 1889:         $defaultquota = '20';
 1890:         $authorquota = '500';
 1891:         if (ref($settings) eq 'HASH') {
 1892:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 1893:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 1894:             } elsif (defined($settings->{'default'})) {
 1895:                 $defaultquota = $settings->{'default'};
 1896:             }
 1897:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 1898:                 $authorquota = $settings->{'authorquota'}->{'default'};
 1899:             }
 1900:         }
 1901:     }
 1902:     $typecount ++;
 1903:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 1904:     $datatable .= '<tr'.$css_class.'>'.
 1905:                   '<td>'.$othertitle.'</td>'.
 1906:                   '<td class="LC_left_item">';
 1907:     if ($context eq 'requestcourses') {
 1908:         $datatable .= '<table><tr>';
 1909:     }
 1910:     my %defcell;
 1911:     foreach my $item (@usertools) {
 1912:         if ($context eq 'requestcourses') {
 1913:             my ($curroption,$currlimit);
 1914:             if (ref($settings) eq 'HASH') {
 1915:                 if (ref($settings->{$item}) eq 'HASH') {
 1916:                     $curroption = $settings->{$item}->{'default'};
 1917:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 1918:                         $currlimit = $1;
 1919:                     }
 1920:                 }
 1921:             }
 1922:             if (!$curroption) {
 1923:                 $curroption = 'norequest';
 1924:             }
 1925:             $datatable .= '<th>'.$titles{$item}.'</th>';
 1926:             foreach my $option (@options) {
 1927:                 my $val = $option;
 1928:                 if ($option eq 'norequest') {
 1929:                     $val = 0;
 1930:                 }
 1931:                 if ($option eq 'validate') {
 1932:                     my $canvalidate = 0;
 1933:                     if (ref($validations{$item}) eq 'HASH') {
 1934:                         if ($validations{$item}{'default'}) {
 1935:                             $canvalidate = 1;
 1936:                         }
 1937:                     }
 1938:                     next if (!$canvalidate);
 1939:                 }
 1940:                 my $checked = '';
 1941:                 if ($option eq $curroption) {
 1942:                     $checked = ' checked="checked"';
 1943:                 } elsif ($option eq 'autolimit') {
 1944:                     if ($curroption =~ /^autolimit/) {
 1945:                         $checked = ' checked="checked"';
 1946:                     }
 1947:                 }
 1948:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 1949:                                   '<input type="radio" name="crsreq_'.$item.
 1950:                                   '_default" value="'.$val.'"'.$checked.' />'.
 1951:                                   $titles{$option}.'</label>';
 1952:                 if ($option eq 'autolimit') {
 1953:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 1954:                                        $item.'_limit_default" size="1" '.
 1955:                                        'value="'.$currlimit.'" />';
 1956:                 }
 1957:                 $defcell{$item} .= '</span> ';
 1958:                 if ($option eq 'autolimit') {
 1959:                     $defcell{$item} .= $titles{'unlimited'};
 1960:                 }
 1961:             }
 1962:         } elsif ($context eq 'requestauthor') {
 1963:             my $curroption;
 1964:             if (ref($settings) eq 'HASH') {
 1965:                 $curroption = $settings->{'default'};
 1966:             }
 1967:             if (!$curroption) {
 1968:                 $curroption = 'norequest';
 1969:             }
 1970:             foreach my $option (@options) {
 1971:                 my $val = $option;
 1972:                 if ($option eq 'norequest') {
 1973:                     $val = 0;
 1974:                 }
 1975:                 my $checked = '';
 1976:                 if ($option eq $curroption) {
 1977:                     $checked = ' checked="checked"';
 1978:                 }
 1979:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1980:                               '<input type="radio" name="authorreq_default"'.
 1981:                               ' value="'.$val.'"'.$checked.' />'.
 1982:                               $titles{$option}.'</label></span>&nbsp; ';
 1983:             }
 1984:         } else {
 1985:             my $checked = 'checked="checked" ';
 1986:             if (ref($settings) eq 'HASH') {
 1987:                 if (ref($settings->{$item}) eq 'HASH') {
 1988:                     if ($settings->{$item}->{'default'} == 0) {
 1989:                         $checked = '';
 1990:                     } elsif ($settings->{$item}->{'default'} == 1) {
 1991:                         $checked = 'checked="checked" ';
 1992:                     }
 1993:                 }
 1994:             }
 1995:             $datatable .= '<span class="LC_nobreak"><label>'.
 1996:                           '<input type="checkbox" name="'.$context.'_'.$item.
 1997:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 1998:                           '</label></span>&nbsp; ';
 1999:         }
 2000:     }
 2001:     if ($context eq 'requestcourses') {
 2002:         $datatable .= '</tr><tr>';
 2003:         foreach my $item (@usertools) {
 2004:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2005:         }
 2006:         $datatable .= '</tr></table>';
 2007:     }
 2008:     $datatable .= '</td>';
 2009:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2010:         $datatable .= '<td class="LC_right_item">'.
 2011:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2012:                       '<input type="text" name="defaultquota" value="'.
 2013:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2014:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2015:                       '<input type="text" name="authorquota" value="'.
 2016:                       $authorquota.'" size="5" /></span></td>';
 2017:     }
 2018:     $datatable .= '</tr>';
 2019:     $typecount ++;
 2020:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2021:     $datatable .= '<tr'.$css_class.'>'.
 2022:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2023:     if ($context eq 'requestcourses') {
 2024:         $datatable .= &mt('(overrides affiliation, if set)').
 2025:                       '</td>'.
 2026:                       '<td class="LC_left_item">'.
 2027:                       '<table><tr>';
 2028:     } else {
 2029:         $datatable .= &mt('(overrides affiliation, if checked)').
 2030:                       '</td>'.
 2031:                       '<td class="LC_left_item" colspan="2">'.
 2032:                       '<br />';
 2033:     }
 2034:     my %advcell;
 2035:     foreach my $item (@usertools) {
 2036:         if ($context eq 'requestcourses') {
 2037:             my ($curroption,$currlimit);
 2038:             if (ref($settings) eq 'HASH') {
 2039:                 if (ref($settings->{$item}) eq 'HASH') {
 2040:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2041:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2042:                         $currlimit = $1;
 2043:                     }
 2044:                 }
 2045:             }
 2046:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2047:             my $checked = '';
 2048:             if ($curroption eq '') {
 2049:                 $checked = ' checked="checked"';
 2050:             }
 2051:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2052:                                '<input type="radio" name="crsreq_'.$item.
 2053:                                '__LC_adv" value=""'.$checked.' />'.
 2054:                                &mt('No override set').'</label></span>&nbsp; ';
 2055:             foreach my $option (@options) {
 2056:                 my $val = $option;
 2057:                 if ($option eq 'norequest') {
 2058:                     $val = 0;
 2059:                 }
 2060:                 if ($option eq 'validate') {
 2061:                     my $canvalidate = 0;
 2062:                     if (ref($validations{$item}) eq 'HASH') {
 2063:                         if ($validations{$item}{'_LC_adv'}) {
 2064:                             $canvalidate = 1;
 2065:                         }
 2066:                     }
 2067:                     next if (!$canvalidate);
 2068:                 }
 2069:                 my $checked = '';
 2070:                 if ($val eq $curroption) {
 2071:                     $checked = ' checked="checked"';
 2072:                 } elsif ($option eq 'autolimit') {
 2073:                     if ($curroption =~ /^autolimit/) {
 2074:                         $checked = ' checked="checked"';
 2075:                     }
 2076:                 }
 2077:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2078:                                   '<input type="radio" name="crsreq_'.$item.
 2079:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2080:                                   $titles{$option}.'</label>';
 2081:                 if ($option eq 'autolimit') {
 2082:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2083:                                        $item.'_limit__LC_adv" size="1" '.
 2084:                                        'value="'.$currlimit.'" />';
 2085:                 }
 2086:                 $advcell{$item} .= '</span> ';
 2087:                 if ($option eq 'autolimit') {
 2088:                     $advcell{$item} .= $titles{'unlimited'};
 2089:                 }
 2090:             }
 2091:         } elsif ($context eq 'requestauthor') {
 2092:             my $curroption;
 2093:             if (ref($settings) eq 'HASH') {
 2094:                 $curroption = $settings->{'_LC_adv'};
 2095:             }
 2096:             my $checked = '';
 2097:             if ($curroption eq '') {
 2098:                 $checked = ' checked="checked"';
 2099:             }
 2100:             $datatable .= '<span class="LC_nobreak"><label>'.
 2101:                           '<input type="radio" name="authorreq__LC_adv"'.
 2102:                           ' value=""'.$checked.' />'.
 2103:                           &mt('No override set').'</label></span>&nbsp; ';
 2104:             foreach my $option (@options) {
 2105:                 my $val = $option;
 2106:                 if ($option eq 'norequest') {
 2107:                     $val = 0;
 2108:                 }
 2109:                 my $checked = '';
 2110:                 if ($val eq $curroption) {
 2111:                     $checked = ' checked="checked"';
 2112:                 }
 2113:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2114:                               '<input type="radio" name="authorreq__LC_adv"'.
 2115:                               ' value="'.$val.'"'.$checked.' />'.
 2116:                               $titles{$option}.'</label></span>&nbsp; ';
 2117:             }
 2118:         } else {
 2119:             my $checked = 'checked="checked" ';
 2120:             if (ref($settings) eq 'HASH') {
 2121:                 if (ref($settings->{$item}) eq 'HASH') {
 2122:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2123:                         $checked = '';
 2124:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2125:                         $checked = 'checked="checked" ';
 2126:                     }
 2127:                 }
 2128:             }
 2129:             $datatable .= '<span class="LC_nobreak"><label>'.
 2130:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2131:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2132:                           '</label></span>&nbsp; ';
 2133:         }
 2134:     }
 2135:     if ($context eq 'requestcourses') {
 2136:         $datatable .= '</tr><tr>';
 2137:         foreach my $item (@usertools) {
 2138:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2139:         }
 2140:         $datatable .= '</tr></table>';
 2141:     }
 2142:     $datatable .= '</td></tr>';
 2143:     $$rowtotal += $typecount;
 2144:     return $datatable;
 2145: }
 2146: 
 2147: sub print_requestmail {
 2148:     my ($dom,$action,$settings,$rowtotal) = @_;
 2149:     my ($now,$datatable,%currapp);
 2150:     $now = time;
 2151:     if (ref($settings) eq 'HASH') {
 2152:         if (ref($settings->{'notify'}) eq 'HASH') {
 2153:             if ($settings->{'notify'}{'approval'} ne '') {
 2154:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2155:             }
 2156:         }
 2157:     }
 2158:     my $numinrow = 2;
 2159:     my $css_class;
 2160:     $css_class = ($$rowtotal%2? ' class="LC_odd_row"':'');
 2161:     my $text;
 2162:     if ($action eq 'requestcourses') {
 2163:         $text = &mt('Receive notification of course requests requiring approval');
 2164:     } elsif ($action eq 'requestauthor') {
 2165:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2166:     } else {
 2167:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2168:     }
 2169:     $datatable = '<tr'.$css_class.'>'.
 2170:                  ' <td>'.$text.'</td>'.
 2171:                  ' <td class="LC_left_item">';
 2172:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2173:                                                  $action.'notifyapproval',%currapp);
 2174:     if ($numdc > 0) {
 2175:         $datatable .= $table;
 2176:     } else {
 2177:         $datatable .= &mt('There are no active Domain Coordinators');
 2178:     }
 2179:     $datatable .='</td></tr>';
 2180:     return $datatable;
 2181: }
 2182: 
 2183: sub print_studentcode {
 2184:     my ($settings,$rowtotal) = @_;
 2185:     my $rownum = 0; 
 2186:     my ($output,%current);
 2187:     my @crstypes = ('official','unofficial','community','textbook');
 2188:     if (ref($settings) eq 'HASH') {
 2189:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2190:             foreach my $type (@crstypes) {
 2191:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2192:             }
 2193:         }
 2194:     }
 2195:     $output .= '<tr>'.
 2196:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2197:                '<td class="LC_left_item">';
 2198:     foreach my $type (@crstypes) {
 2199:         my $check = ' ';
 2200:         if ($current{$type}) {
 2201:             $check = ' checked="checked" ';
 2202:         }
 2203:         $output .= '<span class="LC_nobreak"><label>'.
 2204:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2205:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2206:     }
 2207:     $output .= '</td></tr>';
 2208:     $$rowtotal ++;
 2209:     return $output;
 2210: }
 2211: 
 2212: sub print_textbookcourses {
 2213:     my ($dom,$type,$settings,$rowtotal) = @_;
 2214:     my $rownum = 0;
 2215:     my $css_class;
 2216:     my $itemcount = 1;
 2217:     my $maxnum = 0;
 2218:     my $bookshash;
 2219:     if (ref($settings) eq 'HASH') {
 2220:         $bookshash = $settings->{$type};
 2221:     }
 2222:     my %ordered;
 2223:     if (ref($bookshash) eq 'HASH') {
 2224:         foreach my $item (keys(%{$bookshash})) {
 2225:             if (ref($bookshash->{$item}) eq 'HASH') {
 2226:                 my $num = $bookshash->{$item}{'order'};
 2227:                 $ordered{$num} = $item;
 2228:             }
 2229:         }
 2230:     }
 2231:     my $confname = $dom.'-domainconfig';
 2232:     my $switchserver = &check_switchserver($dom,$confname);
 2233:     my $maxnum = scalar(keys(%ordered));
 2234:     my $datatable;
 2235:     if (keys(%ordered)) {
 2236:         my @items = sort { $a <=> $b } keys(%ordered);
 2237:         for (my $i=0; $i<@items; $i++) {
 2238:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2239:             my $key = $ordered{$items[$i]};
 2240:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2241:             my $coursetitle = $coursehash{'description'};
 2242:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2243:             if (ref($bookshash->{$key}) eq 'HASH') {
 2244:                 $subject = $bookshash->{$key}->{'subject'};
 2245:                 $title = $bookshash->{$key}->{'title'};
 2246:                 if ($type eq 'textbooks') {
 2247:                     $publisher = $bookshash->{$key}->{'publisher'};
 2248:                     $author = $bookshash->{$key}->{'author'};
 2249:                     $image = $bookshash->{$key}->{'image'};
 2250:                     if ($image ne '') {
 2251:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2252:                         my $imagethumb = "$path/tn-".$imagefile;
 2253:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2254:                     }
 2255:                 }
 2256:             }
 2257:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2258:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2259:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2260:             for (my $k=0; $k<=$maxnum; $k++) {
 2261:                 my $vpos = $k+1;
 2262:                 my $selstr;
 2263:                 if ($k == $i) {
 2264:                     $selstr = ' selected="selected" ';
 2265:                 }
 2266:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2267:             }
 2268:             $datatable .= '</select>'.('&nbsp;'x2).
 2269:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2270:                 &mt('Delete?').'</label></span></td>'.
 2271:                 '<td colspan="2">'.
 2272:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2273:                 ('&nbsp;'x2).
 2274:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2275:             if ($type eq 'textbooks') {
 2276:                 $datatable .= ('&nbsp;'x2).
 2277:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2278:                               ('&nbsp;'x2).
 2279:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2280:                               ('&nbsp;'x2).
 2281:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2282:                 if ($image) {
 2283:                     $datatable .= '<span class="LC_nobreak">'.
 2284:                                   $imgsrc.
 2285:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2286:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2287:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2288:                 }
 2289:                 if ($switchserver) {
 2290:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2291:                 } else {
 2292:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2293:                 }
 2294:             }
 2295:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2296:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2297:                           $coursetitle.'</span></td></tr>'."\n";
 2298:             $itemcount ++;
 2299:         }
 2300:     }
 2301:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2302:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2303:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2304:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2305:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2306:     for (my $k=0; $k<$maxnum+1; $k++) {
 2307:         my $vpos = $k+1;
 2308:         my $selstr;
 2309:         if ($k == $maxnum) {
 2310:             $selstr = ' selected="selected" ';
 2311:         }
 2312:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2313:     }
 2314:     $datatable .= '</select>&nbsp;'."\n".
 2315:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</td>'."\n".
 2316:                   '<td colspan="2">'.
 2317:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2318:                   ('&nbsp;'x2).
 2319:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2320:                   ('&nbsp;'x2);
 2321:     if ($type eq 'textbooks') {
 2322:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2323:                       ('&nbsp;'x2).
 2324:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2325:                       ('&nbsp;'x2).
 2326:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2327:         if ($switchserver) {
 2328:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2329:         } else {
 2330:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2331:         }
 2332:     }
 2333:     $datatable .= '</span>'."\n".
 2334:                   '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2335:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2336:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2337:                   &Apache::loncommon::selectcourse_link
 2338:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course');
 2339:                   '</span></td>'."\n".
 2340:                   '</tr>'."\n";
 2341:     $itemcount ++;
 2342:     return $datatable;
 2343: }
 2344: 
 2345: sub textbookcourses_javascript {
 2346:     my ($settings) = @_;
 2347:     return unless(ref($settings) eq 'HASH');
 2348:     my (%ordered,%total,%jstext);
 2349:     foreach my $type ('textbooks','templates') {
 2350:         $total{$type} = 0;
 2351:         if (ref($settings->{$type}) eq 'HASH') {
 2352:             foreach my $item (keys(%{$settings->{$type}})) {
 2353:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2354:                     my $num = $settings->{$type}->{$item}{'order'};
 2355:                     $ordered{$type}{$num} = $item;
 2356:                 }
 2357:             }
 2358:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2359:         }
 2360:         my @jsarray = ();
 2361:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 2362:             push(@jsarray,$ordered{$type}{$item});
 2363:         }
 2364:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 2365:     }
 2366:     return <<"ENDSCRIPT";
 2367: <script type="text/javascript">
 2368: // <![CDATA[
 2369: function reorderBooks(form,item,caller) {
 2370:     var changedVal;
 2371: $jstext{'textbooks'};
 2372: $jstext{'templates'};
 2373:     var newpos;
 2374:     var maxh;
 2375:     if (caller == 'textbooks') {  
 2376:         newpos = 'textbooks_addbook_pos';
 2377:         maxh = 1 + $total{'textbooks'};
 2378:     } else {
 2379:         newpos = 'templates_addbook_pos';
 2380:         maxh = 1 + $total{'templates'};
 2381:     }
 2382:     var current = new Array;
 2383:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2384:     if (item == newpos) {
 2385:         changedVal = newitemVal;
 2386:     } else {
 2387:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2388:         current[newitemVal] = newpos;
 2389:     }
 2390:     if (caller == 'textbooks') {
 2391:         for (var i=0; i<textbooks.length; i++) {
 2392:             var elementName = 'textbooks_'+textbooks[i];
 2393:             if (elementName != item) {
 2394:                 if (form.elements[elementName]) {
 2395:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2396:                     current[currVal] = elementName;
 2397:                 }
 2398:             }
 2399:         }
 2400:     }
 2401:     if (caller == 'templates') {
 2402:         for (var i=0; i<templates.length; i++) {
 2403:             var elementName = 'templates_'+templates[i];
 2404:             if (elementName != item) {
 2405:                 if (form.elements[elementName]) {
 2406:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2407:                     current[currVal] = elementName;
 2408:                 }
 2409:             }
 2410:         }
 2411:     }
 2412:     var oldVal;
 2413:     for (var j=0; j<maxh; j++) {
 2414:         if (current[j] == undefined) {
 2415:             oldVal = j;
 2416:         }
 2417:     }
 2418:     if (oldVal < changedVal) {
 2419:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2420:            var elementName = current[k];
 2421:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2422:         }
 2423:     } else {
 2424:         for (var k=changedVal; k<oldVal; k++) {
 2425:             var elementName = current[k];
 2426:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2427:         }
 2428:     }
 2429:     return;
 2430: }
 2431: 
 2432: // ]]>
 2433: </script>
 2434: 
 2435: ENDSCRIPT
 2436: }
 2437: 
 2438: sub print_autoenroll {
 2439:     my ($dom,$settings,$rowtotal) = @_;
 2440:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 2441:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,$failsafe);
 2442:     if (ref($settings) eq 'HASH') {
 2443:         if (exists($settings->{'run'})) {
 2444:             if ($settings->{'run'} eq '0') {
 2445:                 $runoff = ' checked="checked" ';
 2446:                 $runon = ' ';
 2447:             } else {
 2448:                 $runon = ' checked="checked" ';
 2449:                 $runoff = ' ';
 2450:             }
 2451:         } else {
 2452:             if ($autorun) {
 2453:                 $runon = ' checked="checked" ';
 2454:                 $runoff = ' ';
 2455:             } else {
 2456:                 $runoff = ' checked="checked" ';
 2457:                 $runon = ' ';
 2458:             }
 2459:         }
 2460:         if (exists($settings->{'co-owners'})) {
 2461:             if ($settings->{'co-owners'} eq '0') {
 2462:                 $coownersoff = ' checked="checked" ';
 2463:                 $coownerson = ' ';
 2464:             } else {
 2465:                 $coownerson = ' checked="checked" ';
 2466:                 $coownersoff = ' ';
 2467:             }
 2468:         } else {
 2469:             $coownersoff = ' checked="checked" ';
 2470:             $coownerson = ' ';
 2471:         }
 2472:         if (exists($settings->{'sender_domain'})) {
 2473:             $defdom = $settings->{'sender_domain'};
 2474:         }
 2475:         if (exists($settings->{'autofailsafe'})) {
 2476:             $failsafe = $settings->{'autofailsafe'};
 2477:         }
 2478:     } else {
 2479:         if ($autorun) {
 2480:             $runon = ' checked="checked" ';
 2481:             $runoff = ' ';
 2482:         } else {
 2483:             $runoff = ' checked="checked" ';
 2484:             $runon = ' ';
 2485:         }
 2486:     }
 2487:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 2488:     my $notif_sender;
 2489:     if (ref($settings) eq 'HASH') {
 2490:         $notif_sender = $settings->{'sender_uname'};
 2491:     }
 2492:     my $datatable='<tr class="LC_odd_row">'.
 2493:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 2494:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2495:                   '<input type="radio" name="autoenroll_run"'.
 2496:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2497:                   '<label><input type="radio" name="autoenroll_run"'.
 2498:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 2499:                   '</tr><tr>'.
 2500:                   '<td>'.&mt('Notification messages - sender').
 2501:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 2502:                   &mt('username').':&nbsp;'.
 2503:                   '<input type="text" name="sender_uname" value="'.
 2504:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 2505:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 2506:                   '<tr class="LC_odd_row">'.
 2507:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 2508:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2509:                   '<input type="radio" name="autoassign_coowners"'.
 2510:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2511:                   '<label><input type="radio" name="autoassign_coowners"'.
 2512:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 2513:                   '</tr><tr>'.
 2514:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 2515:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 2516:                   '<input type="text" name="autoenroll_failsafe"'.
 2517:                   ' value="'.$failsafe.'" size="4" /></td></tr>';
 2518:     $$rowtotal += 4;
 2519:     return $datatable;
 2520: }
 2521: 
 2522: sub print_autoupdate {
 2523:     my ($position,$dom,$settings,$rowtotal) = @_;
 2524:     my $datatable;
 2525:     if ($position eq 'top') {
 2526:         my $updateon = ' ';
 2527:         my $updateoff = ' checked="checked" ';
 2528:         my $classlistson = ' ';
 2529:         my $classlistsoff = ' checked="checked" ';
 2530:         if (ref($settings) eq 'HASH') {
 2531:             if ($settings->{'run'} eq '1') {
 2532:                 $updateon = $updateoff;
 2533:                 $updateoff = ' ';
 2534:             }
 2535:             if ($settings->{'classlists'} eq '1') {
 2536:                 $classlistson = $classlistsoff;
 2537:                 $classlistsoff = ' ';
 2538:             }
 2539:         }
 2540:         my %title = (
 2541:                    run => 'Auto-update active?',
 2542:                    classlists => 'Update information in classlists?',
 2543:                     );
 2544:         $datatable = '<tr class="LC_odd_row">'. 
 2545:                   '<td>'.&mt($title{'run'}).'</td>'.
 2546:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2547:                   '<input type="radio" name="autoupdate_run"'.
 2548:                   $updateon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2549:                   '<label><input type="radio" name="autoupdate_run"'.
 2550:                   $updateoff.'value="0" />'.&mt('No').'</label></span></td>'.
 2551:                   '</tr><tr>'.
 2552:                   '<td>'.&mt($title{'classlists'}).'</td>'.
 2553:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 2554:                   '<label><input type="radio" name="classlists"'.
 2555:                   $classlistson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2556:                   '<label><input type="radio" name="classlists"'.
 2557:                   $classlistsoff.'value="0" />'.&mt('No').'</label></span></td>'.
 2558:                   '</tr>';
 2559:         $$rowtotal += 2;
 2560:     } elsif ($position eq 'middle') {
 2561:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2562:         my $numinrow = 3;
 2563:         my $locknamesettings;
 2564:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 2565:                                      $dom,$numinrow,$othertitle,
 2566:                                     'lockablenames');
 2567:         $$rowtotal ++;
 2568:     } else {
 2569:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2570:         my @fields = ('lastname','firstname','middlename','generation',
 2571:                       'permanentemail','id');
 2572:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 2573:         my $numrows = 0;
 2574:         if (ref($types) eq 'ARRAY') {
 2575:             if (@{$types} > 0) {
 2576:                 $datatable = 
 2577:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 2578:                                          \@fields,$types,\$numrows);
 2579:                     $$rowtotal += @{$types}; 
 2580:             }
 2581:         }
 2582:         $datatable .= 
 2583:             &usertype_update_row($settings,{'default' => $othertitle},
 2584:                                  \%fieldtitles,\@fields,['default'],
 2585:                                  \$numrows);
 2586:         $$rowtotal ++;     
 2587:     }
 2588:     return $datatable;
 2589: }
 2590: 
 2591: sub print_autocreate {
 2592:     my ($dom,$settings,$rowtotal) = @_;
 2593:     my (%createon,%createoff,%currhash);
 2594:     my @types = ('xml','req');
 2595:     if (ref($settings) eq 'HASH') {
 2596:         foreach my $item (@types) {
 2597:             $createoff{$item} = ' checked="checked" ';
 2598:             $createon{$item} = ' ';
 2599:             if (exists($settings->{$item})) {
 2600:                 if ($settings->{$item}) {
 2601:                     $createon{$item} = ' checked="checked" ';
 2602:                     $createoff{$item} = ' ';
 2603:                 }
 2604:             }
 2605:         }
 2606:         if ($settings->{'xmldc'} ne '') {
 2607:             $currhash{$settings->{'xmldc'}} = 1;
 2608:         }
 2609:     } else {
 2610:         foreach my $item (@types) {
 2611:             $createoff{$item} = ' checked="checked" ';
 2612:             $createon{$item} = ' ';
 2613:         }
 2614:     }
 2615:     $$rowtotal += 2;
 2616:     my $numinrow = 2;
 2617:     my $datatable='<tr class="LC_odd_row">'.
 2618:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 2619:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2620:                   '<input type="radio" name="autocreate_xml"'.
 2621:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2622:                   '<label><input type="radio" name="autocreate_xml"'.
 2623:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 2624:                   '</td></tr><tr>'.
 2625:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 2626:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2627:                   '<input type="radio" name="autocreate_req"'.
 2628:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2629:                   '<label><input type="radio" name="autocreate_req"'.
 2630:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 2631:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 2632:                                                    'autocreate_xmldc',%currhash);
 2633:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 2634:     if ($numdc > 1) {
 2635:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 2636:                       '</td><td class="LC_left_item">';
 2637:     } else {
 2638:         $datatable .= &mt('Course creation processed as:').
 2639:                       '</td><td class="LC_right_item">';
 2640:     }
 2641:     $datatable .= $dctable.'</td></tr>';
 2642:     $$rowtotal += $rows;
 2643:     return $datatable;
 2644: }
 2645: 
 2646: sub print_directorysrch {
 2647:     my ($position,$dom,$settings,$rowtotal) = @_;
 2648:     my $datatable;
 2649:     if ($position eq 'top') {
 2650:         my $instsrchon = ' ';
 2651:         my $instsrchoff = ' checked="checked" ';
 2652:         my ($exacton,$containson,$beginson);
 2653:         my $instlocalon = ' ';
 2654:         my $instlocaloff = ' checked="checked" ';
 2655:         if (ref($settings) eq 'HASH') {
 2656:             if ($settings->{'available'} eq '1') {
 2657:                 $instsrchon = $instsrchoff;
 2658:                 $instsrchoff = ' ';
 2659:             }
 2660:             if ($settings->{'localonly'} eq '1') {
 2661:                 $instlocalon = $instlocaloff;
 2662:                 $instlocaloff = ' ';
 2663:             }
 2664:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 2665:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 2666:                     if ($type eq 'exact') {
 2667:                         $exacton = ' checked="checked" ';
 2668:                     } elsif ($type eq 'contains') {
 2669:                         $containson = ' checked="checked" ';
 2670:                     } elsif ($type eq 'begins') {
 2671:                         $beginson = ' checked="checked" ';
 2672:                     }
 2673:                 }
 2674:             } else {
 2675:                 if ($settings->{'searchtypes'} eq 'exact') {
 2676:                     $exacton = ' checked="checked" ';
 2677:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 2678:                     $containson = ' checked="checked" ';
 2679:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 2680:                     $exacton = ' checked="checked" ';
 2681:                     $containson = ' checked="checked" ';
 2682:                 }
 2683:             }
 2684:         }
 2685:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 2686:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2687: 
 2688:         my $numinrow = 4;
 2689:         my $cansrchrow = 0;
 2690:         $datatable='<tr class="LC_odd_row">'.
 2691:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 2692:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2693:                    '<input type="radio" name="dirsrch_available"'.
 2694:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2695:                    '<label><input type="radio" name="dirsrch_available"'.
 2696:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 2697:                    '</tr><tr>'.
 2698:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 2699:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2700:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 2701:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 2702:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 2703:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 2704:                    '</tr>';
 2705:         $$rowtotal += 2;
 2706:         if (ref($usertypes) eq 'HASH') {
 2707:             if (keys(%{$usertypes}) > 0) {
 2708:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 2709:                                              $numinrow,$othertitle,'cansearch');
 2710:                 $cansrchrow = 1;
 2711:             }
 2712:         }
 2713:         if ($cansrchrow) {
 2714:             $$rowtotal ++;
 2715:             $datatable .= '<tr>';
 2716:         } else {
 2717:             $datatable .= '<tr class="LC_odd_row">';
 2718:         }
 2719:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 2720:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 2721:         foreach my $title (@{$titleorder}) {
 2722:             if (defined($searchtitles->{$title})) {
 2723:                 my $check = ' ';
 2724:                 if (ref($settings) eq 'HASH') {
 2725:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 2726:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 2727:                             $check = ' checked="checked" ';
 2728:                         }
 2729:                     }
 2730:                 }
 2731:                 $datatable .= '<td class="LC_left_item">'.
 2732:                               '<span class="LC_nobreak"><label>'.
 2733:                               '<input type="checkbox" name="searchby" '.
 2734:                               'value="'.$title.'"'.$check.'/>'.
 2735:                               $searchtitles->{$title}.'</label></span></td>';
 2736:             }
 2737:         }
 2738:         $datatable .= '</tr></table></td></tr>';
 2739:         $$rowtotal ++;
 2740:         if ($cansrchrow) {
 2741:             $datatable .= '<tr class="LC_odd_row">';
 2742:         } else {
 2743:             $datatable .= '<tr>';
 2744:         }
 2745:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 2746:                       '<td class="LC_left_item" colspan="2">'.
 2747:                       '<span class="LC_nobreak"><label>'.
 2748:                       '<input type="checkbox" name="searchtypes" '.
 2749:                       $exacton.' value="exact" />'.&mt('Exact match').
 2750:                       '</label>&nbsp;'.
 2751:                       '<label><input type="checkbox" name="searchtypes" '.
 2752:                       $beginson.' value="begins" />'.&mt('Begins with').
 2753:                       '</label>&nbsp;'.
 2754:                       '<label><input type="checkbox" name="searchtypes" '.
 2755:                       $containson.' value="contains" />'.&mt('Contains').
 2756:                       '</label></span></td></tr>';
 2757:         $$rowtotal ++;
 2758:     } else {
 2759:         my $domsrchon = ' checked="checked" ';
 2760:         my $domsrchoff = ' ';
 2761:         my $domlocalon = ' ';
 2762:         my $domlocaloff = ' checked="checked" ';
 2763:         if (ref($settings) eq 'HASH') {
 2764:             if ($settings->{'lclocalonly'} eq '1') {
 2765:                 $domlocalon = $domlocaloff;
 2766:                 $domlocaloff = ' ';
 2767:             }
 2768:             if ($settings->{'lcavailable'} eq '0') {
 2769:                 $domsrchoff = $domsrchon;
 2770:                 $domsrchon = ' ';
 2771:             }
 2772:         }
 2773:         $datatable='<tr class="LC_odd_row">'.
 2774:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 2775:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2776:                       '<input type="radio" name="dirsrch_domavailable"'.
 2777:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2778:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 2779:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 2780:                       '</tr><tr>'.
 2781:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 2782:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2783:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 2784:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 2785:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 2786:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 2787:                       '</tr>';
 2788:         $$rowtotal += 2;
 2789:     }
 2790:     return $datatable;
 2791: }
 2792: 
 2793: sub print_contacts {
 2794:     my ($position,$dom,$settings,$rowtotal) = @_;
 2795:     my $datatable;
 2796:     my @contacts = ('adminemail','supportemail');
 2797:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 2798:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings);
 2799:     if ($position eq 'top') {
 2800:         if (ref($settings) eq 'HASH') {
 2801:             foreach my $item (@contacts) {
 2802:                 if (exists($settings->{$item})) {
 2803:                     $to{$item} = $settings->{$item};
 2804:                 }
 2805:             }
 2806:         }
 2807:     } elsif ($position eq 'middle') {
 2808:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 2809:                      'updatesmail','idconflictsmail');
 2810:         foreach my $type (@mailings) {
 2811:             $otheremails{$type} = '';
 2812:         }
 2813:     } else {
 2814:         @mailings = ('helpdeskmail','otherdomsmail');
 2815:         foreach my $type (@mailings) {
 2816:             $otheremails{$type} = '';
 2817:         }
 2818:         $bccemails{'helpdeskmail'} = '';
 2819:         $bccemails{'otherdomsmail'} = '';
 2820:         $includestr{'helpdeskmail'} = '';
 2821:         $includestr{'otherdomsmail'} = '';
 2822:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 2823:     }
 2824:     if (ref($settings) eq 'HASH') {
 2825:         unless ($position eq 'top') {
 2826:             foreach my $type (@mailings) {
 2827:                 if (exists($settings->{$type})) {
 2828:                     if (ref($settings->{$type}) eq 'HASH') {
 2829:                         foreach my $item (@contacts) {
 2830:                             if ($settings->{$type}{$item}) {
 2831:                                 $checked{$type}{$item} = ' checked="checked" ';
 2832:                             }
 2833:                         }
 2834:                         $otheremails{$type} = $settings->{$type}{'others'};
 2835:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 2836:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 2837:                             if ($settings->{$type}{'include'} ne '') {
 2838:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 2839:                                 $includestr{$type} = &unescape($includestr{$type});
 2840:                             }
 2841:                         }
 2842:                     }
 2843:                 } elsif ($type eq 'lonstatusmail') {
 2844:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 2845:                 }
 2846:             }
 2847:         }
 2848:         if ($position eq 'bottom') {
 2849:             foreach my $type (@mailings) {
 2850:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 2851:                 if ($settings->{$type}{'include'} ne '') {
 2852:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 2853:                     $includestr{$type} = &unescape($includestr{$type});
 2854:                 }
 2855:             }
 2856:             if (ref($settings->{'helpform'}) eq 'HASH') {
 2857:                 if (ref($fields) eq 'ARRAY') {
 2858:                     foreach my $field (@{$fields}) {
 2859:                         $currfield{$field} = $settings->{'helpform'}{$field};
 2860:                     }
 2861:                 }
 2862:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 2863:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 2864:                 } else {
 2865:                     $maxsize = '1.0';
 2866:                 }
 2867:             } else {
 2868:                 if (ref($fields) eq 'ARRAY') {
 2869:                     foreach my $field (@{$fields}) {
 2870:                         $currfield{$field} = 'yes';
 2871:                     }
 2872:                 }
 2873:                 $maxsize = '1.0';
 2874:             }
 2875:         }
 2876:     } else {
 2877:         if ($position eq 'top') {
 2878:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 2879:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 2880:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 2881:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 2882:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 2883:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 2884:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 2885:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 2886:         } elsif ($position eq 'bottom') {
 2887:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 2888:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 2889:             if (ref($fields) eq 'ARRAY') {
 2890:                 foreach my $field (@{$fields}) {
 2891:                     $currfield{$field} = 'yes';
 2892:                 }
 2893:             }
 2894:             $maxsize = '1.0';
 2895:         }
 2896:     }
 2897:     my ($titles,$short_titles) = &contact_titles();
 2898:     my $rownum = 0;
 2899:     my $css_class;
 2900:     if ($position eq 'top') {
 2901:         foreach my $item (@contacts) {
 2902:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 2903:             $datatable .= '<tr'.$css_class.'>'. 
 2904:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 2905:                           '</span></td><td class="LC_right_item">'.
 2906:                           '<input type="text" name="'.$item.'" value="'.
 2907:                           $to{$item}.'" /></td></tr>';
 2908:             $rownum ++;
 2909:         }
 2910:     } else {
 2911:         foreach my $type (@mailings) {
 2912:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 2913:             $datatable .= '<tr'.$css_class.'>'.
 2914:                           '<td><span class="LC_nobreak">'.
 2915:                           $titles->{$type}.': </span></td>'.
 2916:                           '<td class="LC_left_item">';
 2917:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 2918:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 2919:             }
 2920:             $datatable .= '<span class="LC_nobreak">';
 2921:             foreach my $item (@contacts) {
 2922:                 $datatable .= '<label>'.
 2923:                               '<input type="checkbox" name="'.$type.'"'.
 2924:                               $checked{$type}{$item}.
 2925:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 2926:                               '</label>&nbsp;';
 2927:             }
 2928:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 2929:                           '<input type="text" name="'.$type.'_others" '.
 2930:                           'value="'.$otheremails{$type}.'"  />';
 2931:             my %locchecked;
 2932:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 2933:                 foreach my $loc ('s','b') {
 2934:                     if ($includeloc{$type} eq $loc) {
 2935:                         $locchecked{$loc} = ' checked="checked"';
 2936:                         last;
 2937:                     }
 2938:                 }
 2939:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 2940:                               '<input type="text" name="'.$type.'_bcc" '.
 2941:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 2942:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 2943:                               &mt('Text automatically added to e-mail:').' '.
 2944:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br >'.
 2945:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 2946:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 2947:                               ('&nbsp;'x2).
 2948:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 2949:                               '</span></fieldset>';
 2950:             }
 2951:             $datatable .= '</td></tr>'."\n";
 2952:             $rownum ++;
 2953:         }
 2954:     }
 2955:     if ($position eq 'middle') {
 2956:         my %choices;
 2957:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',
 2958:                                        &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 2959:                                        &mt('LON-CAPA core group - MSU'),600,500));
 2960:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 2961:                                         &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 2962:                                         &mt('LON-CAPA core group - MSU'),600,500));
 2963:         my @toggles = ('reporterrors','reportupdates');
 2964:         my %defaultchecked = ('reporterrors'  => 'on',
 2965:                               'reportupdates' => 'on');
 2966:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 2967:                                                    \%choices,$rownum);
 2968:         $datatable .= $reports;
 2969:     } elsif ($position eq 'bottom') {
 2970:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 2971:         $datatable .= '<tr'.$css_class.'>'.
 2972:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 2973:                       &mt('(e-mail, subject, and description always shown)').
 2974:                       '</td><td class="LC_left_item">';
 2975:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 2976:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 2977:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 2978:             foreach my $field (@{$fields}) {
 2979:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 2980:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 2981:                     $datatable .= ' '.&mt('(logged-in users)');
 2982:                 }
 2983:                 $datatable .='</td><td>';
 2984:                 my $clickaction;
 2985:                 if ($field eq 'screenshot') {
 2986:                     $clickaction = ' onclick="screenshotSize(this);"';
 2987:                 }
 2988:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 2989:                     foreach my $option (@{$possoptions->{$field}}) {
 2990:                         my $checked;
 2991:                         if ($currfield{$field} eq $option) {
 2992:                             $checked = ' checked="checked"';
 2993:                         }
 2994:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2995:                                       '<input type="radio" name="helpform_'.$field.'" '.
 2996:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 2997:                                       '</label></span>'.('&nbsp;'x2);
 2998:                     }
 2999:                 }
 3000:                 if ($field eq 'screenshot') {
 3001:                     my $display;
 3002:                     if ($currfield{$field} eq 'no') {
 3003:                         $display = ' style="display:none"';
 3004:                     }
 3005:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.' />'.
 3006:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 3007:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 3008:                 }
 3009:                 $datatable .= '</td></tr>';
 3010:             }
 3011:             $datatable .= '</table>';
 3012:         }
 3013:         $datatable .= '</td></tr>'."\n";
 3014:         $rownum ++;
 3015:     }
 3016:     $$rowtotal += $rownum;
 3017:     return $datatable;
 3018: }
 3019: 
 3020: sub contacts_javascript {
 3021:     return <<"ENDSCRIPT";
 3022: 
 3023: <script type="text/javascript">
 3024: // <![CDATA[
 3025: 
 3026: function screenshotSize(field) {
 3027:     if (document.getElementById('help_screenshotsize')) {
 3028:         if (field.value == 'no') {
 3029:             document.getElementById('help_screenshotsize').style.display="none";
 3030:         } else {
 3031:             document.getElementById('help_screenshotsize').style.display="";
 3032:         }
 3033:     }
 3034:     return;
 3035: }
 3036: 
 3037: // ]]>
 3038: </script>
 3039: 
 3040: ENDSCRIPT
 3041: }
 3042: 
 3043: sub print_helpsettings {
 3044:     my ($position,$dom,$settings,$rowtotal) = @_;
 3045:     my $confname = $dom.'-domainconfig';
 3046:     my $formname = 'display';
 3047:     my ($datatable,$itemcount);
 3048:     if ($position eq 'top') {
 3049:         $itemcount = 1;
 3050:         my (%choices,%defaultchecked,@toggles);
 3051:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 3052:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 3053:                                      &mt('LON-CAPA bug tracker'),600,500));
 3054:         %defaultchecked = ('submitbugs' => 'on');
 3055:         @toggles = ('submitbugs');
 3056:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3057:                                                      \%choices,$itemcount);
 3058:         $$rowtotal ++;
 3059:     } else {
 3060:         my $css_class;
 3061:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 3062:         my (%customroles,%ordered,%current);
 3063:         if (ref($settings->{'adhoc'}) eq 'HASH') {
 3064:             %current = %{$settings->{'adhoc'}};
 3065:         }
 3066:         my $count = 0;
 3067:         foreach my $key (sort(keys(%existing))) {
 3068:             if ($key=~/^rolesdef\_(\w+)$/) {
 3069:                 my $rolename = $1;
 3070:                 my (%privs,$order);
 3071:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 3072:                 $customroles{$rolename} = \%privs;
 3073:                 if (ref($current{$rolename}) eq 'HASH') {
 3074:                     $order = $current{$rolename}{'order'};
 3075:                 }
 3076:                 if ($order eq '') {
 3077:                     $order = $count;
 3078:                 }
 3079:                 $ordered{$order} = $rolename;
 3080:                 $count++;
 3081:             }
 3082:         }
 3083:         my $maxnum = scalar(keys(%ordered));
 3084:         my @roles_by_num = ();
 3085:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3086:             push(@roles_by_num,$item);
 3087:         }
 3088:         my $context = 'domprefs';
 3089:         my $crstype = 'Course';
 3090:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3091:         my @accesstypes = ('all','none');
 3092:         my ($numstatustypes,@jsarray);
 3093:         if (ref($types) eq 'ARRAY') {
 3094:             if (@{$types} > 0) {
 3095:                 $numstatustypes = scalar(@{$types});
 3096:                 push(@accesstypes,'status');
 3097:                 @jsarray = ('bystatus');
 3098:             }
 3099:         }
 3100:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh']);
 3101:         if (keys(%domhelpdesk)) {
 3102:             push(@accesstypes,('inc','exc'));
 3103:             push(@jsarray,('notinc','notexc'));
 3104:         }
 3105:         my $hiddenstr = join("','",@jsarray);
 3106:         $datatable .= &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname);
 3107:         my $context = 'domprefs';
 3108:         my $crstype = 'Course';
 3109:         my $prefix = 'helproles_';
 3110:         my $add_class = 'LC_hidden';
 3111:         foreach my $num (@roles_by_num) {
 3112:             my $role = $ordered{$num};
 3113:             my ($desc,$access,@statuses);
 3114:             if (ref($current{$role}) eq 'HASH') {
 3115:                 $desc = $current{$role}{'desc'};
 3116:                 $access = $current{$role}{'access'};
 3117:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 3118:                     @statuses = @{$current{$role}{'insttypes'}};
 3119:                 }
 3120:             }
 3121:             if ($desc eq '') {
 3122:                 $desc = $role;
 3123:             }
 3124:             my $identifier = 'custhelp'.$num;
 3125:             my %full=();
 3126:             my %levels= (
 3127:                          course => {},
 3128:                          domain => {},
 3129:                          system => {},
 3130:                         );
 3131:             my %levelscurrent=(
 3132:                                course => {},
 3133:                                domain => {},
 3134:                                system => {},
 3135:                               );
 3136:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 3137:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 3138:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3139:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 3140:             $datatable .= '<tr '.$css_class.'><td valign="top"><b>'.$role.'</b><br />'.
 3141:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 3142:             for (my $k=0; $k<=$maxnum; $k++) {
 3143:                 my $vpos = $k+1;
 3144:                 my $selstr;
 3145:                 if ($k == $num) {
 3146:                     $selstr = ' selected="selected" ';
 3147:                 }
 3148:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 3149:             }
 3150:             $datatable .= '</select>'.('&nbsp;'x2).
 3151:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 3152:                           '</td>'.
 3153:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 3154:                           &mt('Name shown to users:').
 3155:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 3156:                           '</fieldset>'.
 3157:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 3158:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 3159:                           '<fieldset>'.
 3160:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 3161:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 3162:                                                                    \%levelscurrent,$identifier,
 3163:                                                                    'LC_hidden',$prefix.$num.'_privs').
 3164:                           '</fieldset></td>';
 3165:             $itemcount ++;
 3166:         }
 3167:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3168:         my $newcust = 'custhelp'.$count;
 3169:         my (%privs,%levelscurrent);
 3170:         my %full=();
 3171:         my %levels= (
 3172:                      course => {},
 3173:                      domain => {},
 3174:                      system => {},
 3175:                     );
 3176:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 3177:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 3178:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 3179:         $datatable .= '<tr '.$css_class.'><td valign="top"><span class="LC_nobreak"><label>'.
 3180:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 3181:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 3182:         for (my $k=0; $k<$maxnum+1; $k++) {
 3183:             my $vpos = $k+1;
 3184:             my $selstr;
 3185:             if ($k == $maxnum) {
 3186:                 $selstr = ' selected="selected" ';
 3187:             }
 3188:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 3189:         }
 3190:         $datatable .= '</select>&nbsp;'."\n".
 3191:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 3192:                       '</label></span></td>'.
 3193:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 3194:                       '<span class="LC_nobreak">'.
 3195:                       &mt('Internal name:').
 3196:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 3197:                       '</span>'.('&nbsp;'x4).
 3198:                       '<span class="LC_nobreak">'.
 3199:                       &mt('Name shown to users:').
 3200:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 3201:                       '</span></fieldset>'.
 3202:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 3203:                                              $usertypes,$types,\%domhelpdesk).
 3204:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 3205:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 3206:                                                                 \@templateroles,$newcust).
 3207:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 3208:                                                                \%levelscurrent,$newcust).
 3209:                       '</fieldset></td></tr>';
 3210:         $count ++;
 3211:         $$rowtotal += $count;
 3212:     }
 3213:     return $datatable;
 3214: }
 3215: 
 3216: sub adhocbutton {
 3217:     my ($prefix,$num,$field,$visibility) = @_;
 3218:     my %lt = &Apache::lonlocal::texthash(
 3219:                                           show => 'Show details',
 3220:                                           hide => 'Hide details',
 3221:                                         );
 3222:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 3223:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 3224:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 3225:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 3226: }
 3227: 
 3228: sub helpsettings_javascript {
 3229:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 3230:     return unless(ref($roles_by_num) eq 'ARRAY');
 3231:     my %html_js_lt = &Apache::lonlocal::texthash(
 3232:                                           show => 'Show details',
 3233:                                           hide => 'Hide details',
 3234:                                         );
 3235:     &html_escape(\%html_js_lt);
 3236:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 3237:     return <<"ENDSCRIPT";
 3238: <script type="text/javascript">
 3239: // <![CDATA[
 3240: 
 3241: function reorderHelpRoles(form,item) {
 3242:     var changedVal;
 3243: $jstext
 3244:     var newpos = 'helproles_${total}_pos';
 3245:     var maxh = 1 + $total;
 3246:     var current = new Array();
 3247:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3248:     if (item == newpos) {
 3249:         changedVal = newitemVal;
 3250:     } else {
 3251:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3252:         current[newitemVal] = newpos;
 3253:     }
 3254:     for (var i=0; i<helproles.length; i++) {
 3255:         var elementName = 'helproles_'+helproles[i]+'_pos';
 3256:         if (elementName != item) {
 3257:             if (form.elements[elementName]) {
 3258:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3259:                 current[currVal] = elementName;
 3260:             }
 3261:         }
 3262:     }
 3263:     var oldVal;
 3264:     for (var j=0; j<maxh; j++) {
 3265:         if (current[j] == undefined) {
 3266:             oldVal = j;
 3267:         }
 3268:     }
 3269:     if (oldVal < changedVal) {
 3270:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3271:            var elementName = current[k];
 3272:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3273:         }
 3274:     } else {
 3275:         for (var k=changedVal; k<oldVal; k++) {
 3276:             var elementName = current[k];
 3277:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3278:         }
 3279:     }
 3280:     return;
 3281: }
 3282: 
 3283: function helpdeskAccess(num) {
 3284:     var curraccess = null;
 3285:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 3286:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 3287:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 3288:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 3289:             }
 3290:         }
 3291:     }
 3292:     var shown = Array();
 3293:     var hidden = Array();
 3294:     if (curraccess == 'none') {
 3295:         hidden = Array('$hiddenstr');
 3296:     } else {
 3297:         if (curraccess == 'status') {
 3298:             shown = Array('bystatus');
 3299:             hidden = Array('notinc','notexc');
 3300:         } else {
 3301:             if (curraccess == 'exc') {
 3302:                 shown = Array('notexc');
 3303:                 hidden = Array('notinc','bystatus');
 3304:             }
 3305:             if (curraccess == 'inc') {
 3306:                 shown = Array('notinc');
 3307:                 hidden = Array('notexc','bystatus');
 3308:             }
 3309:             if (curraccess == 'all') {
 3310:                 hidden = Array('notinc','notexc','bystatus');
 3311:             }
 3312:         }
 3313:     }
 3314:     if (hidden.length > 0) {
 3315:         for (var i=0; i<hidden.length; i++) {
 3316:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 3317:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 3318:             }
 3319:         }
 3320:     }
 3321:     if (shown.length > 0) {
 3322:         for (var i=0; i<shown.length; i++) {
 3323:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 3324:                 if (shown[i] == 'privs') {
 3325:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 3326:                 } else {
 3327:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 3328:                 }
 3329:             }
 3330:         }
 3331:     }
 3332:     return;
 3333: }
 3334: 
 3335: function toggleHelpdeskItem(num,field) {
 3336:     if (document.getElementById('helproles_'+num+'_'+field)) {
 3337:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 3338:             document.getElementById('helproles_'+num+'_'+field).className =
 3339:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 3340:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 3341:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 3342:             }
 3343:         } else {
 3344:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 3345:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 3346:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 3347:             }
 3348:         }
 3349:     }
 3350:     return;
 3351: }
 3352: 
 3353: // ]]>
 3354: </script>
 3355: 
 3356: ENDSCRIPT
 3357: }
 3358: 
 3359: sub helpdeskroles_access {
 3360:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 3361:         $usertypes,$types,$domhelpdesk) = @_;
 3362:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 3363:     my %lt = &Apache::lonlocal::texthash(
 3364:                     'rou'    => 'Role usage',
 3365:                     'whi'    => 'Which helpdesk personnel may use this role?',
 3366:                     'all'    => 'All',
 3367:                     'none'   => 'None',
 3368:                     'status' => 'Determined based on institutional status',
 3369:                     'inc'    => 'Include all, but exclude specific personnel',
 3370:                     'exc'    => 'Exclude all, but include specific personnel',
 3371:                   );
 3372:     my %usecheck = (
 3373:                      all => ' checked="checked"',
 3374:                    );
 3375:     my %displaydiv = (
 3376:                       status => 'none',
 3377:                       inc    => 'none',
 3378:                       exc    => 'none',
 3379:                       priv   => 'block',
 3380:                      );
 3381:     my $output;
 3382:     if (ref($current) eq 'HASH') {
 3383:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 3384:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 3385:                 $usecheck{$current->{access}} = $usecheck{'all'};
 3386:                 delete($usecheck{'all'});
 3387:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 3388:                     my $access = $1;
 3389:                     $displaydiv{$access} = 'inline';
 3390:                 } elsif ($current->{access} eq 'none') {
 3391:                     $displaydiv{'priv'} = 'none';
 3392:                 }
 3393:             }
 3394:         }
 3395:     }
 3396:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 3397:               '<p>'.$lt{'whi'}.'</p>';
 3398:     foreach my $access (@{$accesstypes}) {
 3399:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 3400:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 3401:                    $lt{$access}.'</label>';
 3402:         if ($access eq 'status') {
 3403:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 3404:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 3405:                                                                  $othertitle,$usertypes,$types).
 3406:                        '</div>';
 3407:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 3408:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 3409:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 3410:                        '</div>';
 3411:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 3412:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 3413:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 3414:                        '</div>';
 3415:         }
 3416:         $output .= '</p>';
 3417:     }
 3418:     $output .= '</fieldset>';
 3419:     return $output;
 3420: }
 3421: 
 3422: sub radiobutton_prefs {
 3423:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 3424:         $additional,$align) = @_;
 3425:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 3426:                    (ref($choices) eq 'HASH'));
 3427: 
 3428:     my (%checkedon,%checkedoff,$datatable,$css_class);
 3429: 
 3430:     foreach my $item (@{$toggles}) {
 3431:         if ($defaultchecked->{$item} eq 'on') {
 3432:             $checkedon{$item} = ' checked="checked" ';
 3433:             $checkedoff{$item} = ' ';
 3434:         } elsif ($defaultchecked->{$item} eq 'off') {
 3435:             $checkedoff{$item} = ' checked="checked" ';
 3436:             $checkedon{$item} = ' ';
 3437:         }
 3438:     }
 3439:     if (ref($settings) eq 'HASH') {
 3440:         foreach my $item (@{$toggles}) {
 3441:             if ($settings->{$item} eq '1') {
 3442:                 $checkedon{$item} =  ' checked="checked" ';
 3443:                 $checkedoff{$item} = ' ';
 3444:             } elsif ($settings->{$item} eq '0') {
 3445:                 $checkedoff{$item} =  ' checked="checked" ';
 3446:                 $checkedon{$item} = ' ';
 3447:             }
 3448:         }
 3449:     }
 3450:     if ($onclick) {
 3451:         $onclick = ' onclick="'.$onclick.'"';
 3452:     }
 3453:     foreach my $item (@{$toggles}) {
 3454:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3455:         $datatable .=
 3456:             '<tr'.$css_class.'><td valign="top">'.
 3457:             '<span class="LC_nobreak">'.$choices->{$item}.
 3458:             '</span></td>';
 3459:         if ($align eq 'left') {
 3460:             $datatable .= '<td class="LC_left_item">';
 3461:         } else {
 3462:             $datatable .= '<td class="LC_right_item">';
 3463:         }
 3464:         $datatable .=
 3465:             '<span class="LC_nobreak">'.
 3466:             '<label><input type="radio" name="'.
 3467:             $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 3468:             '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 3469:             $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>'.
 3470:             '</span>'.$additional.
 3471:             '</td>'.
 3472:             '</tr>';
 3473:         $itemcount ++;
 3474:     }
 3475:     return ($datatable,$itemcount);
 3476: }
 3477: 
 3478: sub print_coursedefaults {
 3479:     my ($position,$dom,$settings,$rowtotal) = @_;
 3480:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 3481:     my $itemcount = 1;
 3482:     my %choices =  &Apache::lonlocal::texthash (
 3483:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 3484:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 3485:         coursecredits        => 'Credits can be specified for courses',
 3486:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 3487:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 3488:         postsubmit           => 'Disable submit button/keypress following student submission',
 3489:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 3490:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 3491:     );
 3492:     my %staticdefaults = (
 3493:                            anonsurvey_threshold => 10,
 3494:                            uploadquota          => 500,
 3495:                            postsubmit           => 60,
 3496:                            mysqltables          => 172800,
 3497:                          );
 3498:     if ($position eq 'top') {
 3499:         %defaultchecked = (
 3500:                             'uselcmath'       => 'on',
 3501:                             'usejsme'         => 'on',
 3502:                             'canclone'        => 'none',
 3503:                           );
 3504:         @toggles = ('uselcmath','usejsme');
 3505:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3506:                                                      \%choices,$itemcount);
 3507:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3508:         $datatable .=
 3509:             '<tr'.$css_class.'><td valign="top">'.
 3510:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 3511:             '</span></td><td class="LC_left_item">';
 3512:         my $currcanclone = 'none';
 3513:         my $onclick;
 3514:         my @cloneoptions = ('none','domain');
 3515:         my %clonetitles = (
 3516:                              none     => 'No additional course requesters',
 3517:                              domain   => "Any course requester in course's domain",
 3518:                              instcode => 'Course requests for official courses ...',
 3519:                           );
 3520:         my (%codedefaults,@code_order,@posscodes);
 3521:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 3522:                                                     \@code_order) eq 'ok') {
 3523:             if (@code_order > 0) {
 3524:                 push(@cloneoptions,'instcode');
 3525:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 3526:             }
 3527:         }
 3528:         if (ref($settings) eq 'HASH') {
 3529:             if ($settings->{'canclone'}) {
 3530:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 3531:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 3532:                         if (@code_order > 0) {
 3533:                             $currcanclone = 'instcode';
 3534:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 3535:                         }
 3536:                     }
 3537:                 } elsif ($settings->{'canclone'} eq 'domain') {
 3538:                     $currcanclone = $settings->{'canclone'};
 3539:                 }
 3540:             }
 3541:         }
 3542:         foreach my $option (@cloneoptions) {
 3543:             my ($checked,$additional);
 3544:             if ($currcanclone eq $option) {
 3545:                 $checked = ' checked="checked"';
 3546:             }
 3547:             if ($option eq 'instcode') {
 3548:                 if (@code_order) {
 3549:                     my $show = 'none';
 3550:                     if ($checked) {
 3551:                         $show = 'block';
 3552:                     }
 3553:                     $additional = '<div id="cloneinstcode" style="display:'.$show.'" />'.
 3554:                                   &mt('Institutional codes for new and cloned course have identical:').
 3555:                                   '<br />';
 3556:                     foreach my $item (@code_order) {
 3557:                         my $codechk;
 3558:                         if ($checked) {
 3559:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 3560:                                 $codechk = ' checked="checked"';
 3561:                             }
 3562:                         }
 3563:                         $additional .= '<label>'.
 3564:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 3565:                                        $item.'</label>';
 3566:                     }
 3567:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 3568:                 }
 3569:             }
 3570:             $datatable .=
 3571:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 3572:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 3573:                 '</label>&nbsp;'.$additional.'</span><br />';
 3574:         }
 3575:         $datatable .= '</td>'.
 3576:                       '</tr>';
 3577:         $itemcount ++;
 3578:     } else {
 3579:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3580:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 3581:         my $currusecredits = 0;
 3582:         my $postsubmitclient = 1;
 3583:         my @types = ('official','unofficial','community','textbook');
 3584:         if (ref($settings) eq 'HASH') {
 3585:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 3586:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 3587:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 3588:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 3589:                 }
 3590:             }
 3591:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 3592:                 foreach my $type (@types) {
 3593:                     next if ($type eq 'community');
 3594:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 3595:                     if ($defcredits{$type} ne '') {
 3596:                         $currusecredits = 1;
 3597:                     }
 3598:                 }
 3599:             }
 3600:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 3601:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 3602:                     $postsubmitclient = 0;
 3603:                     foreach my $type (@types) {
 3604:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3605:                     }
 3606:                 } else {
 3607:                     foreach my $type (@types) {
 3608:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 3609:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 3610:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 3611:                             } else {
 3612:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3613:                             }
 3614:                         } else {
 3615:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3616:                         }
 3617:                     }
 3618:                 }
 3619:             } else {
 3620:                 foreach my $type (@types) {
 3621:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3622:                 }
 3623:             }
 3624:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 3625:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 3626:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 3627:                 }
 3628:             } else {
 3629:                 foreach my $type (@types) {
 3630:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 3631:                 }
 3632:             }
 3633:         } else {
 3634:             foreach my $type (@types) {
 3635:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3636:             }
 3637:         }
 3638:         if (!$currdefresponder) {
 3639:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 3640:         } elsif ($currdefresponder < 1) {
 3641:             $currdefresponder = 1;
 3642:         }
 3643:         foreach my $type (@types) {
 3644:             if ($curruploadquota{$type} eq '') {
 3645:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 3646:             }
 3647:         }
 3648:         $datatable .=
 3649:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 3650:                 $choices{'anonsurvey_threshold'}.
 3651:                 '</span></td>'.
 3652:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 3653:                 '<input type="text" name="anonsurvey_threshold"'.
 3654:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 3655:                 '</td></tr>'."\n";
 3656:         $itemcount ++;
 3657:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3658:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 3659:                       $choices{'uploadquota'}.
 3660:                       '</span></td>'.
 3661:                       '<td align="right" class="LC_right_item">'.
 3662:                       '<table><tr>';
 3663:         foreach my $type (@types) {
 3664:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 3665:                            '<input type="text" name="uploadquota_'.$type.'"'.
 3666:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 3667:         }
 3668:         $datatable .= '</tr></table></td></tr>'."\n";
 3669:         $itemcount ++;
 3670:         my $onclick = "toggleDisplay(this.form,'credits');";
 3671:         my $display = 'none';
 3672:         if ($currusecredits) {
 3673:             $display = 'block';
 3674:         }
 3675:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 3676:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 3677:         foreach my $type (@types) {
 3678:             next if ($type eq 'community');
 3679:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 3680:                            '<input type="text" name="'.$type.'_credits"'.
 3681:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 3682:         }
 3683:         $additional .= '</tr></table></div>'."\n";
 3684:         %defaultchecked = ('coursecredits' => 'off');
 3685:         @toggles = ('coursecredits');
 3686:         my $current = {
 3687:                         'coursecredits' => $currusecredits,
 3688:                       };
 3689:         (my $table,$itemcount) =
 3690:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 3691:                                \%choices,$itemcount,$onclick,$additional,'left');
 3692:         $datatable .= $table;
 3693:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 3694:         my $display = 'none';
 3695:         if ($postsubmitclient) {
 3696:             $display = 'block';
 3697:         }
 3698:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 3699:                       &mt('Number of seconds submit is disabled').'<br />'.
 3700:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 3701:                       '<table><tr>';
 3702:         foreach my $type (@types) {
 3703:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 3704:                            '<input type="text" name="'.$type.'_timeout" value="'.
 3705:                            $deftimeout{$type}.'" size="5" /></td>';
 3706:         }
 3707:         $additional .= '</tr></table></div>'."\n";
 3708:         %defaultchecked = ('postsubmit' => 'on');
 3709:         @toggles = ('postsubmit');
 3710:         $current = {
 3711:                        'postsubmit' => $postsubmitclient,
 3712:                    };
 3713:         ($table,$itemcount) =
 3714:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 3715:                                \%choices,$itemcount,$onclick,$additional,'left');
 3716:         $datatable .= $table;
 3717:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3718:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 3719:                       $choices{'mysqltables'}.
 3720:                       '</span></td>'.
 3721:                       '<td align="right" class="LC_right_item">'.
 3722:                       '<table><tr>';
 3723:         foreach my $type (@types) {
 3724:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 3725:                            '<input type="text" name="mysqltables_'.$type.'"'.
 3726:                            ' value="'.$currmysql{$type}.'" size="5" /></td>';
 3727:         }
 3728:         $datatable .= '</tr></table></td></tr>'."\n";
 3729:         $itemcount ++;
 3730: 
 3731:     }
 3732:     $$rowtotal += $itemcount;
 3733:     return $datatable;
 3734: }
 3735: 
 3736: sub print_selfenrollment {
 3737:     my ($position,$dom,$settings,$rowtotal) = @_;
 3738:     my ($css_class,$datatable);
 3739:     my $itemcount = 1;
 3740:     my @types = ('official','unofficial','community','textbook');
 3741:     if (($position eq 'top') || ($position eq 'middle')) {
 3742:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 3743:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 3744:         my @rows;
 3745:         my $key;
 3746:         if ($position eq 'top') {
 3747:             $key = 'admin'; 
 3748:             if (ref($rowsref) eq 'ARRAY') {
 3749:                 @rows = @{$rowsref};
 3750:             }
 3751:         } elsif ($position eq 'middle') {
 3752:             $key = 'default';
 3753:             @rows = ('types','registered','approval','limit');
 3754:         }
 3755:         foreach my $row (@rows) {
 3756:             if (defined($titlesref->{$row})) {
 3757:                 $itemcount ++;
 3758:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3759:                 $datatable .= '<tr'.$css_class.'>'.
 3760:                               '<td>'.$titlesref->{$row}.'</td>'.
 3761:                               '<td class="LC_left_item">'.
 3762:                               '<table><tr>';
 3763:                 my (%current,%currentcap);
 3764:                 if (ref($settings) eq 'HASH') {
 3765:                     if (ref($settings->{$key}) eq 'HASH') {
 3766:                         foreach my $type (@types) {
 3767:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 3768:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 3769:                             }
 3770:                             if (($row eq 'limit') && ($key eq 'default')) {
 3771:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 3772:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 3773:                                 }
 3774:                             }
 3775:                         }
 3776:                     }
 3777:                 }
 3778:                 my %roles = (
 3779:                              '0' => &Apache::lonnet::plaintext('dc'),
 3780:                             ); 
 3781:             
 3782:                 foreach my $type (@types) {
 3783:                     unless (($row eq 'registered') && ($key eq 'default')) {
 3784:                         $datatable .= '<th>'.&mt($type).'</th>';
 3785:                     }
 3786:                 }
 3787:                 unless (($row eq 'registered') && ($key eq 'default')) {
 3788:                     $datatable .= '</tr><tr>';
 3789:                 }
 3790:                 foreach my $type (@types) {
 3791:                     if ($type eq 'community') {
 3792:                         $roles{'1'} = &mt('Community personnel');
 3793:                     } else {
 3794:                         $roles{'1'} = &mt('Course personnel');
 3795:                     }
 3796:                     $datatable .= '<td style="vertical-align: top">';
 3797:                     if ($position eq 'top') {
 3798:                         my %checked;
 3799:                         if ($current{$type} eq '0') {
 3800:                             $checked{'0'} = ' checked="checked"';
 3801:                         } else {
 3802:                             $checked{'1'} = ' checked="checked"';
 3803:                         }
 3804:                         foreach my $role ('1','0') {
 3805:                             $datatable .= '<span class="LC_nobreak"><label>'.
 3806:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 3807:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 3808:                                           $roles{$role}.'</label></span> ';
 3809:                         }
 3810:                     } else {
 3811:                         if ($row eq 'types') {
 3812:                             my %checked;
 3813:                             if ($current{$type} =~ /^(all|dom)$/) {
 3814:                                 $checked{$1} = ' checked="checked"';
 3815:                             } else {
 3816:                                 $checked{''} = ' checked="checked"';
 3817:                             }
 3818:                             foreach my $val ('','dom','all') {
 3819:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 3820:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 3821:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 3822:                             }
 3823:                         } elsif ($row eq 'registered') {
 3824:                             my %checked;
 3825:                             if ($current{$type} eq '1') {
 3826:                                 $checked{'1'} = ' checked="checked"';
 3827:                             } else {
 3828:                                 $checked{'0'} = ' checked="checked"';
 3829:                             }
 3830:                             foreach my $val ('0','1') {
 3831:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 3832:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 3833:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 3834:                             }
 3835:                         } elsif ($row eq 'approval') {
 3836:                             my %checked;
 3837:                             if ($current{$type} =~ /^([12])$/) {
 3838:                                 $checked{$1} = ' checked="checked"';
 3839:                             } else {
 3840:                                 $checked{'0'} = ' checked="checked"';
 3841:                             }
 3842:                             for my $val (0..2) {
 3843:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 3844:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 3845:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 3846:                             }
 3847:                         } elsif ($row eq 'limit') {
 3848:                             my %checked;
 3849:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 3850:                                 $checked{$1} = ' checked="checked"';
 3851:                             } else {
 3852:                                 $checked{'none'} = ' checked="checked"';
 3853:                             }
 3854:                             my $cap;
 3855:                             if ($currentcap{$type} =~ /^\d+$/) {
 3856:                                 $cap = $currentcap{$type};
 3857:                             }
 3858:                             foreach my $val ('none','allstudents','selfenrolled') {
 3859:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 3860:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 3861:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 3862:                             }
 3863:                             $datatable .= '<br />'.
 3864:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 3865:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 3866:                                           '</span>'; 
 3867:                         }
 3868:                     }
 3869:                     $datatable .= '</td>';
 3870:                 }
 3871:                 $datatable .= '</tr>';
 3872:             }
 3873:             $datatable .= '</table></td></tr>';
 3874:         }
 3875:     } elsif ($position eq 'bottom') {
 3876:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 3877:     }
 3878:     $$rowtotal += $itemcount;
 3879:     return $datatable;
 3880: }
 3881: 
 3882: sub print_validation_rows {
 3883:     my ($caller,$dom,$settings,$rowtotal) = @_;
 3884:     my ($itemsref,$namesref,$fieldsref);
 3885:     if ($caller eq 'selfenroll') { 
 3886:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 3887:     } elsif ($caller eq 'requestcourses') {
 3888:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 3889:     }
 3890:     my %currvalidation;
 3891:     if (ref($settings) eq 'HASH') {
 3892:         if (ref($settings->{'validation'}) eq 'HASH') {
 3893:             %currvalidation = %{$settings->{'validation'}};
 3894:         }
 3895:     }
 3896:     my $datatable;
 3897:     my $itemcount = 0;
 3898:     foreach my $item (@{$itemsref}) {
 3899:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3900:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 3901:                       $namesref->{$item}.
 3902:                       '</span></td>'.
 3903:                       '<td class="LC_left_item">';
 3904:         if (($item eq 'url') || ($item eq 'button')) {
 3905:             $datatable .= '<span class="LC_nobreak">'.
 3906:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 3907:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 3908:         } elsif ($item eq 'fields') {
 3909:             my @currfields;
 3910:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 3911:                 @currfields = @{$currvalidation{$item}};
 3912:             }
 3913:             foreach my $field (@{$fieldsref}) {
 3914:                 my $check = '';
 3915:                 if (grep(/^\Q$field\E$/,@currfields)) {
 3916:                     $check = ' checked="checked"';
 3917:                 }
 3918:                 $datatable .= '<span class="LC_nobreak"><label>'.
 3919:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 3920:                               ' value="'.$field.'"'.$check.' />'.$field.
 3921:                               '</label></span> ';
 3922:             }
 3923:         } elsif ($item eq 'markup') {
 3924:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5" wrap="soft">'.
 3925:                            $currvalidation{$item}.
 3926:                               '</textarea>';
 3927:         }
 3928:         $datatable .= '</td></tr>'."\n";
 3929:         if (ref($rowtotal)) {
 3930:             $itemcount ++;
 3931:         }
 3932:     }
 3933:     if ($caller eq 'requestcourses') {
 3934:         my %currhash;
 3935:         if (ref($settings) eq 'HASH') {
 3936:             if (ref($settings->{'validation'}) eq 'HASH') {
 3937:                 if ($settings->{'validation'}{'dc'} ne '') {
 3938:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 3939:                 }
 3940:             }
 3941:         }
 3942:         my $numinrow = 2;
 3943:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 3944:                                                        'validationdc',%currhash);
 3945:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3946:         $datatable .= '</td></tr><tr'.$css_class.'><td>';
 3947:         if ($numdc > 1) {
 3948:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 3949:         } else {
 3950:             $datatable .=  &mt('Course creation processed as: ');
 3951:         }
 3952:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 3953:         $itemcount ++;
 3954:     }
 3955:     if (ref($rowtotal)) {
 3956:         $$rowtotal += $itemcount;
 3957:     }
 3958:     return $datatable;
 3959: }
 3960: 
 3961: sub print_usersessions {
 3962:     my ($position,$dom,$settings,$rowtotal) = @_;
 3963:     my ($css_class,$datatable,%checked,%choices);
 3964:     my (%by_ip,%by_location,@intdoms);
 3965:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
 3966: 
 3967:     my @alldoms = &Apache::lonnet::all_domains();
 3968:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 3969:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 3970:     my %altids = &id_for_thisdom(%servers);
 3971:     my $itemcount = 1;
 3972:     if ($position eq 'top') {
 3973:         if (keys(%serverhomes) > 1) {
 3974:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 3975:             my $curroffloadnow;
 3976:             if (ref($settings) eq 'HASH') {
 3977:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 3978:                     $curroffloadnow = $settings->{'offloadnow'};
 3979:                 }
 3980:             }
 3981:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,$curroffloadnow,$rowtotal);
 3982:         } else {
 3983:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 3984:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.');
 3985:         }
 3986:     } else {
 3987:         if (keys(%by_location) == 0) {
 3988:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 3989:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.');
 3990:         } else {
 3991:             my %lt = &usersession_titles();
 3992:             my $numinrow = 5;
 3993:             my $prefix;
 3994:             my @types;
 3995:             if ($position eq 'bottom') {
 3996:                 $prefix = 'remote';
 3997:                 @types = ('version','excludedomain','includedomain');
 3998:             } else {
 3999:                 $prefix = 'hosted';
 4000:                 @types = ('excludedomain','includedomain');
 4001:             }
 4002:             my (%current,%checkedon,%checkedoff);
 4003:             my @lcversions = &Apache::lonnet::all_loncaparevs();
 4004:             my @locations = sort(keys(%by_location));
 4005:             foreach my $type (@types) {
 4006:                 $checkedon{$type} = '';
 4007:                 $checkedoff{$type} = ' checked="checked"';
 4008:             }
 4009:             if (ref($settings) eq 'HASH') {
 4010:                 if (ref($settings->{$prefix}) eq 'HASH') {
 4011:                     foreach my $key (keys(%{$settings->{$prefix}})) {
 4012:                         $current{$key} = $settings->{$prefix}{$key};
 4013:                         if ($key eq 'version') {
 4014:                             if ($current{$key} ne '') {
 4015:                                 $checkedon{$key} = ' checked="checked"';
 4016:                                 $checkedoff{$key} = '';
 4017:                             }
 4018:                         } elsif (ref($current{$key}) eq 'ARRAY') {
 4019:                             $checkedon{$key} = ' checked="checked"';
 4020:                             $checkedoff{$key} = '';
 4021:                         }
 4022:                     }
 4023:                 }
 4024:             }
 4025:             foreach my $type (@types) {
 4026:                 next if ($type ne 'version' && !@locations);
 4027:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4028:                 $datatable .= '<tr'.$css_class.'>
 4029:                                <td><span class="LC_nobreak">'.$lt{$type}.'</span><br />
 4030:                                <span class="LC_nobreak">&nbsp;
 4031:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 4032:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 4033:                 if ($type eq 'version') {
 4034:                     my $selector = '<select name="'.$prefix.'_version">';
 4035:                     foreach my $version (@lcversions) {
 4036:                         my $selected = '';
 4037:                         if ($current{'version'} eq $version) {
 4038:                             $selected = ' selected="selected"';
 4039:                         }
 4040:                         $selector .= ' <option value="'.$version.'"'.
 4041:                                      $selected.'>'.$version.'</option>';
 4042:                     }
 4043:                     $selector .= '</select> ';
 4044:                     $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 4045:                 } else {
 4046:                     $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 4047:                                  'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 4048:                                  ' />'.('&nbsp;'x2).
 4049:                                  '<input type="button" value="'.&mt('uncheck all').'" '.
 4050:                                  'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 4051:                                  "\n".
 4052:                                  '</div><div><table>';
 4053:                     my $rem;
 4054:                     for (my $i=0; $i<@locations; $i++) {
 4055:                         my ($showloc,$value,$checkedtype);
 4056:                         if (ref($by_location{$locations[$i]}) eq 'ARRAY') {
 4057:                             my $ip = $by_location{$locations[$i]}->[0];
 4058:                             if (ref($by_ip{$ip}) eq 'ARRAY') {
 4059:                                  $value = join(':',@{$by_ip{$ip}});
 4060:                                 $showloc = join(', ',@{$by_ip{$ip}});
 4061:                                 if (ref($current{$type}) eq 'ARRAY') {
 4062:                                     foreach my $loc (@{$by_ip{$ip}}) {  
 4063:                                         if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 4064:                                             $checkedtype = ' checked="checked"';
 4065:                                             last;
 4066:                                         }
 4067:                                     }
 4068:                                 }
 4069:                             }
 4070:                         }
 4071:                         $rem = $i%($numinrow);
 4072:                         if ($rem == 0) {
 4073:                             if ($i > 0) {
 4074:                                 $datatable .= '</tr>';
 4075:                             }
 4076:                             $datatable .= '<tr>';
 4077:                         }
 4078:                         $datatable .= '<td class="LC_left_item">'.
 4079:                                       '<span class="LC_nobreak"><label>'.
 4080:                                       '<input type="checkbox" name="'.$prefix.'_'.$type.
 4081:                                       '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 4082:                                       '</label></span></td>';
 4083:                     }
 4084:                     $rem = @locations%($numinrow);
 4085:                     my $colsleft = $numinrow - $rem;
 4086:                     if ($colsleft > 1 ) {
 4087:                         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4088:                                       '&nbsp;</td>';
 4089:                     } elsif ($colsleft == 1) {
 4090:                         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 4091:                     }
 4092:                     $datatable .= '</tr></table>';
 4093:                 }
 4094:                 $datatable .= '</td></tr>';
 4095:                 $itemcount ++;
 4096:             }
 4097:         }
 4098:     }
 4099:     $$rowtotal += $itemcount;
 4100:     return $datatable;
 4101: }
 4102: 
 4103: sub build_location_hashes {
 4104:     my ($intdoms,$by_ip,$by_location) = @_;
 4105:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 4106:                   (ref($by_location) eq 'HASH')); 
 4107:     my %iphost = &Apache::lonnet::get_iphost();
 4108:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 4109:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 4110:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 4111:         foreach my $id (@{$iphost{$primary_ip}}) {
 4112:             my $intdom = &Apache::lonnet::internet_dom($id);
 4113:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 4114:                 push(@{$intdoms},$intdom);
 4115:             }
 4116:         }
 4117:     }
 4118:     foreach my $ip (keys(%iphost)) {
 4119:         if (ref($iphost{$ip}) eq 'ARRAY') {
 4120:             foreach my $id (@{$iphost{$ip}}) {
 4121:                 my $location = &Apache::lonnet::internet_dom($id);
 4122:                 if ($location) {
 4123:                     next if (grep(/^\Q$location\E$/,@{$intdoms}));
 4124:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 4125:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 4126:                             push(@{$by_ip->{$ip}},$location);
 4127:                         }
 4128:                     } else {
 4129:                         $by_ip->{$ip} = [$location];
 4130:                     }
 4131:                 }
 4132:             }
 4133:         }
 4134:     }
 4135:     foreach my $ip (sort(keys(%{$by_ip}))) {
 4136:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 4137:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 4138:             my $first = $by_ip->{$ip}->[0];
 4139:             if (ref($by_location->{$first}) eq 'ARRAY') {
 4140:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 4141:                     push(@{$by_location->{$first}},$ip);
 4142:                 }
 4143:             } else {
 4144:                 $by_location->{$first} = [$ip];
 4145:             }
 4146:         }
 4147:     }
 4148:     return;
 4149: }
 4150: 
 4151: sub current_offloads_to {
 4152:     my ($dom,$settings,$servers) = @_;
 4153:     my (%spareid,%otherdomconfigs);
 4154:     if (ref($servers) eq 'HASH') {
 4155:         foreach my $lonhost (sort(keys(%{$servers}))) {
 4156:             my $gotspares;
 4157:             if (ref($settings) eq 'HASH') {
 4158:                 if (ref($settings->{'spares'}) eq 'HASH') {
 4159:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 4160:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 4161:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 4162:                         $gotspares = 1;
 4163:                     }
 4164:                 }
 4165:             }
 4166:             unless ($gotspares) {
 4167:                 my $gotspares;
 4168:                 my $serverhomeID =
 4169:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 4170:                 my $serverhomedom =
 4171:                     &Apache::lonnet::host_domain($serverhomeID);
 4172:                 if ($serverhomedom ne $dom) {
 4173:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 4174:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 4175:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 4176:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 4177:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 4178:                                 $gotspares = 1;
 4179:                             }
 4180:                         }
 4181:                     } else {
 4182:                         $otherdomconfigs{$serverhomedom} =
 4183:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 4184:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 4185:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 4186:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 4187:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 4188:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 4189:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 4190:                                         $gotspares = 1;
 4191:                                     }
 4192:                                 }
 4193:                             }
 4194:                         }
 4195:                     }
 4196:                 }
 4197:             }
 4198:             unless ($gotspares) {
 4199:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 4200:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 4201:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 4202:                } else {
 4203:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 4204:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 4205:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 4206:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 4207:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 4208:                     } else {
 4209:                         my %what = (
 4210:                              spareid => 1,
 4211:                         );
 4212:                         my ($result,$returnhash) = 
 4213:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 4214:                         if ($result eq 'ok') { 
 4215:                             if (ref($returnhash) eq 'HASH') {
 4216:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 4217:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 4218:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 4219:                                 }
 4220:                             }
 4221:                         }
 4222:                     }
 4223:                 }
 4224:             }
 4225:         }
 4226:     }
 4227:     return %spareid;
 4228: }
 4229: 
 4230: sub spares_row {
 4231:     my ($dom,$servers,$spareid,$serverhomes,$altids,$curroffloadnow,$rowtotal) = @_;
 4232:     my $css_class;
 4233:     my $numinrow = 4;
 4234:     my $itemcount = 1;
 4235:     my $datatable;
 4236:     my %typetitles = &sparestype_titles();
 4237:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 4238:         foreach my $server (sort(keys(%{$servers}))) {
 4239:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 4240:             my ($othercontrol,$serverdom);
 4241:             if ($serverhome ne $server) {
 4242:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 4243:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 4244:             } else {
 4245:                 $serverdom = &Apache::lonnet::host_domain($server);
 4246:                 if ($serverdom ne $dom) {
 4247:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 4248:                 }
 4249:             }
 4250:             next unless (ref($spareid->{$server}) eq 'HASH');
 4251:             my $checkednow;
 4252:             if (ref($curroffloadnow) eq 'HASH') {
 4253:                 if ($curroffloadnow->{$server}) {
 4254:                     $checkednow = ' checked="checked"';
 4255:                 }
 4256:             }
 4257:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4258:             $datatable .= '<tr'.$css_class.'>
 4259:                            <td rowspan="2">
 4260:                             <span class="LC_nobreak">'.
 4261:                           &mt('[_1] when busy, offloads to:'
 4262:                               ,'<b>'.$server.'</b>').'</span><br />'.
 4263:                           '<span class="LC_nobreak">'."\n".
 4264:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 4265:                           '&nbsp;'.&mt('Switch active users on next access').'</label></span>'.
 4266:                           "\n";
 4267:             my (%current,%canselect);
 4268:             my @choices = 
 4269:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 4270:             foreach my $type ('primary','default') {
 4271:                 if (ref($spareid->{$server}) eq 'HASH') {
 4272:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 4273:                         my @spares = @{$spareid->{$server}{$type}};
 4274:                         if (@spares > 0) {
 4275:                             if ($othercontrol) {
 4276:                                 $current{$type} = join(', ',@spares);
 4277:                             } else {
 4278:                                 $current{$type} .= '<table>';
 4279:                                 my $numspares = scalar(@spares);
 4280:                                 for (my $i=0;  $i<@spares; $i++) {
 4281:                                     my $rem = $i%($numinrow);
 4282:                                     if ($rem == 0) {
 4283:                                         if ($i > 0) {
 4284:                                             $current{$type} .= '</tr>';
 4285:                                         }
 4286:                                         $current{$type} .= '<tr>';
 4287:                                     }
 4288:                                     $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;'.
 4289:                                                        $spareid->{$server}{$type}[$i].
 4290:                                                        '</label></td>'."\n";
 4291:                                 }
 4292:                                 my $rem = @spares%($numinrow);
 4293:                                 my $colsleft = $numinrow - $rem;
 4294:                                 if ($colsleft > 1 ) {
 4295:                                     $current{$type} .= '<td colspan="'.$colsleft.
 4296:                                                        '" class="LC_left_item">'.
 4297:                                                        '&nbsp;</td>';
 4298:                                 } elsif ($colsleft == 1) {
 4299:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 4300:                                 }
 4301:                                 $current{$type} .= '</tr></table>';
 4302:                             }
 4303:                         }
 4304:                     }
 4305:                     if ($current{$type} eq '') {
 4306:                         $current{$type} = &mt('None specified');
 4307:                     }
 4308:                     if ($othercontrol) {
 4309:                         if ($type eq 'primary') {
 4310:                             $canselect{$type} = $othercontrol;
 4311:                         }
 4312:                     } else {
 4313:                         $canselect{$type} = 
 4314:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 4315:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 4316:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 4317:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 4318:                         if (@choices > 0) {
 4319:                             foreach my $lonhost (@choices) {
 4320:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 4321:                             }
 4322:                         }
 4323:                         $canselect{$type} .= '</select>'."\n";
 4324:                     }
 4325:                 } else {
 4326:                     $current{$type} = &mt('Could not be determined');
 4327:                     if ($type eq 'primary') {
 4328:                         $canselect{$type} =  $othercontrol;
 4329:                     }
 4330:                 }
 4331:                 if ($type eq 'default') {
 4332:                     $datatable .= '<tr'.$css_class.'>';
 4333:                 }
 4334:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 4335:                               '<td>'.$current{$type}.'</td>'."\n".
 4336:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 4337:             }
 4338:             $itemcount ++;
 4339:         }
 4340:     }
 4341:     $$rowtotal += $itemcount;
 4342:     return $datatable;
 4343: }
 4344: 
 4345: sub possible_newspares {
 4346:     my ($server,$currspares,$serverhomes,$altids) = @_;
 4347:     my $serverhostname = &Apache::lonnet::hostname($server);
 4348:     my %excluded;
 4349:     if ($serverhostname ne '') {
 4350:         %excluded = (
 4351:                        $serverhostname => 1,
 4352:                     );
 4353:     }
 4354:     if (ref($currspares) eq 'HASH') {
 4355:         foreach my $type (keys(%{$currspares})) {
 4356:             if (ref($currspares->{$type}) eq 'ARRAY') {
 4357:                 if (@{$currspares->{$type}} > 0) {
 4358:                     foreach my $curr (@{$currspares->{$type}}) {
 4359:                         my $hostname = &Apache::lonnet::hostname($curr);
 4360:                         $excluded{$hostname} = 1;
 4361:                     }
 4362:                 }
 4363:             }
 4364:         }
 4365:     }
 4366:     my @choices;
 4367:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 4368:         if (keys(%{$serverhomes}) > 1) {
 4369:             foreach my $name (sort(keys(%{$serverhomes}))) {
 4370:                 unless ($excluded{$name}) {
 4371:                     if (exists($altids->{$serverhomes->{$name}})) {
 4372:                         push(@choices,$altids->{$serverhomes->{$name}});
 4373:                     } else {
 4374:                         push(@choices,$serverhomes->{$name});
 4375:                     }
 4376:                 }
 4377:             }
 4378:         }
 4379:     }
 4380:     return sort(@choices);
 4381: }
 4382: 
 4383: sub print_loadbalancing {
 4384:     my ($dom,$settings,$rowtotal) = @_;
 4385:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 4386:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 4387:     my $numinrow = 1;
 4388:     my $datatable;
 4389:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 4390:     my (%currbalancer,%currtargets,%currrules,%existing);
 4391:     if (ref($settings) eq 'HASH') {
 4392:         %existing = %{$settings};
 4393:     }
 4394:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 4395:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 4396:                                   \%currtargets,\%currrules);
 4397:     } else {
 4398:         return;
 4399:     }
 4400:     my ($othertitle,$usertypes,$types) =
 4401:         &Apache::loncommon::sorted_inst_types($dom);
 4402:     my $rownum = 8;
 4403:     if (ref($types) eq 'ARRAY') {
 4404:         $rownum += scalar(@{$types});
 4405:     }
 4406:     my @css_class = ('LC_odd_row','LC_even_row');
 4407:     my $balnum = 0;
 4408:     my $islast;
 4409:     my (@toshow,$disabledtext);
 4410:     if (keys(%currbalancer) > 0) {
 4411:         @toshow = sort(keys(%currbalancer));
 4412:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 4413:             push(@toshow,'');
 4414:         }
 4415:     } else {
 4416:         @toshow = ('');
 4417:         $disabledtext = &mt('No existing load balancer');
 4418:     }
 4419:     foreach my $lonhost (@toshow) {
 4420:         if ($balnum == scalar(@toshow)-1) {
 4421:             $islast = 1;
 4422:         } else {
 4423:             $islast = 0;
 4424:         }
 4425:         my $cssidx = $balnum%2;
 4426:         my $targets_div_style = 'display: none';
 4427:         my $disabled_div_style = 'display: block';
 4428:         my $homedom_div_style = 'display: none';
 4429:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 4430:                       '<td rowspan="'.$rownum.'" valign="top">'.
 4431:                       '<p>';
 4432:         if ($lonhost eq '') {
 4433:             $datatable .= '<span class="LC_nobreak">';
 4434:             if (keys(%currbalancer) > 0) {
 4435:                 $datatable .= &mt('Add balancer:');
 4436:             } else {
 4437:                 $datatable .= &mt('Enable balancer:');
 4438:             }
 4439:             $datatable .= '&nbsp;'.
 4440:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 4441:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 4442:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 4443:                           '<option value="" selected="selected">'.&mt('None').
 4444:                           '</option>'."\n";
 4445:             foreach my $server (sort(keys(%servers))) {
 4446:                 next if ($currbalancer{$server});
 4447:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 4448:             }
 4449:             $datatable .=
 4450:                 '</select>'."\n".
 4451:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 4452:         } else {
 4453:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 4454:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 4455:                            &mt('Stop balancing').'</label>'.
 4456:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 4457:             $targets_div_style = 'display: block';
 4458:             $disabled_div_style = 'display: none';
 4459:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 4460:                 $homedom_div_style = 'display: block';
 4461:             }
 4462:         }
 4463:         $datatable .= '</p></td><td rowspan="'.$rownum.'" valign="top">'.
 4464:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 4465:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 4466:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 4467:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 4468:         my @sparestypes = ('primary','default');
 4469:         my %typetitles = &sparestype_titles();
 4470:         my %hostherechecked = (
 4471:                                   no => ' checked="checked"',
 4472:                               );
 4473:         foreach my $sparetype (@sparestypes) {
 4474:             my $targettable;
 4475:             for (my $i=0; $i<$numspares; $i++) {
 4476:                 my $checked;
 4477:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 4478:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 4479:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 4480:                             $checked = ' checked="checked"';
 4481:                         }
 4482:                     }
 4483:                 }
 4484:                 my ($chkboxval,$disabled);
 4485:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 4486:                     $chkboxval = $spares[$i];
 4487:                 }
 4488:                 if (exists($currbalancer{$spares[$i]})) {
 4489:                     $disabled = ' disabled="disabled"';
 4490:                 }
 4491:                 $targettable .=
 4492:                     '<td><span class="LC_nobreak"><label>'.
 4493:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 4494:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 4495:                     '</span></label></span></td>';
 4496:                 my $rem = $i%($numinrow);
 4497:                 if ($rem == 0) {
 4498:                     if (($i > 0) && ($i < $numspares-1)) {
 4499:                         $targettable .= '</tr>';
 4500:                     }
 4501:                     if ($i < $numspares-1) {
 4502:                         $targettable .= '<tr>';
 4503:                     }
 4504:                 }
 4505:             }
 4506:             if ($targettable ne '') {
 4507:                 my $rem = $numspares%($numinrow);
 4508:                 my $colsleft = $numinrow - $rem;
 4509:                 if ($colsleft > 1 ) {
 4510:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4511:                                     '&nbsp;</td>';
 4512:                 } elsif ($colsleft == 1) {
 4513:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 4514:                 }
 4515:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 4516:                                '<table><tr>'.$targettable.'</tr></table><br />';
 4517:             }
 4518:             $hostherechecked{$sparetype} = '';
 4519:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 4520:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 4521:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 4522:                         $hostherechecked{$sparetype} = ' checked="checked"';
 4523:                         $hostherechecked{'no'} = '';
 4524:                     }
 4525:                 }
 4526:             }
 4527:         }
 4528:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 4529:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 4530:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 4531:         foreach my $sparetype (@sparestypes) {
 4532:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 4533:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 4534:                           '</i></label><br />';
 4535:         }
 4536:         $datatable .= '</div></td></tr>'.
 4537:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 4538:                                            $othertitle,$usertypes,$types,\%servers,
 4539:                                            \%currbalancer,$lonhost,
 4540:                                            $targets_div_style,$homedom_div_style,
 4541:                                            $css_class[$cssidx],$balnum,$islast);
 4542:         $$rowtotal += $rownum;
 4543:         $balnum ++;
 4544:     }
 4545:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 4546:     return $datatable;
 4547: }
 4548: 
 4549: sub get_loadbalancers_config {
 4550:     my ($servers,$existing,$currbalancer,$currtargets,$currrules) = @_;
 4551:     return unless ((ref($servers) eq 'HASH') &&
 4552:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 4553:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH'));
 4554:     if (keys(%{$existing}) > 0) {
 4555:         my $oldlonhost;
 4556:         foreach my $key (sort(keys(%{$existing}))) {
 4557:             if ($key eq 'lonhost') {
 4558:                 $oldlonhost = $existing->{'lonhost'};
 4559:                 $currbalancer->{$oldlonhost} = 1;
 4560:             } elsif ($key eq 'targets') {
 4561:                 if ($oldlonhost) {
 4562:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 4563:                 }
 4564:             } elsif ($key eq 'rules') {
 4565:                 if ($oldlonhost) {
 4566:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 4567:                 }
 4568:             } elsif (ref($existing->{$key}) eq 'HASH') {
 4569:                 $currbalancer->{$key} = 1;
 4570:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 4571:                 $currrules->{$key} = $existing->{$key}{'rules'};
 4572:             }
 4573:         }
 4574:     } else {
 4575:         my ($balancerref,$targetsref) =
 4576:                 &Apache::lonnet::get_lonbalancer_config($servers);
 4577:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 4578:             foreach my $server (sort(keys(%{$balancerref}))) {
 4579:                 $currbalancer->{$server} = 1;
 4580:                 $currtargets->{$server} = $targetsref->{$server};
 4581:             }
 4582:         }
 4583:     }
 4584:     return;
 4585: }
 4586: 
 4587: sub loadbalancing_rules {
 4588:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 4589:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 4590:         $css_class,$balnum,$islast) = @_;
 4591:     my $output;
 4592:     my $num = 0;
 4593:     my ($alltypes,$othertypes,$titles) =
 4594:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 4595:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 4596:         foreach my $type (@{$alltypes}) {
 4597:             $num ++;
 4598:             my $current;
 4599:             if (ref($currrules) eq 'HASH') {
 4600:                 $current = $currrules->{$type};
 4601:             }
 4602:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 4603:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 4604:                     $current = '';
 4605:                 }
 4606:             }
 4607:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 4608:                                              $servers,$currbalancer,$lonhost,$dom,
 4609:                                              $targets_div_style,$homedom_div_style,
 4610:                                              $css_class,$balnum,$num,$islast);
 4611:         }
 4612:     }
 4613:     return $output;
 4614: }
 4615: 
 4616: sub loadbalancing_titles {
 4617:     my ($dom,$intdom,$usertypes,$types) = @_;
 4618:     my %othertypes = (
 4619:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 4620:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 4621:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 4622:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 4623:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 4624:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 4625:                      );
 4626:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 4627:     if (ref($types) eq 'ARRAY') {
 4628:         unshift(@alltypes,@{$types},'default');
 4629:     }
 4630:     my %titles;
 4631:     foreach my $type (@alltypes) {
 4632:         if ($type =~ /^_LC_/) {
 4633:             $titles{$type} = $othertypes{$type};
 4634:         } elsif ($type eq 'default') {
 4635:             $titles{$type} = &mt('All users from [_1]',$dom);
 4636:             if (ref($types) eq 'ARRAY') {
 4637:                 if (@{$types} > 0) {
 4638:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 4639:                 }
 4640:             }
 4641:         } elsif (ref($usertypes) eq 'HASH') {
 4642:             $titles{$type} = $usertypes->{$type};
 4643:         }
 4644:     }
 4645:     return (\@alltypes,\%othertypes,\%titles);
 4646: }
 4647: 
 4648: sub loadbalance_rule_row {
 4649:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 4650:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 4651:     my @rulenames;
 4652:     my %ruletitles = &offloadtype_text();
 4653:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 4654:         @rulenames = ('balancer','offloadedto','specific');
 4655:     } else {
 4656:         @rulenames = ('default','homeserver');
 4657:         if ($type eq '_LC_external') {
 4658:             push(@rulenames,'externalbalancer');
 4659:         } else {
 4660:             push(@rulenames,'specific');
 4661:         }
 4662:         push(@rulenames,'none');
 4663:     }
 4664:     my $style = $targets_div_style;
 4665:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 4666:         $style = $homedom_div_style;
 4667:     }
 4668:     my $space;
 4669:     if ($islast && $num == 1) {
 4670:         $space = '<div display="inline-block">&nbsp;</div>';
 4671:     }
 4672:     my $output =
 4673:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td valign="top">'.$space.
 4674:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 4675:         '<td valaign="top">'.$space.
 4676:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 4677:     for (my $i=0; $i<@rulenames; $i++) {
 4678:         my $rule = $rulenames[$i];
 4679:         my ($checked,$extra);
 4680:         if ($rulenames[$i] eq 'default') {
 4681:             $rule = '';
 4682:         }
 4683:         if ($rulenames[$i] eq 'specific') {
 4684:             if (ref($servers) eq 'HASH') {
 4685:                 my $default;
 4686:                 if (($current ne '') && (exists($servers->{$current}))) {
 4687:                     $checked = ' checked="checked"';
 4688:                 }
 4689:                 unless ($checked) {
 4690:                     $default = ' selected="selected"';
 4691:                 }
 4692:                 $extra =
 4693:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 4694:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 4695:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 4696:                     '<option value=""'.$default.'></option>'."\n";
 4697:                 foreach my $server (sort(keys(%{$servers}))) {
 4698:                     if (ref($currbalancer) eq 'HASH') {
 4699:                         next if (exists($currbalancer->{$server}));
 4700:                     }
 4701:                     my $selected;
 4702:                     if ($server eq $current) {
 4703:                         $selected = ' selected="selected"';
 4704:                     }
 4705:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 4706:                 }
 4707:                 $extra .= '</select>';
 4708:             }
 4709:         } elsif ($rule eq $current) {
 4710:             $checked = ' checked="checked"';
 4711:         }
 4712:         $output .= '<span class="LC_nobreak"><label>'.
 4713:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 4714:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 4715:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 4716:                    ')"'.$checked.' />&nbsp;';
 4717:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 4718:             $output .= $ruletitles{'particular'};
 4719:         } else {
 4720:             $output .= $ruletitles{$rulenames[$i]};
 4721:         }
 4722:         $output .= '</label>'.$extra.'</span><br />'."\n";
 4723:     }
 4724:     $output .= '</div></td></tr>'."\n";
 4725:     return $output;
 4726: }
 4727: 
 4728: sub offloadtype_text {
 4729:     my %ruletitles = &Apache::lonlocal::texthash (
 4730:            'default'          => 'Offloads to default destinations',
 4731:            'homeserver'       => "Offloads to user's home server",
 4732:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 4733:            'specific'         => 'Offloads to specific server',
 4734:            'none'             => 'No offload',
 4735:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 4736:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 4737:            'particular'       => 'Session hosted (after re-auth) on server:',
 4738:     );
 4739:     return %ruletitles;
 4740: }
 4741: 
 4742: sub sparestype_titles {
 4743:     my %typestitles = &Apache::lonlocal::texthash (
 4744:                           'primary' => 'primary',
 4745:                           'default' => 'default',
 4746:                       );
 4747:     return %typestitles;
 4748: }
 4749: 
 4750: sub contact_titles {
 4751:     my %titles = &Apache::lonlocal::texthash (
 4752:                    'supportemail'    => 'Support E-mail address',
 4753:                    'adminemail'      => 'Default Server Admin E-mail address',
 4754:                    'errormail'       => 'Error reports to be e-mailed to',
 4755:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 4756:                    'helpdeskmail'    => "Helpdesk requests for this domain's users",
 4757:                    'otherdomsmail'   => 'Helpdesk requests for other (unconfigured) domains',
 4758:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 4759:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 4760:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 4761:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 4762:                  );
 4763:     my %short_titles = &Apache::lonlocal::texthash (
 4764:                            adminemail   => 'Admin E-mail address',
 4765:                            supportemail => 'Support E-mail',
 4766:                        );   
 4767:     return (\%titles,\%short_titles);
 4768: }
 4769: 
 4770: sub helpform_fields {
 4771:     my %titles =  &Apache::lonlocal::texthash (
 4772:                        'username'   => 'Name',
 4773:                        'user'       => 'Username/domain',
 4774:                        'phone'      => 'Phone',
 4775:                        'cc'         => 'Cc e-mail',
 4776:                        'course'     => 'Course Details',
 4777:                        'section'    => 'Sections',
 4778:                        'screenshot' => 'File upload',
 4779:     );
 4780:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 4781:     my %possoptions = (
 4782:                         username     => ['yes','no','req'],
 4783:                         phone        => ['yes','no','req'],
 4784:                         user         => ['yes','no'],
 4785:                         cc           => ['yes','no'],
 4786:                         course       => ['yes','no'],
 4787:                         section      => ['yes','no'],
 4788:                         screenshot   => ['yes','no'],
 4789:                       );
 4790:     my %fieldoptions = &Apache::lonlocal::texthash (
 4791:                          'yes'  => 'Optional',
 4792:                          'req'  => 'Required',
 4793:                          'no'   => "Not shown",
 4794:     );
 4795:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 4796: }
 4797: 
 4798: sub tool_titles {
 4799:     my %titles = &Apache::lonlocal::texthash (
 4800:                      aboutme    => 'Personal web page',
 4801:                      blog       => 'Blog',
 4802:                      webdav     => 'WebDAV',
 4803:                      portfolio  => 'Portfolio',
 4804:                      official   => 'Official courses (with institutional codes)',
 4805:                      unofficial => 'Unofficial courses',
 4806:                      community  => 'Communities',
 4807:                      textbook   => 'Textbook courses',
 4808:                  );
 4809:     return %titles;
 4810: }
 4811: 
 4812: sub courserequest_titles {
 4813:     my %titles = &Apache::lonlocal::texthash (
 4814:                                    official   => 'Official',
 4815:                                    unofficial => 'Unofficial',
 4816:                                    community  => 'Communities',
 4817:                                    textbook   => 'Textbook',
 4818:                                    norequest  => 'Not allowed',
 4819:                                    approval   => 'Approval by Dom. Coord.',
 4820:                                    validate   => 'With validation',
 4821:                                    autolimit  => 'Numerical limit',
 4822:                                    unlimited  => '(blank for unlimited)',
 4823:                  );
 4824:     return %titles;
 4825: }
 4826: 
 4827: sub authorrequest_titles {
 4828:     my %titles = &Apache::lonlocal::texthash (
 4829:                                    norequest  => 'Not allowed',
 4830:                                    approval   => 'Approval by Dom. Coord.',
 4831:                                    automatic  => 'Automatic approval',
 4832:                  );
 4833:     return %titles;
 4834: }
 4835: 
 4836: sub courserequest_conditions {
 4837:     my %conditions = &Apache::lonlocal::texthash (
 4838:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 4839:        validate   => '(Processing of request subject to institutional validation).',
 4840:                  );
 4841:     return %conditions;
 4842: }
 4843: 
 4844: 
 4845: sub print_usercreation {
 4846:     my ($position,$dom,$settings,$rowtotal) = @_;
 4847:     my $numinrow = 4;
 4848:     my $datatable;
 4849:     if ($position eq 'top') {
 4850:         $$rowtotal ++;
 4851:         my $rowcount = 0;
 4852:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 4853:         if (ref($rules) eq 'HASH') {
 4854:             if (keys(%{$rules}) > 0) {
 4855:                 $datatable .= &user_formats_row('username',$settings,$rules,
 4856:                                                 $ruleorder,$numinrow,$rowcount);
 4857:                 $$rowtotal ++;
 4858:                 $rowcount ++;
 4859:             }
 4860:         }
 4861:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 4862:         if (ref($idrules) eq 'HASH') {
 4863:             if (keys(%{$idrules}) > 0) {
 4864:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 4865:                                                 $idruleorder,$numinrow,$rowcount);
 4866:                 $$rowtotal ++;
 4867:                 $rowcount ++;
 4868:             }
 4869:         }
 4870:         if ($rowcount == 0) {
 4871:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 4872:             $$rowtotal ++;
 4873:             $rowcount ++;
 4874:         }
 4875:     } elsif ($position eq 'middle') {
 4876:         my @creators = ('author','course','requestcrs');
 4877:         my ($rules,$ruleorder) =
 4878:             &Apache::lonnet::inst_userrules($dom,'username');
 4879:         my %lt = &usercreation_types();
 4880:         my %checked;
 4881:         if (ref($settings) eq 'HASH') {
 4882:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 4883:                 foreach my $item (@creators) {
 4884:                     $checked{$item} = $settings->{'cancreate'}{$item};
 4885:                 }
 4886:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 4887:                 foreach my $item (@creators) {
 4888:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 4889:                         $checked{$item} = 'none';
 4890:                     }
 4891:                 }
 4892:             }
 4893:         }
 4894:         my $rownum = 0;
 4895:         foreach my $item (@creators) {
 4896:             $rownum ++;
 4897:             if ($checked{$item} eq '') {
 4898:                 $checked{$item} = 'any';
 4899:             }
 4900:             my $css_class;
 4901:             if ($rownum%2) {
 4902:                 $css_class = '';
 4903:             } else {
 4904:                 $css_class = ' class="LC_odd_row" ';
 4905:             }
 4906:             $datatable .= '<tr'.$css_class.'>'.
 4907:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 4908:                          '</span></td><td align="right">';
 4909:             my @options = ('any');
 4910:             if (ref($rules) eq 'HASH') {
 4911:                 if (keys(%{$rules}) > 0) {
 4912:                     push(@options,('official','unofficial'));
 4913:                 }
 4914:             }
 4915:             push(@options,'none');
 4916:             foreach my $option (@options) {
 4917:                 my $type = 'radio';
 4918:                 my $check = ' ';
 4919:                 if ($checked{$item} eq $option) {
 4920:                     $check = ' checked="checked" ';
 4921:                 } 
 4922:                 $datatable .= '<span class="LC_nobreak"><label>'.
 4923:                               '<input type="'.$type.'" name="can_createuser_'.
 4924:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 4925:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 4926:             }
 4927:             $datatable .= '</td></tr>';
 4928:         }
 4929:     } else {
 4930:         my @contexts = ('author','course','domain');
 4931:         my @authtypes = ('int','krb4','krb5','loc');
 4932:         my %checked;
 4933:         if (ref($settings) eq 'HASH') {
 4934:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 4935:                 foreach my $item (@contexts) {
 4936:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 4937:                         foreach my $auth (@authtypes) {
 4938:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 4939:                                 $checked{$item}{$auth} = ' checked="checked" ';
 4940:                             }
 4941:                         }
 4942:                     }
 4943:                 }
 4944:             }
 4945:         } else {
 4946:             foreach my $item (@contexts) {
 4947:                 foreach my $auth (@authtypes) {
 4948:                     $checked{$item}{$auth} = ' checked="checked" ';
 4949:                 }
 4950:             }
 4951:         }
 4952:         my %title = &context_names();
 4953:         my %authname = &authtype_names();
 4954:         my $rownum = 0;
 4955:         my $css_class; 
 4956:         foreach my $item (@contexts) {
 4957:             if ($rownum%2) {
 4958:                 $css_class = '';
 4959:             } else {
 4960:                 $css_class = ' class="LC_odd_row" ';
 4961:             }
 4962:             $datatable .=   '<tr'.$css_class.'>'.
 4963:                             '<td>'.$title{$item}.
 4964:                             '</td><td class="LC_left_item">'.
 4965:                             '<span class="LC_nobreak">';
 4966:             foreach my $auth (@authtypes) {
 4967:                 $datatable .= '<label>'. 
 4968:                               '<input type="checkbox" name="'.$item.'_auth" '.
 4969:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 4970:                               $authname{$auth}.'</label>&nbsp;';
 4971:             }
 4972:             $datatable .= '</span></td></tr>';
 4973:             $rownum ++;
 4974:         }
 4975:         $$rowtotal += $rownum;
 4976:     }
 4977:     return $datatable;
 4978: }
 4979: 
 4980: sub print_selfcreation {
 4981:     my ($position,$dom,$settings,$rowtotal) = @_;
 4982:     my (@selfcreate,$createsettings,$processing,$datatable);
 4983:     if (ref($settings) eq 'HASH') {
 4984:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 4985:             $createsettings = $settings->{'cancreate'};
 4986:             if (ref($createsettings) eq 'HASH') {
 4987:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 4988:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 4989:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 4990:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 4991:                         @selfcreate = ('email','login','sso');
 4992:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 4993:                         @selfcreate = ($createsettings->{'selfcreate'});
 4994:                     }
 4995:                 }
 4996:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 4997:                     $processing = $createsettings->{'selfcreateprocessing'};
 4998:                 }
 4999:             }
 5000:         }
 5001:     }
 5002:     my %radiohash;
 5003:     my $numinrow = 4;
 5004:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 5005:     if ($position eq 'top') {
 5006:         my %choices = &Apache::lonlocal::texthash (
 5007:                                                       cancreate_login      => 'Institutional Login',
 5008:                                                       cancreate_sso        => 'Institutional Single Sign On',
 5009:                                                   );
 5010:         my @toggles = sort(keys(%choices));
 5011:         my %defaultchecked = (
 5012:                                'cancreate_login' => 'off',
 5013:                                'cancreate_sso'   => 'off',
 5014:                              );
 5015:         my ($onclick,$itemcount);
 5016:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 5017:                                                      \%choices,$itemcount,$onclick);
 5018:         $$rowtotal += $itemcount;
 5019:         
 5020:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5021: 
 5022:         if (ref($usertypes) eq 'HASH') {
 5023:             if (keys(%{$usertypes}) > 0) {
 5024:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 5025:                                              $dom,$numinrow,$othertitle,
 5026:                                              'statustocreate',$$rowtotal);
 5027:                 $$rowtotal ++;
 5028:             }
 5029:         }
 5030:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 5031:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 5032:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 5033:         my $rem;
 5034:         my $numperrow = 2;
 5035:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 5036:         $datatable .= '<tr'.$css_class.'>'.
 5037:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 5038:                      '<td class="LC_left_item">'."\n".
 5039:                      '<table><tr><td>'."\n";
 5040:         for (my $i=0; $i<@fields; $i++) {
 5041:             $rem = $i%($numperrow);
 5042:             if ($rem == 0) {
 5043:                 if ($i > 0) {
 5044:                     $datatable .= '</tr>';
 5045:                 }
 5046:                 $datatable .= '<tr>';
 5047:             }
 5048:             my $currval;
 5049:             if (ref($createsettings) eq 'HASH') {
 5050:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 5051:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 5052:                 }
 5053:             }
 5054:             $datatable .= '<td class="LC_left_item">'.
 5055:                           '<span class="LC_nobreak">'.
 5056:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 5057:                           'value="'.$currval.'" size="10" />&nbsp;'.
 5058:                           $fieldtitles{$fields[$i]}.'</span></td>';
 5059:         }
 5060:         my $colsleft = $numperrow - $rem;
 5061:         if ($colsleft > 1 ) {
 5062:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 5063:                          '&nbsp;</td>';
 5064:         } elsif ($colsleft == 1) {
 5065:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 5066:         }
 5067:         $datatable .= '</tr></table></td></tr>';
 5068:         $$rowtotal ++;
 5069:     } elsif ($position eq 'middle') {
 5070:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 5071:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5072:         $usertypes->{'default'} = $othertitle;
 5073:         if (ref($types) eq 'ARRAY') {
 5074:             push(@{$types},'default');
 5075:             $usertypes->{'default'} = $othertitle;
 5076:             foreach my $status (@{$types}) {
 5077:                 $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 5078:                                                        $numinrow,$$rowtotal,$usertypes);
 5079:                 $$rowtotal ++;
 5080:             }
 5081:         }
 5082:     } else {
 5083:         my %choices = &Apache::lonlocal::texthash (
 5084:                                                       cancreate_email => 'E-mail address as username',
 5085:                                                   );
 5086:         my @toggles = sort(keys(%choices));
 5087:         my %defaultchecked = (
 5088:                                'cancreate_email' => 'off',
 5089:                              );
 5090:         my $itemcount = 0;
 5091:         my $display = 'none';
 5092:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 5093:             $display = 'block';
 5094:         }
 5095:         my $onclick = "toggleDisplay(this.form,'emailoptions');";
 5096:         my $additional = '<div id="emailoptions" style="display: '.$display.'">';
 5097:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 5098:         my $usertypes = {};
 5099:         my $order = [];
 5100:         if ((ref($domdefaults{'inststatustypes'}) eq 'HASH') && (ref($domdefaults{'inststatusguest'}) eq 'ARRAY')) {
 5101:             $usertypes = $domdefaults{'inststatustypes'};
 5102:             $order = $domdefaults{'inststatusguest'};
 5103:         }
 5104:         if (ref($order) eq 'ARRAY') {
 5105:             push(@{$order},'default');
 5106:             if (@{$order} > 1) {
 5107:                 $usertypes->{'default'} = &mt('Other users');
 5108:                 $additional .= '<table><tr>';
 5109:                 foreach my $status (@{$order}) {
 5110:                     $additional .= '<th>'.$usertypes->{$status}.'</th>';
 5111:                 }
 5112:                 $additional .= '</tr><tr>';
 5113:                 foreach my $status (@{$order}) {
 5114:                     $additional .= '<td>'.&email_as_username($rowtotal,$processing,$status).'</td>';
 5115:                 }
 5116:                 $additional .= '</tr></table>';
 5117:             } else {
 5118:                 $usertypes->{'default'} = &mt('All users');
 5119:                 $additional .= &email_as_username($rowtotal,$processing);
 5120:             }
 5121:         }
 5122:         $additional .= '</div>'."\n";
 5123: 
 5124:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 5125:                                                      \%choices,$$rowtotal,$onclick,$additional);
 5126:         $$rowtotal ++;
 5127:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal);
 5128:         $$rowtotal ++;
 5129:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 5130:         $numinrow = 1;
 5131:         if (ref($order) eq 'ARRAY') {
 5132:             foreach my $status (@{$order}) {
 5133:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 5134:                                                        $numinrow,$$rowtotal,$usertypes,$infofields,$infotitles);
 5135:                 $$rowtotal ++;
 5136:             }
 5137:         }
 5138:         my ($emailrules,$emailruleorder) =
 5139:             &Apache::lonnet::inst_userrules($dom,'email');
 5140:         if (ref($emailrules) eq 'HASH') {
 5141:             if (keys(%{$emailrules}) > 0) {
 5142:                 $datatable .= &user_formats_row('email',$settings,$emailrules,
 5143:                                                 $emailruleorder,$numinrow,$$rowtotal);
 5144:                 $$rowtotal ++;
 5145:             }
 5146:         }
 5147:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal);
 5148:     }
 5149:     return $datatable;
 5150: }
 5151: 
 5152: sub email_as_username {
 5153:     my ($rowtotal,$processing,$type) = @_;
 5154:     my %choices =
 5155:         &Apache::lonlocal::texthash (
 5156:                                       automatic => 'Automatic approval',
 5157:                                       approval  => 'Queued for approval',
 5158:                                     );
 5159:     my $output;
 5160:     foreach my $option ('automatic','approval') {
 5161:         my $checked;
 5162:         if (ref($processing) eq 'HASH') {
 5163:             if ($type eq '') {   
 5164:                 if (!exists($processing->{'default'})) {
 5165:                     if ($option eq 'automatic') {
 5166:                         $checked = ' checked="checked"';
 5167:                     }
 5168:                 } else {
 5169:                     if ($processing->{'default'} eq $option) {
 5170:                         $checked = ' checked="checked"';
 5171:                     }
 5172:                 }
 5173:             } else {
 5174:                 if (!exists($processing->{$type})) {
 5175:                     if ($option eq 'automatic') {
 5176:                         $checked = ' checked="checked"';
 5177:                     }
 5178:                 } else {
 5179:                     if ($processing->{$type} eq $option) {
 5180:                         $checked = ' checked="checked"';
 5181:                     }
 5182:                 }
 5183:             }
 5184:         } elsif ($option eq 'automatic') {
 5185:             $checked = ' checked="checked"'; 
 5186:         }
 5187:         my $name = 'cancreate_emailprocess';
 5188:         if (($type ne '') && ($type ne 'default')) {
 5189:             $name .= '_'.$type;
 5190:         }
 5191:         $output .= '<span class="LC_nobreak"><label>'.
 5192:                    '<input type="radio" name="'.$name.'"'.
 5193:                    $checked.' value="'.$option.'" />'.
 5194:                    $choices{$option}.'</label></span>';
 5195:         if ($type eq '') {
 5196:             $output .= '&nbsp;';
 5197:         } else {
 5198:             $output .= '<br />';
 5199:         }
 5200:     }
 5201:     $$rowtotal ++;
 5202:     return $output;
 5203: }
 5204: 
 5205: sub captcha_choice {
 5206:     my ($context,$settings,$itemcount) = @_;
 5207:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
 5208:         $vertext,$currver); 
 5209:     my %lt = &captcha_phrases();
 5210:     $keyentry = 'hidden';
 5211:     if ($context eq 'cancreate') {
 5212:         $rowname = &mt('CAPTCHA validation');
 5213:     } elsif ($context eq 'login') {
 5214:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
 5215:     }
 5216:     if (ref($settings) eq 'HASH') {
 5217:         if ($settings->{'captcha'}) {
 5218:             $checked{$settings->{'captcha'}} = ' checked="checked"';
 5219:         } else {
 5220:             $checked{'original'} = ' checked="checked"';
 5221:         }
 5222:         if ($settings->{'captcha'} eq 'recaptcha') {
 5223:             $pubtext = $lt{'pub'};
 5224:             $privtext = $lt{'priv'};
 5225:             $keyentry = 'text';
 5226:             $vertext = $lt{'ver'};
 5227:             $currver = $settings->{'recaptchaversion'};
 5228:             if ($currver ne '2') {
 5229:                 $currver = 1;
 5230:             }
 5231:         }
 5232:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
 5233:             $currpub = $settings->{'recaptchakeys'}{'public'};
 5234:             $currpriv = $settings->{'recaptchakeys'}{'private'};
 5235:         }
 5236:     } else {
 5237:         $checked{'original'} = ' checked="checked"';
 5238:     }
 5239:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5240:     my $output = '<tr'.$css_class.'>'.
 5241:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="2">'."\n".
 5242:                  '<table><tr><td>'."\n";
 5243:     foreach my $option ('original','recaptcha','notused') {
 5244:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
 5245:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
 5246:                    $lt{$option}.'</label></span>';
 5247:         unless ($option eq 'notused') {
 5248:             $output .= ('&nbsp;'x2)."\n";
 5249:         }
 5250:     }
 5251: #
 5252: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
 5253: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
 5254: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
 5255: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
 5256: #
 5257:     $output .= '</td></tr>'."\n".
 5258:                '<tr><td>'."\n".
 5259:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
 5260:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
 5261:                $currpub.'" size="40" /></span><br />'."\n".
 5262:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
 5263:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
 5264:                $currpriv.'" size="40" /></span><br />'.
 5265:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
 5266:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
 5267:                $currver.'" size="3" /></span><br />'.
 5268:                '</td></tr></table>'."\n".
 5269:                '</td></tr>';
 5270:     return $output;
 5271: }
 5272: 
 5273: sub user_formats_row {
 5274:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount) = @_;
 5275:     my $output;
 5276:     my %text = (
 5277:                    'username' => 'new usernames',
 5278:                    'id'       => 'IDs',
 5279:                    'email'    => 'self-created accounts (e-mail)',
 5280:                );
 5281:     my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 5282:     $output = '<tr '.$css_class.'>'.
 5283:               '<td><span class="LC_nobreak">';
 5284:     if ($type eq 'email') {
 5285:         $output .= &mt("Formats disallowed for $text{$type}: ");
 5286:     } else {
 5287:         $output .= &mt("Format rules to check for $text{$type}: ");
 5288:     }
 5289:     $output .= '</span></td>'.
 5290:                '<td class="LC_left_item" colspan="2"><table>';
 5291:     my $rem;
 5292:     if (ref($ruleorder) eq 'ARRAY') {
 5293:         for (my $i=0; $i<@{$ruleorder}; $i++) {
 5294:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
 5295:                 my $rem = $i%($numinrow);
 5296:                 if ($rem == 0) {
 5297:                     if ($i > 0) {
 5298:                         $output .= '</tr>';
 5299:                     }
 5300:                     $output .= '<tr>';
 5301:                 }
 5302:                 my $check = ' ';
 5303:                 if (ref($settings) eq 'HASH') {
 5304:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
 5305:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
 5306:                             $check = ' checked="checked" ';
 5307:                         }
 5308:                     }
 5309:                 }
 5310:                 $output .= '<td class="LC_left_item">'.
 5311:                            '<span class="LC_nobreak"><label>'.
 5312:                            '<input type="checkbox" name="'.$type.'_rule" '.
 5313:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
 5314:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
 5315:             }
 5316:         }
 5317:         $rem = @{$ruleorder}%($numinrow);
 5318:     }
 5319:     my $colsleft = $numinrow - $rem;
 5320:     if ($colsleft > 1 ) {
 5321:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 5322:                    '&nbsp;</td>';
 5323:     } elsif ($colsleft == 1) {
 5324:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 5325:     }
 5326:     $output .= '</tr></table></td></tr>';
 5327:     return $output;
 5328: }
 5329: 
 5330: sub usercreation_types {
 5331:     my %lt = &Apache::lonlocal::texthash (
 5332:                     author     => 'When adding a co-author',
 5333:                     course     => 'When adding a user to a course',
 5334:                     requestcrs => 'When requesting a course',
 5335:                     any        => 'Any',
 5336:                     official   => 'Institutional only ',
 5337:                     unofficial => 'Non-institutional only',
 5338:                     none       => 'None',
 5339:     );
 5340:     return %lt;
 5341: }
 5342: 
 5343: sub selfcreation_types {
 5344:     my %lt = &Apache::lonlocal::texthash (
 5345:                     selfcreate => 'User creates own account',
 5346:                     any        => 'Any',
 5347:                     official   => 'Institutional only ',
 5348:                     unofficial => 'Non-institutional only',
 5349:                     email      => 'E-mail address',
 5350:                     login      => 'Institutional Login',
 5351:                     sso        => 'SSO',
 5352:              );
 5353: }
 5354: 
 5355: sub authtype_names {
 5356:     my %lt = &Apache::lonlocal::texthash(
 5357:                       int    => 'Internal',
 5358:                       krb4   => 'Kerberos 4',
 5359:                       krb5   => 'Kerberos 5',
 5360:                       loc    => 'Local',
 5361:                   );
 5362:     return %lt;
 5363: }
 5364: 
 5365: sub context_names {
 5366:     my %context_title = &Apache::lonlocal::texthash(
 5367:        author => 'Creating users when an Author',
 5368:        course => 'Creating users when in a course',
 5369:        domain => 'Creating users when a Domain Coordinator',
 5370:     );
 5371:     return %context_title;
 5372: }
 5373: 
 5374: sub print_usermodification {
 5375:     my ($position,$dom,$settings,$rowtotal) = @_;
 5376:     my $numinrow = 4;
 5377:     my ($context,$datatable,$rowcount);
 5378:     if ($position eq 'top') {
 5379:         $rowcount = 0;
 5380:         $context = 'author'; 
 5381:         foreach my $role ('ca','aa') {
 5382:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 5383:                                                    $numinrow,$rowcount);
 5384:             $$rowtotal ++;
 5385:             $rowcount ++;
 5386:         }
 5387:     } elsif ($position eq 'bottom') {
 5388:         $context = 'course';
 5389:         $rowcount = 0;
 5390:         foreach my $role ('st','ep','ta','in','cr') {
 5391:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 5392:                                                    $numinrow,$rowcount);
 5393:             $$rowtotal ++;
 5394:             $rowcount ++;
 5395:         }
 5396:     }
 5397:     return $datatable;
 5398: }
 5399: 
 5400: sub print_defaults {
 5401:     my ($position,$dom,$settings,$rowtotal) = @_;
 5402:     my $rownum = 0;
 5403:     my ($datatable,$css_class);
 5404:     if ($position eq 'top') {
 5405:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
 5406:                      'datelocale_def','portal_def');
 5407:         my %defaults;
 5408:         if (ref($settings) eq 'HASH') {
 5409:             %defaults = %{$settings};
 5410:         } else {
 5411:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 5412:             foreach my $item (@items) {
 5413:                 $defaults{$item} = $domdefaults{$item};
 5414:             }
 5415:         }
 5416:         my $titles = &defaults_titles($dom);
 5417:         foreach my $item (@items) {
 5418:             if ($rownum%2) {
 5419:                 $css_class = '';
 5420:             } else {
 5421:                 $css_class = ' class="LC_odd_row" ';
 5422:             }
 5423:             $datatable .= '<tr'.$css_class.'>'.
 5424:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 5425:                           '</span></td><td class="LC_right_item" colspan="3">';
 5426:             if ($item eq 'auth_def') {
 5427:                 my @authtypes = ('internal','krb4','krb5','localauth');
 5428:                 my %shortauth = (
 5429:                                  internal => 'int',
 5430:                                  krb4 => 'krb4',
 5431:                                  krb5 => 'krb5',
 5432:                                  localauth  => 'loc'
 5433:                                 );
 5434:                 my %authnames = &authtype_names();
 5435:                 foreach my $auth (@authtypes) {
 5436:                     my $checked = ' ';
 5437:                     if ($defaults{$item} eq $auth) {
 5438:                         $checked = ' checked="checked" ';
 5439:                     }
 5440:                     $datatable .= '<label><input type="radio" name="'.$item.
 5441:                                   '" value="'.$auth.'"'.$checked.'/>'.
 5442:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
 5443:                 }
 5444:             } elsif ($item eq 'timezone_def') {
 5445:                 my $includeempty = 1;
 5446:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
 5447:             } elsif ($item eq 'datelocale_def') {
 5448:                 my $includeempty = 1;
 5449:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
 5450:             } elsif ($item eq 'lang_def') {
 5451:                 my $includeempty = 1;
 5452:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
 5453:             } else {
 5454:                 my $size;
 5455:                 if ($item eq 'portal_def') {
 5456:                     $size = ' size="25"';
 5457:                 }
 5458:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 5459:                               $defaults{$item}.'"'.$size.' />';
 5460:             }
 5461:             $datatable .= '</td></tr>';
 5462:             $rownum ++;
 5463:         }
 5464:     } else {
 5465:         my (%defaults);
 5466:         if (ref($settings) eq 'HASH') {
 5467:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH') &&
 5468:                 (ref($settings->{'inststatusguest'}) eq 'ARRAY')) {
 5469:                 my $maxnum = @{$settings->{'inststatusorder'}};
 5470:                 for (my $i=0; $i<$maxnum; $i++) {
 5471:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
 5472:                     my $item = $settings->{'inststatusorder'}->[$i];
 5473:                     my $title = $settings->{'inststatustypes'}->{$item};
 5474:                     my $guestok;
 5475:                     if (grep(/^\Q$item\E$/,@{$settings->{'inststatusguest'}})) {
 5476:                         $guestok = 1;
 5477:                     }
 5478:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
 5479:                     $datatable .= '<tr'.$css_class.'>'.
 5480:                                   '<td><span class="LC_nobreak">'.
 5481:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
 5482:                     for (my $k=0; $k<=$maxnum; $k++) {
 5483:                         my $vpos = $k+1;
 5484:                         my $selstr;
 5485:                         if ($k == $i) {
 5486:                             $selstr = ' selected="selected" ';
 5487:                         }
 5488:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5489:                     }
 5490:                     my ($checkedon,$checkedoff);
 5491:                     $checkedoff = ' checked="checked"';
 5492:                     if ($guestok) {
 5493:                         $checkedon = $checkedoff;
 5494:                         $checkedoff = ''; 
 5495:                     }
 5496:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
 5497:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
 5498:                                   &mt('delete').'</span></td>'.
 5499:                                   '<td class="LC_left_item"><span class="LC_nobreak">'.&mt('Name displayed:').
 5500:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
 5501:                                   '</span></td>'.
 5502:                                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 5503:                                   '<label><input type="radio" value="1" name="inststatus_guest_'.$item.'"'.$checkedon.' />'.
 5504:                                   &mt('Yes').'</label>'.('&nbsp;'x2).
 5505:                                   '<label><input type="radio" value="0" name="inststatus_guest_'.$item.'"'.$checkedoff.' />'.
 5506:                                   &mt('No').'</label></span></td></tr>';
 5507:                 }
 5508:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
 5509:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
 5510:                 $datatable .= '<tr '.$css_class.'>'.
 5511:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
 5512:                 for (my $k=0; $k<=$maxnum; $k++) {
 5513:                     my $vpos = $k+1;
 5514:                     my $selstr;
 5515:                     if ($k == $maxnum) {
 5516:                         $selstr = ' selected="selected" ';
 5517:                     }
 5518:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5519:                 }
 5520:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
 5521:                               '<input type="text" size="10" name="addinststatus" value="" />'.
 5522:                               '&nbsp;'.&mt('(new)').
 5523:                               '</span></td><td class="LC_left_item"><span class="LC_nobreak">'.
 5524:                               &mt('Name displayed:').
 5525:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
 5526:                               '<td class="LC_right_item"><span class="LC_nobreak">'.
 5527:                               '<label><input type="radio" value="1" name="addinststatus_guest" />'.
 5528:                               &mt('Yes').'</label>'.('&nbsp;'x2).
 5529:                               '<label><input type="radio" value="0" name="addinststatus_guest" />'.
 5530:                               &mt('No').'</label></span></td></tr>';
 5531:                               '</tr>'."\n";
 5532:                 $rownum ++;
 5533:             }
 5534:         }
 5535:     }
 5536:     $$rowtotal += $rownum;
 5537:     return $datatable;
 5538: }
 5539: 
 5540: sub get_languages_hash {
 5541:     my %langchoices;
 5542:     foreach my $id (&Apache::loncommon::languageids()) {
 5543:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 5544:         if ($code ne '') {
 5545:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 5546:         }
 5547:     }
 5548:     return %langchoices;
 5549: }
 5550: 
 5551: sub defaults_titles {
 5552:     my ($dom) = @_;
 5553:     my %titles = &Apache::lonlocal::texthash (
 5554:                    'auth_def'      => 'Default authentication type',
 5555:                    'auth_arg_def'  => 'Default authentication argument',
 5556:                    'lang_def'      => 'Default language',
 5557:                    'timezone_def'  => 'Default timezone',
 5558:                    'datelocale_def' => 'Default locale for dates',
 5559:                    'portal_def'     => 'Portal/Default URL',
 5560:                  );
 5561:     if ($dom) {
 5562:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
 5563:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 5564:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
 5565:         $protocol = 'http' if ($protocol ne 'https');
 5566:         if ($uint_dom) {
 5567:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
 5568:                                          $uint_dom);
 5569:         }
 5570:     }
 5571:     return (\%titles);
 5572: }
 5573: 
 5574: sub print_scantronformat {
 5575:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
 5576:     my $itemcount = 1;
 5577:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
 5578:         %confhash);
 5579:     my $switchserver = &check_switchserver($dom,$confname);
 5580:     my %lt = &Apache::lonlocal::texthash (
 5581:                 default => 'Default bubblesheet format file error',
 5582:                 custom  => 'Custom bubblesheet format file error',
 5583:              );
 5584:     my %scantronfiles = (
 5585:         default => 'default.tab',
 5586:         custom => 'custom.tab',
 5587:     );
 5588:     foreach my $key (keys(%scantronfiles)) {
 5589:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
 5590:                               .$scantronfiles{$key};
 5591:     }
 5592:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
 5593:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
 5594:         if (!$switchserver) {
 5595:             my $servadm = $r->dir_config('lonAdmEMail');
 5596:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
 5597:             if ($configuserok eq 'ok') {
 5598:                 if ($author_ok eq 'ok') {
 5599:                     my %legacyfile = (
 5600:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab', 
 5601:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab', 
 5602:                     );
 5603:                     my %md5chk;
 5604:                     foreach my $type (keys(%legacyfile)) {
 5605:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
 5606:                         chomp($md5chk{$type});
 5607:                     }
 5608:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
 5609:                         foreach my $type (keys(%legacyfile)) {
 5610:                             ($scantronurls{$type},my $error) = 
 5611:                                 &legacy_scantronformat($r,$dom,$confname,
 5612:                                                  $type,$legacyfile{$type},
 5613:                                                  $scantronurls{$type},
 5614:                                                  $scantronfiles{$type});
 5615:                             if ($error ne '') {
 5616:                                 $error{$type} = $error;
 5617:                             }
 5618:                         }
 5619:                         if (keys(%error) == 0) {
 5620:                             $is_custom = 1;
 5621:                             $confhash{'scantron'}{'scantronformat'} = 
 5622:                                 $scantronurls{'custom'};
 5623:                             my $putresult = 
 5624:                                 &Apache::lonnet::put_dom('configuration',
 5625:                                                          \%confhash,$dom);
 5626:                             if ($putresult ne 'ok') {
 5627:                                 $error{'custom'} = 
 5628:                                     '<span class="LC_error">'.
 5629:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 5630:                             }
 5631:                         }
 5632:                     } else {
 5633:                         ($scantronurls{'default'},my $error) =
 5634:                             &legacy_scantronformat($r,$dom,$confname,
 5635:                                           'default',$legacyfile{'default'},
 5636:                                           $scantronurls{'default'},
 5637:                                           $scantronfiles{'default'});
 5638:                         if ($error eq '') {
 5639:                             $confhash{'scantron'}{'scantronformat'} = ''; 
 5640:                             my $putresult =
 5641:                                 &Apache::lonnet::put_dom('configuration',
 5642:                                                          \%confhash,$dom);
 5643:                             if ($putresult ne 'ok') {
 5644:                                 $error{'default'} =
 5645:                                     '<span class="LC_error">'.
 5646:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 5647:                             }
 5648:                         } else {
 5649:                             $error{'default'} = $error;
 5650:                         }
 5651:                     }
 5652:                 }
 5653:             }
 5654:         } else {
 5655:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
 5656:         }
 5657:     }
 5658:     if (ref($settings) eq 'HASH') {
 5659:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
 5660:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
 5661:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
 5662:                 $scantronurl = '';
 5663:             } else {
 5664:                 $scantronurl = $settings->{'scantronformat'};
 5665:             }
 5666:             $is_custom = 1;
 5667:         } else {
 5668:             $scantronurl = $scantronurls{'default'};
 5669:         }
 5670:     } else {
 5671:         if ($is_custom) {
 5672:             $scantronurl = $scantronurls{'custom'};
 5673:         } else {
 5674:             $scantronurl = $scantronurls{'default'};
 5675:         }
 5676:     }
 5677:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5678:     $datatable .= '<tr'.$css_class.'>';
 5679:     if (!$is_custom) {
 5680:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
 5681:                       '<span class="LC_nobreak">';
 5682:         if ($scantronurl) {
 5683:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
 5684:                                                          undef,undef,undef,undef,'background-color:#ffffff');
 5685:         } else {
 5686:             $datatable = &mt('File unavailable for display');
 5687:         }
 5688:         $datatable .= '</span></td>';
 5689:         if (keys(%error) == 0) { 
 5690:             $datatable .= '<td valign="bottom">';
 5691:             if (!$switchserver) {
 5692:                 $datatable .= &mt('Upload:').'<br />';
 5693:             }
 5694:         } else {
 5695:             my $errorstr;
 5696:             foreach my $key (sort(keys(%error))) {
 5697:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 5698:             }
 5699:             $datatable .= '<td>'.$errorstr;
 5700:         }
 5701:     } else {
 5702:         if (keys(%error) > 0) {
 5703:             my $errorstr;
 5704:             foreach my $key (sort(keys(%error))) {
 5705:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 5706:             } 
 5707:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
 5708:         } elsif ($scantronurl) {
 5709:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
 5710:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 5711:             $datatable .= '<td><span class="LC_nobreak">'.
 5712:                           $link.
 5713:                           '<label><input type="checkbox" name="scantronformat_del"'.
 5714:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
 5715:                           '<td><span class="LC_nobreak">&nbsp;'.
 5716:                           &mt('Replace:').'</span><br />';
 5717:         }
 5718:     }
 5719:     if (keys(%error) == 0) {
 5720:         if ($switchserver) {
 5721:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5722:         } else {
 5723:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 5724:                          '<input type="file" name="scantronformat" /></span>';
 5725:         }
 5726:     }
 5727:     $datatable .= '</td></tr>';
 5728:     $$rowtotal ++;
 5729:     return $datatable;
 5730: }
 5731: 
 5732: sub legacy_scantronformat {
 5733:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
 5734:     my ($url,$error);
 5735:     my @statinfo = &Apache::lonnet::stat_file($newurl);
 5736:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
 5737:         (my $result,$url) =
 5738:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
 5739:                          '','',$newfile);
 5740:         if ($result ne 'ok') {
 5741:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
 5742:         }
 5743:     }
 5744:     return ($url,$error);
 5745: }
 5746: 
 5747: sub print_coursecategories {
 5748:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
 5749:     my $datatable;
 5750:     if ($position eq 'top') {
 5751:         my (%checked);
 5752:         my @catitems = ('unauth','auth');
 5753:         my @cattypes = ('std','domonly','codesrch','none');
 5754:         $checked{'unauth'} = 'std';
 5755:         $checked{'auth'} = 'std';
 5756:         if (ref($settings) eq 'HASH') {
 5757:             foreach my $type (@cattypes) {
 5758:                 if ($type eq $settings->{'unauth'}) {
 5759:                     $checked{'unauth'} = $type;
 5760:                 }
 5761:                 if ($type eq $settings->{'auth'}) {
 5762:                     $checked{'auth'} = $type;
 5763:                 }
 5764:             }
 5765:         }
 5766:         my %lt = &Apache::lonlocal::texthash (
 5767:                                                unauth   => 'Catalog type for unauthenticated users',
 5768:                                                auth     => 'Catalog type for authenticated users',
 5769:                                                none     => 'No catalog',
 5770:                                                std      => 'Standard catalog',
 5771:                                                domonly  => 'Domain-only catalog',
 5772:                                                codesrch => "Code search form",
 5773:                                              );
 5774:        my $itemcount = 0;
 5775:        foreach my $item (@catitems) {
 5776:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 5777:            $datatable .= '<tr '.$css_class.'>'.
 5778:                          '<td>'.$lt{$item}.'</td>'.
 5779:                          '<td class="LC_right_item"><span class="LC_nobreak">';
 5780:            foreach my $type (@cattypes) {
 5781:                my $ischecked;
 5782:                if ($checked{$item} eq $type) {
 5783:                    $ischecked=' checked="checked"';
 5784:                }
 5785:                $datatable .= '<label>'.
 5786:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
 5787:                              ' />'.$lt{$type}.'</label>&nbsp;';
 5788:            }
 5789:            $datatable .= '</td></tr>';
 5790:            $itemcount ++;
 5791:         }
 5792:         $$rowtotal += $itemcount;
 5793:     } elsif ($position eq 'middle') {
 5794:         my $toggle_cats_crs = ' ';
 5795:         my $toggle_cats_dom = ' checked="checked" ';
 5796:         my $can_cat_crs = ' ';
 5797:         my $can_cat_dom = ' checked="checked" ';
 5798:         my $toggle_catscomm_comm = ' ';
 5799:         my $toggle_catscomm_dom = ' checked="checked" ';
 5800:         my $can_catcomm_comm = ' ';
 5801:         my $can_catcomm_dom = ' checked="checked" ';
 5802: 
 5803:         if (ref($settings) eq 'HASH') {
 5804:             if ($settings->{'togglecats'} eq 'crs') {
 5805:                 $toggle_cats_crs = $toggle_cats_dom;
 5806:                 $toggle_cats_dom = ' ';
 5807:             }
 5808:             if ($settings->{'categorize'} eq 'crs') {
 5809:                 $can_cat_crs = $can_cat_dom;
 5810:                 $can_cat_dom = ' ';
 5811:             }
 5812:             if ($settings->{'togglecatscomm'} eq 'comm') {
 5813:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
 5814:                 $toggle_catscomm_dom = ' ';
 5815:             }
 5816:             if ($settings->{'categorizecomm'} eq 'comm') {
 5817:                 $can_catcomm_comm = $can_catcomm_dom;
 5818:                 $can_catcomm_dom = ' ';
 5819:             }
 5820:         }
 5821:         my %title = &Apache::lonlocal::texthash (
 5822:                      togglecats     => 'Show/Hide a course in catalog',
 5823:                      togglecatscomm => 'Show/Hide a community in catalog',
 5824:                      categorize     => 'Assign a category to a course',
 5825:                      categorizecomm => 'Assign a category to a community',
 5826:                     );
 5827:         my %level = &Apache::lonlocal::texthash (
 5828:                      dom  => 'Set in Domain',
 5829:                      crs  => 'Set in Course',
 5830:                      comm => 'Set in Community',
 5831:                     );
 5832:         $datatable = '<tr class="LC_odd_row">'.
 5833:                   '<td>'.$title{'togglecats'}.'</td>'.
 5834:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 5835:                   '<input type="radio" name="togglecats"'.
 5836:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 5837:                   '<label><input type="radio" name="togglecats"'.
 5838:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
 5839:                   '</tr><tr>'.
 5840:                   '<td>'.$title{'categorize'}.'</td>'.
 5841:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 5842:                   '<label><input type="radio" name="categorize"'.
 5843:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 5844:                   '<label><input type="radio" name="categorize"'.
 5845:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
 5846:                   '</tr><tr class="LC_odd_row">'.
 5847:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
 5848:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 5849:                   '<input type="radio" name="togglecatscomm"'.
 5850:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 5851:                   '<label><input type="radio" name="togglecatscomm"'.
 5852:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
 5853:                   '</tr><tr>'.
 5854:                   '<td>'.$title{'categorizecomm'}.'</td>'.
 5855:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 5856:                   '<label><input type="radio" name="categorizecomm"'.
 5857:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 5858:                   '<label><input type="radio" name="categorizecomm"'.
 5859:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
 5860:                   '</tr>';
 5861:         $$rowtotal += 4;
 5862:     } else {
 5863:         my $css_class;
 5864:         my $itemcount = 1;
 5865:         my $cathash; 
 5866:         if (ref($settings) eq 'HASH') {
 5867:             $cathash = $settings->{'cats'};
 5868:         }
 5869:         if (ref($cathash) eq 'HASH') {
 5870:             my (@cats,@trails,%allitems,%idx,@jsarray);
 5871:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
 5872:                                                    \%allitems,\%idx,\@jsarray);
 5873:             my $maxdepth = scalar(@cats);
 5874:             my $colattrib = '';
 5875:             if ($maxdepth > 2) {
 5876:                 $colattrib = ' colspan="2" ';
 5877:             }
 5878:             my @path;
 5879:             if (@cats > 0) {
 5880:                 if (ref($cats[0]) eq 'ARRAY') {
 5881:                     my $numtop = @{$cats[0]};
 5882:                     my $maxnum = $numtop;
 5883:                     my %default_names = (
 5884:                           instcode    => &mt('Official courses'),
 5885:                           communities => &mt('Communities'),
 5886:                     );
 5887: 
 5888:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
 5889:                         ($cathash->{'instcode::0'} eq '') ||
 5890:                         (!grep(/^communities$/,@{$cats[0]})) || 
 5891:                         ($cathash->{'communities::0'} eq '')) {
 5892:                         $maxnum ++;
 5893:                     }
 5894:                     my $lastidx;
 5895:                     for (my $i=0; $i<$numtop; $i++) {
 5896:                         my $parent = $cats[0][$i];
 5897:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5898:                         my $item = &escape($parent).'::0';
 5899:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
 5900:                         $lastidx = $idx{$item};
 5901:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5902:                                       .'<select name="'.$item.'"'.$chgstr.'>';
 5903:                         for (my $k=0; $k<=$maxnum; $k++) {
 5904:                             my $vpos = $k+1;
 5905:                             my $selstr;
 5906:                             if ($k == $i) {
 5907:                                 $selstr = ' selected="selected" ';
 5908:                             }
 5909:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5910:                         }
 5911:                         $datatable .= '</select></span></td><td>';
 5912:                         if ($parent eq 'instcode' || $parent eq 'communities') {
 5913:                             $datatable .=  '<span class="LC_nobreak">'
 5914:                                            .$default_names{$parent}.'</span>';
 5915:                             if ($parent eq 'instcode') {
 5916:                                 $datatable .= '<br /><span class="LC_nobreak">('
 5917:                                               .&mt('with institutional codes')
 5918:                                               .')</span></td><td'.$colattrib.'>';
 5919:                             } else {
 5920:                                 $datatable .= '<table><tr><td>';
 5921:                             }
 5922:                             $datatable .= '<span class="LC_nobreak">'
 5923:                                           .'<label><input type="radio" name="'
 5924:                                           .$parent.'" value="1" checked="checked" />'
 5925:                                           .&mt('Display').'</label>';
 5926:                             if ($parent eq 'instcode') {
 5927:                                 $datatable .= '&nbsp;';
 5928:                             } else {
 5929:                                 $datatable .= '</span></td></tr><tr><td>'
 5930:                                               .'<span class="LC_nobreak">';
 5931:                             }
 5932:                             $datatable .= '<label><input type="radio" name="'
 5933:                                           .$parent.'" value="0" />'
 5934:                                           .&mt('Do not display').'</label></span>';
 5935:                             if ($parent eq 'communities') {
 5936:                                 $datatable .= '</td></tr></table>';
 5937:                             }
 5938:                             $datatable .= '</td>';
 5939:                         } else {
 5940:                             $datatable .= $parent
 5941:                                           .'&nbsp;<span class="LC_nobreak"><label>'
 5942:                                           .'<input type="checkbox" name="deletecategory" '
 5943:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
 5944:                         }
 5945:                         my $depth = 1;
 5946:                         push(@path,$parent);
 5947:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
 5948:                         pop(@path);
 5949:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 5950:                         $itemcount ++;
 5951:                     }
 5952:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5953:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
 5954:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
 5955:                     for (my $k=0; $k<=$maxnum; $k++) {
 5956:                         my $vpos = $k+1;
 5957:                         my $selstr;
 5958:                         if ($k == $numtop) {
 5959:                             $selstr = ' selected="selected" ';
 5960:                         }
 5961:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5962:                     }
 5963:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
 5964:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
 5965:                                   .'</tr>'."\n";
 5966:                     $itemcount ++;
 5967:                     foreach my $default ('instcode','communities') {
 5968:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
 5969:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5970:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
 5971:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
 5972:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
 5973:                             for (my $k=0; $k<=$maxnum; $k++) {
 5974:                                 my $vpos = $k+1;
 5975:                                 my $selstr;
 5976:                                 if ($k == $maxnum) {
 5977:                                     $selstr = ' selected="selected" ';
 5978:                                 }
 5979:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5980:                             }
 5981:                             $datatable .= '</select></span></td>'.
 5982:                                           '<td><span class="LC_nobreak">'.
 5983:                                           $default_names{$default}.'</span>';
 5984:                             if ($default eq 'instcode') {
 5985:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
 5986:                                               .&mt('with institutional codes').')</span>';
 5987:                             }
 5988:                             $datatable .= '</td>'
 5989:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
 5990:                                           .&mt('Display').'</label>&nbsp;'
 5991:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
 5992:                                           .&mt('Do not display').'</label></span></td></tr>';
 5993:                         }
 5994:                     }
 5995:                 }
 5996:             } else {
 5997:                 $datatable .= &initialize_categories($itemcount);
 5998:             }
 5999:         } else {
 6000:             $datatable .= '<td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td>'
 6001:                           .&initialize_categories($itemcount);
 6002:         }
 6003:         $$rowtotal += $itemcount;
 6004:     }
 6005:     return $datatable;
 6006: }
 6007: 
 6008: sub print_serverstatuses {
 6009:     my ($dom,$settings,$rowtotal) = @_;
 6010:     my $datatable;
 6011:     my @pages = &serverstatus_pages();
 6012:     my (%namedaccess,%machineaccess);
 6013:     foreach my $type (@pages) {
 6014:         $namedaccess{$type} = '';
 6015:         $machineaccess{$type}= '';
 6016:     }
 6017:     if (ref($settings) eq 'HASH') {
 6018:         foreach my $type (@pages) {
 6019:             if (exists($settings->{$type})) {
 6020:                 if (ref($settings->{$type}) eq 'HASH') {
 6021:                     foreach my $key (keys(%{$settings->{$type}})) {
 6022:                         if ($key eq 'namedusers') {
 6023:                             $namedaccess{$type} = $settings->{$type}->{$key};
 6024:                         } elsif ($key eq 'machines') {
 6025:                             $machineaccess{$type} = $settings->{$type}->{$key};
 6026:                         }
 6027:                     }
 6028:                 }
 6029:             }
 6030:         }
 6031:     }
 6032:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
 6033:     my $rownum = 0;
 6034:     my $css_class;
 6035:     foreach my $type (@pages) {
 6036:         $rownum ++;
 6037:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 6038:         $datatable .= '<tr'.$css_class.'>'.
 6039:                       '<td><span class="LC_nobreak">'.
 6040:                       $titles->{$type}.'</span></td>'.
 6041:                       '<td class="LC_left_item">'.
 6042:                       '<input type="text" name="'.$type.'_namedusers" '.
 6043:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
 6044:                       '<td class="LC_right_item">'.
 6045:                       '<span class="LC_nobreak">'.
 6046:                       '<input type="text" name="'.$type.'_machines" '.
 6047:                       'value="'.$machineaccess{$type}.'" size="10" />'.
 6048:                       '</td></tr>'."\n";
 6049:     }
 6050:     $$rowtotal += $rownum;
 6051:     return $datatable;
 6052: }
 6053: 
 6054: sub serverstatus_pages {
 6055:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
 6056:             'checksums','clusterstatus','metadata_keywords','metadata_harvest',
 6057:             'takeoffline','takeonline','showenv','toggledebug','ping','domconf',
 6058:             'uniquecodes','diskusage','coursecatalog');
 6059: }
 6060: 
 6061: sub defaults_javascript {
 6062:     my ($settings) = @_;
 6063:     return unless (ref($settings) eq 'HASH');
 6064:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 6065:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
 6066:         if ($maxnum eq '') {
 6067:             $maxnum = 0;
 6068:         }
 6069:         $maxnum ++;
 6070:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
 6071:         return <<"ENDSCRIPT";
 6072: <script type="text/javascript">
 6073: // <![CDATA[
 6074: function reorderTypes(form,caller) {
 6075:     var changedVal;
 6076: $jstext 
 6077:     var newpos = 'addinststatus_pos';
 6078:     var current = new Array;
 6079:     var maxh = $maxnum;
 6080:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 6081:     var oldVal;
 6082:     if (caller == newpos) {
 6083:         changedVal = newitemVal;
 6084:     } else {
 6085:         var curritem = 'inststatus_pos_'+caller;
 6086:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
 6087:         current[newitemVal] = newpos;
 6088:     }
 6089:     for (var i=0; i<inststatuses.length; i++) {
 6090:         if (inststatuses[i] != caller) {
 6091:             var elementName = 'inststatus_pos_'+inststatuses[i];
 6092:             if (form.elements[elementName]) {
 6093:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 6094:                 current[currVal] = elementName;
 6095:             }
 6096:         }
 6097:     }
 6098:     for (var j=0; j<maxh; j++) {
 6099:         if (current[j] == undefined) {
 6100:             oldVal = j;
 6101:         }
 6102:     }
 6103:     if (oldVal < changedVal) {
 6104:         for (var k=oldVal+1; k<=changedVal ; k++) {
 6105:            var elementName = current[k];
 6106:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 6107:         }
 6108:     } else {
 6109:         for (var k=changedVal; k<oldVal; k++) {
 6110:             var elementName = current[k];
 6111:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 6112:         }
 6113:     }
 6114:     return;
 6115: }
 6116: 
 6117: // ]]>
 6118: </script>
 6119: 
 6120: ENDSCRIPT
 6121:     }
 6122: }
 6123: 
 6124: sub coursecategories_javascript {
 6125:     my ($settings) = @_;
 6126:     my ($output,$jstext,$cathash);
 6127:     if (ref($settings) eq 'HASH') {
 6128:         $cathash = $settings->{'cats'};
 6129:     }
 6130:     if (ref($cathash) eq 'HASH') {
 6131:         my (@cats,@jsarray,%idx);
 6132:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
 6133:         if (@jsarray > 0) {
 6134:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
 6135:             for (my $i=0; $i<@jsarray; $i++) {
 6136:                 if (ref($jsarray[$i]) eq 'ARRAY') {
 6137:                     my $catstr = join('","',@{$jsarray[$i]});
 6138:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
 6139:                 }
 6140:             }
 6141:         }
 6142:     } else {
 6143:         $jstext  = '    var categories = Array(1);'."\n".
 6144:                    '    categories[0] = Array("instcode_pos");'."\n"; 
 6145:     }
 6146:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
 6147:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
 6148:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
 6149:     &js_escape(\$instcode_reserved);
 6150:     &js_escape(\$communities_reserved);
 6151:     &js_escape(\$choose_again);
 6152:     $output = <<"ENDSCRIPT";
 6153: <script type="text/javascript">
 6154: // <![CDATA[
 6155: function reorderCats(form,parent,item,idx) {
 6156:     var changedVal;
 6157: $jstext
 6158:     var newpos = 'addcategory_pos';
 6159:     if (parent == '') {
 6160:         var has_instcode = 0;
 6161:         var maxtop = categories[idx].length;
 6162:         for (var j=0; j<maxtop; j++) {
 6163:             if (categories[idx][j] == 'instcode::0') {
 6164:                 has_instcode == 1;
 6165:             }
 6166:         }
 6167:         if (has_instcode == 0) {
 6168:             categories[idx][maxtop] = 'instcode_pos';
 6169:         }
 6170:     } else {
 6171:         newpos += '_'+parent;
 6172:     }
 6173:     var maxh = 1 + categories[idx].length;
 6174:     var current = new Array;
 6175:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 6176:     if (item == newpos) {
 6177:         changedVal = newitemVal;
 6178:     } else {
 6179:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 6180:         current[newitemVal] = newpos;
 6181:     }
 6182:     for (var i=0; i<categories[idx].length; i++) {
 6183:         var elementName = categories[idx][i];
 6184:         if (elementName != item) {
 6185:             if (form.elements[elementName]) {
 6186:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 6187:                 current[currVal] = elementName;
 6188:             }
 6189:         }
 6190:     }
 6191:     var oldVal;
 6192:     for (var j=0; j<maxh; j++) {
 6193:         if (current[j] == undefined) {
 6194:             oldVal = j;
 6195:         }
 6196:     }
 6197:     if (oldVal < changedVal) {
 6198:         for (var k=oldVal+1; k<=changedVal ; k++) {
 6199:            var elementName = current[k];
 6200:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 6201:         }
 6202:     } else {
 6203:         for (var k=changedVal; k<oldVal; k++) {
 6204:             var elementName = current[k];
 6205:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 6206:         }
 6207:     }
 6208:     return;
 6209: }
 6210: 
 6211: function categoryCheck(form) {
 6212:     if (form.elements['addcategory_name'].value == 'instcode') {
 6213:         alert('$instcode_reserved\\n$choose_again');
 6214:         return false;
 6215:     }
 6216:     if (form.elements['addcategory_name'].value == 'communities') {
 6217:         alert('$communities_reserved\\n$choose_again');
 6218:         return false;
 6219:     }
 6220:     return true;
 6221: }
 6222: 
 6223: // ]]>
 6224: </script>
 6225: 
 6226: ENDSCRIPT
 6227:     return $output;
 6228: }
 6229: 
 6230: sub initialize_categories {
 6231:     my ($itemcount) = @_;
 6232:     my ($datatable,$css_class,$chgstr);
 6233:     my %default_names = (
 6234:                       instcode    => 'Official courses (with institutional codes)',
 6235:                       communities => 'Communities',
 6236:                         );
 6237:     my $select0 = ' selected="selected"';
 6238:     my $select1 = '';
 6239:     foreach my $default ('instcode','communities') {
 6240:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6241:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'',$default"."_pos','0'".');"';
 6242:         if ($default eq 'communities') {
 6243:             $select1 = $select0;
 6244:             $select0 = '';
 6245:         }
 6246:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 6247:                      .'<select name="'.$default.'_pos">'
 6248:                      .'<option value="0"'.$select0.'>1</option>'
 6249:                      .'<option value="1"'.$select1.'>2</option>'
 6250:                      .'<option value="2">3</option></select>&nbsp;'
 6251:                      .$default_names{$default}
 6252:                      .'</span></td><td><span class="LC_nobreak">'
 6253:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
 6254:                      .&mt('Display').'</label>&nbsp;<label>'
 6255:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
 6256:                  .'</label></span></td></tr>';
 6257:         $itemcount ++;
 6258:     }
 6259:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6260:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
 6261:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 6262:                   .'<select name="addcategory_pos"'.$chgstr.'>'
 6263:                   .'<option value="0">1</option>'
 6264:                   .'<option value="1">2</option>'
 6265:                   .'<option value="2" selected="selected">3</option></select>&nbsp;'
 6266:                   .&mt('Add category').'</td><td>'.&mt('Name:')
 6267:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></td></tr>';
 6268:     return $datatable;
 6269: }
 6270: 
 6271: sub build_category_rows {
 6272:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
 6273:     my ($text,$name,$item,$chgstr);
 6274:     if (ref($cats) eq 'ARRAY') {
 6275:         my $maxdepth = scalar(@{$cats});
 6276:         if (ref($cats->[$depth]) eq 'HASH') {
 6277:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 6278:                 my $numchildren = @{$cats->[$depth]{$parent}};
 6279:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6280:                 $text .= '<td><table class="LC_data_table">';
 6281:                 my ($idxnum,$parent_name,$parent_item);
 6282:                 my $higher = $depth - 1;
 6283:                 if ($higher == 0) {
 6284:                     $parent_name = &escape($parent).'::'.$higher;
 6285:                 } else {
 6286:                     if (ref($path) eq 'ARRAY') {
 6287:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 6288:                     }
 6289:                 }
 6290:                 $parent_item = 'addcategory_pos_'.$parent_name;
 6291:                 for (my $j=0; $j<=$numchildren; $j++) {
 6292:                     if ($j < $numchildren) {
 6293:                         $name = $cats->[$depth]{$parent}[$j];
 6294:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
 6295:                         $idxnum = $idx->{$item};
 6296:                     } else {
 6297:                         $name = $parent_name;
 6298:                         $item = $parent_item;
 6299:                     }
 6300:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
 6301:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
 6302:                     for (my $i=0; $i<=$numchildren; $i++) {
 6303:                         my $vpos = $i+1;
 6304:                         my $selstr;
 6305:                         if ($j == $i) {
 6306:                             $selstr = ' selected="selected" ';
 6307:                         }
 6308:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
 6309:                     }
 6310:                     $text .= '</select>&nbsp;';
 6311:                     if ($j < $numchildren) {
 6312:                         my $deeper = $depth+1;
 6313:                         $text .= $name.'&nbsp;'
 6314:                                  .'<label><input type="checkbox" name="deletecategory" value="'
 6315:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
 6316:                         if(ref($path) eq 'ARRAY') {
 6317:                             push(@{$path},$name);
 6318:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
 6319:                             pop(@{$path});
 6320:                         }
 6321:                     } else {
 6322:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="textbox" size="20" name="addcategory_name_';
 6323:                         if ($j == $numchildren) {
 6324:                             $text .= $name;
 6325:                         } else {
 6326:                             $text .= $item;
 6327:                         }
 6328:                         $text .= '" value="" />';
 6329:                     }
 6330:                     $text .= '</td></tr>';
 6331:                 }
 6332:                 $text .= '</table></td>';
 6333:             } else {
 6334:                 my $higher = $depth-1;
 6335:                 if ($higher == 0) {
 6336:                     $name = &escape($parent).'::'.$higher;
 6337:                 } else {
 6338:                     if (ref($path) eq 'ARRAY') {
 6339:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 6340:                     }
 6341:                 }
 6342:                 my $colspan;
 6343:                 if ($parent ne 'instcode') {
 6344:                     $colspan = $maxdepth - $depth - 1;
 6345:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="textbox" size="20" name="subcat_'.$name.'" value="" /></td>';
 6346:                 }
 6347:             }
 6348:         }
 6349:     }
 6350:     return $text;
 6351: }
 6352: 
 6353: sub modifiable_userdata_row {
 6354:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref) = @_;
 6355:     my ($role,$rolename,$statustype);
 6356:     $role = $item;
 6357:     if ($context eq 'cancreate') {
 6358:         if ($item =~ /^emailusername_(.+)$/) {
 6359:             $statustype = $1;
 6360:             $role = 'emailusername';
 6361:             if (ref($usertypes) eq 'HASH') {
 6362:                 if ($usertypes->{$statustype}) {
 6363:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
 6364:                 } else {
 6365:                     $rolename = &mt('Data provided by user');
 6366:                 }
 6367:             }
 6368:         }
 6369:     } elsif ($context eq 'selfcreate') {
 6370:         if (ref($usertypes) eq 'HASH') {
 6371:             $rolename = $usertypes->{$role};
 6372:         } else {
 6373:             $rolename = $role;
 6374:         }
 6375:     } else {
 6376:         if ($role eq 'cr') {
 6377:             $rolename = &mt('Custom role');
 6378:         } else {
 6379:             $rolename = &Apache::lonnet::plaintext($role);
 6380:         }
 6381:     }
 6382:     my (@fields,%fieldtitles);
 6383:     if (ref($fieldsref) eq 'ARRAY') {
 6384:         @fields = @{$fieldsref};
 6385:     } else {
 6386:         @fields = ('lastname','firstname','middlename','generation',
 6387:                    'permanentemail','id');
 6388:     }
 6389:     if ((ref($titlesref) eq 'HASH')) {
 6390:         %fieldtitles = %{$titlesref};
 6391:     } else {
 6392:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 6393:     }
 6394:     my $output;
 6395:     my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 6396:     $output = '<tr '.$css_class.'>'.
 6397:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
 6398:               '<td class="LC_left_item" colspan="2"><table>';
 6399:     my $rem;
 6400:     my %checks;
 6401:     if (ref($settings) eq 'HASH') {
 6402:         if (ref($settings->{$context}) eq 'HASH') {
 6403:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
 6404:                 my $hashref = $settings->{$context}->{$role};
 6405:                 if ($role eq 'emailusername') {
 6406:                     if ($statustype) {
 6407:                         if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
 6408:                             $hashref = $settings->{$context}->{$role}->{$statustype};
 6409:                             if (ref($hashref) eq 'HASH') { 
 6410:                                 foreach my $field (@fields) {
 6411:                                     if ($hashref->{$field}) {
 6412:                                         $checks{$field} = $hashref->{$field};
 6413:                                     }
 6414:                                 }
 6415:                             }
 6416:                         }
 6417:                     }
 6418:                 } else {
 6419:                     if (ref($hashref) eq 'HASH') {
 6420:                         foreach my $field (@fields) {
 6421:                             if ($hashref->{$field}) {
 6422:                                 $checks{$field} = ' checked="checked" ';
 6423:                             }
 6424:                         }
 6425:                     }
 6426:                 }
 6427:             }
 6428:         }
 6429:     }
 6430:      
 6431:     for (my $i=0; $i<@fields; $i++) {
 6432:         my $rem = $i%($numinrow);
 6433:         if ($rem == 0) {
 6434:             if ($i > 0) {
 6435:                 $output .= '</tr>';
 6436:             }
 6437:             $output .= '<tr>';
 6438:         }
 6439:         my $check = ' ';
 6440:         unless ($role eq 'emailusername') {
 6441:             if (exists($checks{$fields[$i]})) {
 6442:                 $check = $checks{$fields[$i]}
 6443:             } else {
 6444:                 if ($role eq 'st') {
 6445:                     if (ref($settings) ne 'HASH') {
 6446:                         $check = ' checked="checked" '; 
 6447:                     }
 6448:                 }
 6449:             }
 6450:         }
 6451:         $output .= '<td class="LC_left_item">'.
 6452:                    '<span class="LC_nobreak">';
 6453:         if ($role eq 'emailusername') {
 6454:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
 6455:                 $checks{$fields[$i]} = 'omit';
 6456:             }
 6457:             foreach my $option ('required','optional','omit') {
 6458:                 my $checked='';
 6459:                 if ($checks{$fields[$i]} eq $option) {
 6460:                     $checked='checked="checked" ';
 6461:                 }
 6462:                 $output .= '<label>'.
 6463:                            '<input type="radio" name="canmodify_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
 6464:                            &mt($option).'</label>'.('&nbsp;' x2);
 6465:             }
 6466:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
 6467:         } else {
 6468:             $output .= '<label>'.
 6469:                        '<input type="checkbox" name="canmodify_'.$role.'" '.
 6470:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
 6471:                        '</label>';
 6472:         }
 6473:         $output .= '</span></td>';
 6474:         $rem = @fields%($numinrow);
 6475:     }
 6476:     my $colsleft = $numinrow - $rem;
 6477:     if ($colsleft > 1 ) {
 6478:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6479:                    '&nbsp;</td>';
 6480:     } elsif ($colsleft == 1) {
 6481:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 6482:     }
 6483:     $output .= '</tr></table></td></tr>';
 6484:     return $output;
 6485: }
 6486: 
 6487: sub insttypes_row {
 6488:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rownum) = @_;
 6489:     my %lt = &Apache::lonlocal::texthash (
 6490:                       cansearch => 'Users allowed to search',
 6491:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
 6492:                       lockablenames => 'User preference to lock name',
 6493:              );
 6494:     my $showdom;
 6495:     if ($context eq 'cansearch') {
 6496:         $showdom = ' ('.$dom.')';
 6497:     }
 6498:     my $class = 'LC_left_item';
 6499:     if ($context eq 'statustocreate') {
 6500:         $class = 'LC_right_item';
 6501:     }
 6502:     my $css_class = ' class="LC_odd_row"';
 6503:     if ($rownum ne '') { 
 6504:         $css_class = ($rownum%2? ' class="LC_odd_row"':'');
 6505:     }
 6506:     my $output = '<tr'.$css_class.'>'.
 6507:                  '<td>'.$lt{$context}.$showdom.
 6508:                  '</td><td class="'.$class.'" colspan="2"><table>';
 6509:     my $rem;
 6510:     if (ref($types) eq 'ARRAY') {
 6511:         for (my $i=0; $i<@{$types}; $i++) {
 6512:             if (defined($usertypes->{$types->[$i]})) {
 6513:                 my $rem = $i%($numinrow);
 6514:                 if ($rem == 0) {
 6515:                     if ($i > 0) {
 6516:                         $output .= '</tr>';
 6517:                     }
 6518:                     $output .= '<tr>';
 6519:                 }
 6520:                 my $check = ' ';
 6521:                 if (ref($settings) eq 'HASH') {
 6522:                     if (ref($settings->{$context}) eq 'ARRAY') {
 6523:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
 6524:                             $check = ' checked="checked" ';
 6525:                         }
 6526:                     } elsif ($context eq 'statustocreate') {
 6527:                         $check = ' checked="checked" ';
 6528:                     }
 6529:                 }
 6530:                 $output .= '<td class="LC_left_item">'.
 6531:                            '<span class="LC_nobreak"><label>'.
 6532:                            '<input type="checkbox" name="'.$context.'" '.
 6533:                            'value="'.$types->[$i].'"'.$check.'/>'.
 6534:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 6535:             }
 6536:         }
 6537:         $rem = @{$types}%($numinrow);
 6538:     }
 6539:     my $colsleft = $numinrow - $rem;
 6540:     if (($rem == 0) && (@{$types} > 0)) {
 6541:         $output .= '<tr>';
 6542:     }
 6543:     if ($colsleft > 1) {
 6544:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6545:     } else {
 6546:         $output .= '<td class="LC_left_item">';
 6547:     }
 6548:     my $defcheck = ' ';
 6549:     if (ref($settings) eq 'HASH') {  
 6550:         if (ref($settings->{$context}) eq 'ARRAY') {
 6551:             if (grep(/^default$/,@{$settings->{$context}})) {
 6552:                 $defcheck = ' checked="checked" ';
 6553:             }
 6554:         } elsif ($context eq 'statustocreate') {
 6555:             $defcheck = ' checked="checked" ';
 6556:         }
 6557:     }
 6558:     $output .= '<span class="LC_nobreak"><label>'.
 6559:                '<input type="checkbox" name="'.$context.'" '.
 6560:                'value="default"'.$defcheck.'/>'.
 6561:                $othertitle.'</label></span></td>'.
 6562:                '</tr></table></td></tr>';
 6563:     return $output;
 6564: }
 6565: 
 6566: sub sorted_searchtitles {
 6567:     my %searchtitles = &Apache::lonlocal::texthash(
 6568:                          'uname' => 'username',
 6569:                          'lastname' => 'last name',
 6570:                          'lastfirst' => 'last name, first name',
 6571:                      );
 6572:     my @titleorder = ('uname','lastname','lastfirst');
 6573:     return (\%searchtitles,\@titleorder);
 6574: }
 6575: 
 6576: sub sorted_searchtypes {
 6577:     my %srchtypes_desc = (
 6578:                            exact    => 'is exact match',
 6579:                            contains => 'contains ..',
 6580:                            begins   => 'begins with ..',
 6581:                          );
 6582:     my @srchtypeorder = ('exact','begins','contains');
 6583:     return (\%srchtypes_desc,\@srchtypeorder);
 6584: }
 6585: 
 6586: sub usertype_update_row {
 6587:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
 6588:     my $datatable;
 6589:     my $numinrow = 4;
 6590:     foreach my $type (@{$types}) {
 6591:         if (defined($usertypes->{$type})) {
 6592:             $$rownums ++;
 6593:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
 6594:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
 6595:                           '</td><td class="LC_left_item"><table>';
 6596:             for (my $i=0; $i<@{$fields}; $i++) {
 6597:                 my $rem = $i%($numinrow);
 6598:                 if ($rem == 0) {
 6599:                     if ($i > 0) {
 6600:                         $datatable .= '</tr>';
 6601:                     }
 6602:                     $datatable .= '<tr>';
 6603:                 }
 6604:                 my $check = ' ';
 6605:                 if (ref($settings) eq 'HASH') {
 6606:                     if (ref($settings->{'fields'}) eq 'HASH') {
 6607:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
 6608:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
 6609:                                 $check = ' checked="checked" ';
 6610:                             }
 6611:                         }
 6612:                     }
 6613:                 }
 6614: 
 6615:                 if ($i == @{$fields}-1) {
 6616:                     my $colsleft = $numinrow - $rem;
 6617:                     if ($colsleft > 1) {
 6618:                         $datatable .= '<td colspan="'.$colsleft.'">';
 6619:                     } else {
 6620:                         $datatable .= '<td>';
 6621:                     }
 6622:                 } else {
 6623:                     $datatable .= '<td>';
 6624:                 }
 6625:                 $datatable .= '<span class="LC_nobreak"><label>'.
 6626:                               '<input type="checkbox" name="updateable_'.$type.
 6627:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
 6628:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
 6629:             }
 6630:             $datatable .= '</tr></table></td></tr>';
 6631:         }
 6632:     }
 6633:     return $datatable;
 6634: }
 6635: 
 6636: sub modify_login {
 6637:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
 6638:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
 6639:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon);
 6640:     %title = ( coursecatalog => 'Display course catalog',
 6641:                adminmail => 'Display administrator E-mail address',
 6642:                helpdesk  => 'Display "Contact Helpdesk" link',
 6643:                newuser => 'Link for visitors to create a user account',
 6644:                loginheader => 'Log-in box header');
 6645:     @offon = ('off','on');
 6646:     if (ref($domconfig{login}) eq 'HASH') {
 6647:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
 6648:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
 6649:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
 6650:             }
 6651:         }
 6652:     }
 6653:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
 6654:                                            \%domconfig,\%loginhash);
 6655:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 6656:     foreach my $item (@toggles) {
 6657:         $loginhash{login}{$item} = $env{'form.'.$item};
 6658:     }
 6659:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
 6660:     if (ref($colchanges{'login'}) eq 'HASH') {  
 6661:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
 6662:                                          \%loginhash);
 6663:     }
 6664: 
 6665:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 6666:     my %domservers = &Apache::lonnet::get_servers($dom);
 6667:     my @loginvia_attribs = ('serverpath','custompath','exempt');
 6668:     if (keys(%servers) > 1) {
 6669:         foreach my $lonhost (keys(%servers)) {
 6670:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
 6671:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
 6672:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
 6673:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
 6674:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
 6675:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 6676:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 6677:                         $changes{'loginvia'}{$lonhost} = 1;
 6678:                     } else {
 6679:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
 6680:                         $changes{'loginvia'}{$lonhost} = 1;
 6681:                     }
 6682:                 } else {
 6683:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 6684:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 6685:                         $changes{'loginvia'}{$lonhost} = 1;
 6686:                     }
 6687:                 }
 6688:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
 6689:                     foreach my $item (@loginvia_attribs) {
 6690:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
 6691:                     }
 6692:                 } else {
 6693:                     foreach my $item (@loginvia_attribs) {
 6694:                         my $new = $env{'form.'.$lonhost.'_'.$item};
 6695:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
 6696:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
 6697:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
 6698:                                 $new = '/';
 6699:                             }
 6700:                         }
 6701:                         if (($item eq 'custompath') && 
 6702:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
 6703:                             $new = '';
 6704:                         }
 6705:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
 6706:                             $changes{'loginvia'}{$lonhost} = 1;
 6707:                         }
 6708:                         if ($item eq 'exempt') {
 6709:                             $new = &check_exempt_addresses($new);
 6710:                         }
 6711:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
 6712:                     }
 6713:                 }
 6714:             } else {
 6715:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 6716:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 6717:                     $changes{'loginvia'}{$lonhost} = 1;
 6718:                     foreach my $item (@loginvia_attribs) {
 6719:                         my $new = $env{'form.'.$lonhost.'_'.$item};
 6720:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
 6721:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
 6722:                                 $new = '/';
 6723:                             }
 6724:                         }
 6725:                         if (($item eq 'custompath') && 
 6726:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
 6727:                             $new = '';
 6728:                         }
 6729:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
 6730:                     }
 6731:                 }
 6732:             }
 6733:         }
 6734:     }
 6735: 
 6736:     my $servadm = $r->dir_config('lonAdmEMail');
 6737:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 6738:     if (ref($domconfig{'login'}) eq 'HASH') {
 6739:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
 6740:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
 6741:                 if ($lang eq 'nolang') {
 6742:                     push(@currlangs,$lang);
 6743:                 } elsif (defined($langchoices{$lang})) {
 6744:                     push(@currlangs,$lang);
 6745:                 } else {
 6746:                     next;
 6747:                 }
 6748:             }
 6749:         }
 6750:     }
 6751:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
 6752:     if (@currlangs > 0) {
 6753:         foreach my $lang (@currlangs) {
 6754:             if (grep(/^\Q$lang\E$/,@delurls)) {
 6755:                 $changes{'helpurl'}{$lang} = 1;
 6756:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
 6757:                 $changes{'helpurl'}{$lang} = 1;
 6758:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
 6759:                 push(@newlangs,$lang);
 6760:             } else {
 6761:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
 6762:             }
 6763:         }
 6764:     }
 6765:     unless (grep(/^nolang$/,@currlangs)) {
 6766:         if ($env{'form.loginhelpurl_nolang.filename'}) {
 6767:             $changes{'helpurl'}{'nolang'} = 1;
 6768:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
 6769:             push(@newlangs,'nolang');
 6770:         }
 6771:     }
 6772:     if ($env{'form.loginhelpurl_add_lang'}) {
 6773:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
 6774:             ($env{'form.loginhelpurl_add_file.filename'})) {
 6775:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
 6776:             $addedfile = $env{'form.loginhelpurl_add_lang'};
 6777:         }
 6778:     }
 6779:     if ((@newlangs > 0) || ($addedfile)) {
 6780:         my $error;
 6781:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 6782:         if ($configuserok eq 'ok') {
 6783:             if ($switchserver) {
 6784:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
 6785:             } elsif ($author_ok eq 'ok') {
 6786:                 my @allnew = @newlangs;
 6787:                 if ($addedfile ne '') {
 6788:                     push(@allnew,$addedfile);
 6789:                 }
 6790:                 foreach my $lang (@allnew) {
 6791:                     my $formelem = 'loginhelpurl_'.$lang;
 6792:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
 6793:                         $formelem = 'loginhelpurl_add_file';
 6794:                     }
 6795:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 6796:                                                                "help/$lang",'','',$newfile{$lang});
 6797:                     if ($result eq 'ok') {
 6798:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
 6799:                         $changes{'helpurl'}{$lang} = 1;
 6800:                     } else {
 6801:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
 6802:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 6803:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
 6804:                             (!grep(/^\Q$lang\E$/,@delurls))) {
 6805:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
 6806:                         }
 6807:                     }
 6808:                 }
 6809:             } else {
 6810:                 $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);
 6811:             }
 6812:         } else {
 6813:             $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);
 6814:         }
 6815:         if ($error) {
 6816:             &Apache::lonnet::logthis($error);
 6817:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 6818:         }
 6819:     }
 6820: 
 6821:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
 6822:     if (ref($domconfig{'login'}) eq 'HASH') {
 6823:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
 6824:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
 6825:                 if ($domservers{$lonhost}) {
 6826:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
 6827:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
 6828:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
 6829:                     }
 6830:                 }
 6831:             }
 6832:         }
 6833:     }
 6834:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
 6835:     foreach my $lonhost (sort(keys(%domservers))) {
 6836:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
 6837:             $changes{'headtag'}{$lonhost} = 1;
 6838:         } else {
 6839:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
 6840:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
 6841:             }
 6842:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
 6843:                 push(@newhosts,$lonhost);
 6844:             } elsif ($currheadtagurls{$lonhost}) {
 6845:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
 6846:                 if ($currexempt{$lonhost}) {
 6847:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
 6848:                         $changes{'headtag'}{$lonhost} = 1;
 6849:                     }
 6850:                 } elsif ($possexempt{$lonhost}) {
 6851:                     $changes{'headtag'}{$lonhost} = 1;
 6852:                 }
 6853:                 if ($possexempt{$lonhost}) {
 6854:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
 6855:                 }
 6856:             }
 6857:         }
 6858:     }
 6859:     if (@newhosts) {
 6860:         my $error;
 6861:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 6862:         if ($configuserok eq 'ok') {
 6863:             if ($switchserver) {
 6864:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
 6865:             } elsif ($author_ok eq 'ok') {
 6866:                 foreach my $lonhost (@newhosts) {
 6867:                     my $formelem = 'loginheadtag_'.$lonhost;
 6868:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 6869:                                                                           "login/headtag/$lonhost",'','',
 6870:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
 6871:                     if ($result eq 'ok') {
 6872:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
 6873:                         $changes{'headtag'}{$lonhost} = 1;
 6874:                         if ($possexempt{$lonhost}) {
 6875:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
 6876:                         }
 6877:                     } else {
 6878:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
 6879:                                            $newheadtagurls{$lonhost},$result);
 6880:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 6881:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
 6882:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
 6883:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
 6884:                         }
 6885:                     }
 6886:                 }
 6887:             } else {
 6888:                 $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);
 6889:             }
 6890:         } else {
 6891:             $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);
 6892:         }
 6893:         if ($error) {
 6894:             &Apache::lonnet::logthis($error);
 6895:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 6896:         }
 6897:     }
 6898:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
 6899: 
 6900:     my $defaulthelpfile = '/adm/loginproblems.html';
 6901:     my $defaulttext = &mt('Default in use');
 6902: 
 6903:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
 6904:                                              $dom);
 6905:     if ($putresult eq 'ok') {
 6906:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 6907:         my %defaultchecked = (
 6908:                     'coursecatalog' => 'on',
 6909:                     'helpdesk'      => 'on',
 6910:                     'adminmail'     => 'off',
 6911:                     'newuser'       => 'off',
 6912:         );
 6913:         if (ref($domconfig{'login'}) eq 'HASH') {
 6914:             foreach my $item (@toggles) {
 6915:                 if ($defaultchecked{$item} eq 'on') { 
 6916:                     if (($domconfig{'login'}{$item} eq '0') &&
 6917:                         ($env{'form.'.$item} eq '1')) {
 6918:                         $changes{$item} = 1;
 6919:                     } elsif (($domconfig{'login'}{$item} eq '' ||
 6920:                               $domconfig{'login'}{$item} eq '1') &&
 6921:                              ($env{'form.'.$item} eq '0')) {
 6922:                         $changes{$item} = 1;
 6923:                     }
 6924:                 } elsif ($defaultchecked{$item} eq 'off') {
 6925:                     if (($domconfig{'login'}{$item} eq '1') &&
 6926:                         ($env{'form.'.$item} eq '0')) {
 6927:                         $changes{$item} = 1;
 6928:                     } elsif (($domconfig{'login'}{$item} eq '' ||
 6929:                               $domconfig{'login'}{$item} eq '0') &&
 6930:                              ($env{'form.'.$item} eq '1')) {
 6931:                         $changes{$item} = 1;
 6932:                     }
 6933:                 }
 6934:             }
 6935:         }
 6936:         if (keys(%changes) > 0 || $colchgtext) {
 6937:             &Apache::loncommon::devalidate_domconfig_cache($dom);
 6938:             if (ref($lastactref) eq 'HASH') {
 6939:                 $lastactref->{'domainconfig'} = 1;
 6940:             }
 6941:             $resulttext = &mt('Changes made:').'<ul>';
 6942:             foreach my $item (sort(keys(%changes))) {
 6943:                 if ($item eq 'loginvia') {
 6944:                     if (ref($changes{$item}) eq 'HASH') {
 6945:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
 6946:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
 6947:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
 6948:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
 6949:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
 6950:                                     $protocol = 'http' if ($protocol ne 'https');
 6951:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
 6952: 
 6953:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
 6954:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
 6955:                                     } else {
 6956:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
 6957:                                     }
 6958:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
 6959:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
 6960:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
 6961:                                     }
 6962:                                     $resulttext .= '</li>';
 6963:                                 } else {
 6964:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
 6965:                                 }
 6966:                             } else {
 6967:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
 6968:                             }
 6969:                         }
 6970:                         $resulttext .= '</ul></li>';
 6971:                     }
 6972:                 } elsif ($item eq 'helpurl') {
 6973:                     if (ref($changes{$item}) eq 'HASH') {
 6974:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
 6975:                             if (grep(/^\Q$lang\E$/,@delurls)) {
 6976:                                 my ($chg,$link);
 6977:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
 6978:                                 if ($lang eq 'nolang') {
 6979:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
 6980:                                 } else {
 6981:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
 6982:                                 }
 6983:                                 $resulttext .= '<li>'.$chg.'</li>';
 6984:                             } else {
 6985:                                 my $chg;
 6986:                                 if ($lang eq 'nolang') {
 6987:                                     $chg = &mt('custom log-in help file for no preferred language');
 6988:                                 } else {
 6989:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
 6990:                                 }
 6991:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
 6992:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
 6993:                                                       '?inhibitmenu=yes',$chg,600,500).
 6994:                                                '</li>';
 6995:                             }
 6996:                         }
 6997:                     }
 6998:                 } elsif ($item eq 'headtag') {
 6999:                     if (ref($changes{$item}) eq 'HASH') {
 7000:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
 7001:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
 7002:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
 7003:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
 7004:                                 $resulttext .= '<li><a href="'.
 7005:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
 7006:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 7007:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
 7008:                                 if ($possexempt{$lonhost}) {
 7009:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
 7010:                                 } else {
 7011:                                     $resulttext .= &mt('included for any client IP');
 7012:                                 }
 7013:                                 $resulttext .= '</li>';
 7014:                             }
 7015:                         }
 7016:                     }
 7017:                 } elsif ($item eq 'captcha') {
 7018:                     if (ref($loginhash{'login'}) eq 'HASH') {
 7019:                         my $chgtxt;
 7020:                         if ($loginhash{'login'}{$item} eq 'notused') {
 7021:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
 7022:                         } else {
 7023:                             my %captchas = &captcha_phrases();
 7024:                             if ($captchas{$loginhash{'login'}{$item}}) {
 7025:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
 7026:                             } else {
 7027:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
 7028:                             }
 7029:                         }
 7030:                         $resulttext .= '<li>'.$chgtxt.'</li>';
 7031:                     }
 7032:                 } elsif ($item eq 'recaptchakeys') {
 7033:                     if (ref($loginhash{'login'}) eq 'HASH') {
 7034:                         my ($privkey,$pubkey);
 7035:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
 7036:                             $pubkey = $loginhash{'login'}{$item}{'public'};
 7037:                             $privkey = $loginhash{'login'}{$item}{'private'};
 7038:                         }
 7039:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
 7040:                         if (!$pubkey) {
 7041:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
 7042:                         } else {
 7043:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
 7044:                         }
 7045:                         if (!$privkey) {
 7046:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
 7047:                         } else {
 7048:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
 7049:                         }
 7050:                         $chgtxt .= '</ul>';
 7051:                         $resulttext .= '<li>'.$chgtxt.'</li>';
 7052:                     }
 7053:                 } elsif ($item eq 'recaptchaversion') {
 7054:                     if (ref($loginhash{'login'}) eq 'HASH') {
 7055:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
 7056:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
 7057:                                            '</li>';
 7058:                         }
 7059:                     }
 7060:                 } else {
 7061:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
 7062:                 }
 7063:             }
 7064:             $resulttext .= $colchgtext.'</ul>';
 7065:         } else {
 7066:             $resulttext = &mt('No changes made to log-in page settings');
 7067:         }
 7068:     } else {
 7069:         $resulttext = '<span class="LC_error">'.
 7070: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 7071:     }
 7072:     if ($errors) {
 7073:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
 7074:                        $errors.'</ul>';
 7075:     }
 7076:     return $resulttext;
 7077: }
 7078: 
 7079: sub check_exempt_addresses {
 7080:     my ($iplist) = @_;
 7081:     $iplist =~ s/^\s+//;
 7082:     $iplist =~ s/\s+$//;
 7083:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
 7084:     my (@okips,$new);
 7085:     foreach my $ip (@poss_ips) {
 7086:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
 7087:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
 7088:                 push(@okips,$ip);
 7089:             }
 7090:         }
 7091:     }
 7092:     if (@okips > 0) {
 7093:         $new = join(',',@okips);
 7094:     } else {
 7095:         $new = '';
 7096:     }
 7097:     return $new;
 7098: }
 7099: 
 7100: sub color_font_choices {
 7101:     my %choices =
 7102:         &Apache::lonlocal::texthash (
 7103:             img => "Header",
 7104:             bgs => "Background colors",
 7105:             links => "Link colors",
 7106:             images => "Images",
 7107:             font => "Font color",
 7108:             fontmenu => "Font menu",
 7109:             pgbg => "Page",
 7110:             tabbg => "Header",
 7111:             sidebg => "Border",
 7112:             link => "Link",
 7113:             alink => "Active link",
 7114:             vlink => "Visited link",
 7115:         );
 7116:     return %choices;
 7117: }
 7118: 
 7119: sub modify_rolecolors {
 7120:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
 7121:     my ($resulttext,%rolehash);
 7122:     $rolehash{'rolecolors'} = {};
 7123:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
 7124:         if ($domconfig{'rolecolors'} eq '') {
 7125:             $domconfig{'rolecolors'} = {};
 7126:         }
 7127:     }
 7128:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
 7129:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
 7130:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
 7131:                                              $dom);
 7132:     if ($putresult eq 'ok') {
 7133:         if (keys(%changes) > 0) {
 7134:             &Apache::loncommon::devalidate_domconfig_cache($dom);
 7135:             if (ref($lastactref) eq 'HASH') {
 7136:                 $lastactref->{'domainconfig'} = 1;
 7137:             }
 7138:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
 7139:                                              $rolehash{'rolecolors'});
 7140:         } else {
 7141:             $resulttext = &mt('No changes made to default color schemes');
 7142:         }
 7143:     } else {
 7144:         $resulttext = '<span class="LC_error">'.
 7145: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 7146:     }
 7147:     if ($errors) {
 7148:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
 7149:                        $errors.'</ul>';
 7150:     }
 7151:     return $resulttext;
 7152: }
 7153: 
 7154: sub modify_colors {
 7155:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
 7156:     my (%changes,%choices);
 7157:     my @bgs;
 7158:     my @links = ('link','alink','vlink');
 7159:     my @logintext;
 7160:     my @images;
 7161:     my $servadm = $r->dir_config('lonAdmEMail');
 7162:     my $errors;
 7163:     my %defaults;
 7164:     foreach my $role (@{$roles}) {
 7165:         if ($role eq 'login') {
 7166:             %choices = &login_choices();
 7167:             @logintext = ('textcol','bgcol');
 7168:         } else {
 7169:             %choices = &color_font_choices();
 7170:         }
 7171:         if ($role eq 'login') {
 7172:             @images = ('img','logo','domlogo','login');
 7173:             @bgs = ('pgbg','mainbg','sidebg');
 7174:         } else {
 7175:             @images = ('img');
 7176:             @bgs = ('pgbg','tabbg','sidebg');
 7177:         }
 7178:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
 7179:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
 7180:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
 7181:         }
 7182:         if ($role eq 'login') {
 7183:             foreach my $item (@logintext) {
 7184:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
 7185:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
 7186:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
 7187:                 }
 7188:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
 7189:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
 7190:                 }
 7191:             }
 7192:         } else {
 7193:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
 7194:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
 7195:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
 7196:             }
 7197:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
 7198:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
 7199:             }
 7200:         }
 7201:         foreach my $item (@bgs) {
 7202:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
 7203:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
 7204:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
 7205:             }
 7206:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
 7207:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
 7208:             }
 7209:         }
 7210:         foreach my $item (@links) {
 7211:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
 7212:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
 7213:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
 7214:             }
 7215:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
 7216:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
 7217:             }
 7218:         }
 7219:         my ($configuserok,$author_ok,$switchserver) = 
 7220:             &config_check($dom,$confname,$servadm);
 7221:         my ($width,$height) = &thumb_dimensions();
 7222:         if (ref($domconfig->{$role}) ne 'HASH') {
 7223:             $domconfig->{$role} = {};
 7224:         }
 7225:         foreach my $img (@images) {
 7226:             if (($role eq 'login') && (($img eq 'img') || ($img eq 'logo'))) {  
 7227:                 if (defined($env{'form.login_showlogo_'.$img})) {
 7228:                     $confhash->{$role}{'showlogo'}{$img} = 1;
 7229:                 } else { 
 7230:                     $confhash->{$role}{'showlogo'}{$img} = 0;
 7231:                 }
 7232:             } 
 7233: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
 7234: 		 && !defined($domconfig->{$role}{$img})
 7235: 		 && !$env{'form.'.$role.'_del_'.$img}
 7236: 		 && $env{'form.'.$role.'_import_'.$img}) {
 7237: 		# import the old configured image from the .tab setting
 7238: 		# if they haven't provided a new one 
 7239: 		$domconfig->{$role}{$img} = 
 7240: 		    $env{'form.'.$role.'_import_'.$img};
 7241: 	    }
 7242:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
 7243:                 my $error;
 7244:                 if ($configuserok eq 'ok') {
 7245:                     if ($switchserver) {
 7246:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
 7247:                     } else {
 7248:                         if ($author_ok eq 'ok') {
 7249:                             my ($result,$logourl) = 
 7250:                                 &publishlogo($r,'upload',$role.'_'.$img,
 7251:                                            $dom,$confname,$img,$width,$height);
 7252:                             if ($result eq 'ok') {
 7253:                                 $confhash->{$role}{$img} = $logourl;
 7254:                                 $changes{$role}{'images'}{$img} = 1;
 7255:                             } else {
 7256:                                 $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);
 7257:                             }
 7258:                         } else {
 7259:                             $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);
 7260:                         }
 7261:                     }
 7262:                 } else {
 7263:                     $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);
 7264:                 }
 7265:                 if ($error) {
 7266:                     &Apache::lonnet::logthis($error);
 7267:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 7268:                 }
 7269:             } elsif ($domconfig->{$role}{$img} ne '') {
 7270:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 7271:                     my $error;
 7272:                     if ($configuserok eq 'ok') {
 7273: # is confname an author?
 7274:                         if ($switchserver eq '') {
 7275:                             if ($author_ok eq 'ok') {
 7276:                                 my ($result,$logourl) = 
 7277:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
 7278:                                             $dom,$confname,$img,$width,$height);
 7279:                                 if ($result eq 'ok') {
 7280:                                     $confhash->{$role}{$img} = $logourl;
 7281: 				    $changes{$role}{'images'}{$img} = 1;
 7282:                                 }
 7283:                             }
 7284:                         }
 7285:                     }
 7286:                 }
 7287:             }
 7288:         }
 7289:         if (ref($domconfig) eq 'HASH') {
 7290:             if (ref($domconfig->{$role}) eq 'HASH') {
 7291:                 foreach my $img (@images) {
 7292:                     if ($domconfig->{$role}{$img} ne '') {
 7293:                         if ($env{'form.'.$role.'_del_'.$img}) {
 7294:                             $confhash->{$role}{$img} = '';
 7295:                             $changes{$role}{'images'}{$img} = 1;
 7296:                         } else {
 7297:                             if ($confhash->{$role}{$img} eq '') {
 7298:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
 7299:                             }
 7300:                         }
 7301:                     } else {
 7302:                         if ($env{'form.'.$role.'_del_'.$img}) {
 7303:                             $confhash->{$role}{$img} = '';
 7304:                             $changes{$role}{'images'}{$img} = 1;
 7305:                         } 
 7306:                     }
 7307:                     if (($role eq 'login') && (($img eq 'logo') || ($img eq 'img'))) {
 7308:                         if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
 7309:                             if ($confhash->{$role}{'showlogo'}{$img} ne 
 7310:                                 $domconfig->{$role}{'showlogo'}{$img}) {
 7311:                                 $changes{$role}{'showlogo'}{$img} = 1; 
 7312:                             }
 7313:                         } else {
 7314:                             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
 7315:                                 $changes{$role}{'showlogo'}{$img} = 1;
 7316:                             }
 7317:                         }
 7318:                     }
 7319:                 }
 7320:                 if ($domconfig->{$role}{'font'} ne '') {
 7321:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
 7322:                         $changes{$role}{'font'} = 1;
 7323:                     }
 7324:                 } else {
 7325:                     if ($confhash->{$role}{'font'}) {
 7326:                         $changes{$role}{'font'} = 1;
 7327:                     }
 7328:                 }
 7329:                 if ($role ne 'login') {
 7330:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
 7331:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
 7332:                             $changes{$role}{'fontmenu'} = 1;
 7333:                         }
 7334:                     } else {
 7335:                         if ($confhash->{$role}{'fontmenu'}) {
 7336:                             $changes{$role}{'fontmenu'} = 1;
 7337:                         }
 7338:                     }
 7339:                 }
 7340:                 foreach my $item (@bgs) {
 7341:                     if ($domconfig->{$role}{$item} ne '') {
 7342:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
 7343:                             $changes{$role}{'bgs'}{$item} = 1;
 7344:                         } 
 7345:                     } else {
 7346:                         if ($confhash->{$role}{$item}) {
 7347:                             $changes{$role}{'bgs'}{$item} = 1;
 7348:                         }
 7349:                     }
 7350:                 }
 7351:                 foreach my $item (@links) {
 7352:                     if ($domconfig->{$role}{$item} ne '') {
 7353:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
 7354:                             $changes{$role}{'links'}{$item} = 1;
 7355:                         }
 7356:                     } else {
 7357:                         if ($confhash->{$role}{$item}) {
 7358:                             $changes{$role}{'links'}{$item} = 1;
 7359:                         }
 7360:                     }
 7361:                 }
 7362:                 foreach my $item (@logintext) {
 7363:                     if ($domconfig->{$role}{$item} ne '') {
 7364:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
 7365:                             $changes{$role}{'logintext'}{$item} = 1;
 7366:                         }
 7367:                     } else {
 7368:                         if ($confhash->{$role}{$item}) {
 7369:                             $changes{$role}{'logintext'}{$item} = 1;
 7370:                         }
 7371:                     }
 7372:                 }
 7373:             } else {
 7374:                 &default_change_checker($role,\@images,\@links,\@bgs,
 7375:                                         \@logintext,$confhash,\%changes); 
 7376:             }
 7377:         } else {
 7378:             &default_change_checker($role,\@images,\@links,\@bgs,
 7379:                                     \@logintext,$confhash,\%changes); 
 7380:         }
 7381:     }
 7382:     return ($errors,%changes);
 7383: }
 7384: 
 7385: sub config_check {
 7386:     my ($dom,$confname,$servadm) = @_;
 7387:     my ($configuserok,$author_ok,$switchserver,%currroles);
 7388:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
 7389:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
 7390:                                                    $confname,$servadm);
 7391:     if ($configuserok eq 'ok') {
 7392:         $switchserver = &check_switchserver($dom,$confname);
 7393:         if ($switchserver eq '') {
 7394:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
 7395:         }
 7396:     }
 7397:     return ($configuserok,$author_ok,$switchserver);
 7398: }
 7399: 
 7400: sub default_change_checker {
 7401:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
 7402:     foreach my $item (@{$links}) {
 7403:         if ($confhash->{$role}{$item}) {
 7404:             $changes->{$role}{'links'}{$item} = 1;
 7405:         }
 7406:     }
 7407:     foreach my $item (@{$bgs}) {
 7408:         if ($confhash->{$role}{$item}) {
 7409:             $changes->{$role}{'bgs'}{$item} = 1;
 7410:         }
 7411:     }
 7412:     foreach my $item (@{$logintext}) {
 7413:         if ($confhash->{$role}{$item}) {
 7414:             $changes->{$role}{'logintext'}{$item} = 1;
 7415:         }
 7416:     }
 7417:     foreach my $img (@{$images}) {
 7418:         if ($env{'form.'.$role.'_del_'.$img}) {
 7419:             $confhash->{$role}{$img} = '';
 7420:             $changes->{$role}{'images'}{$img} = 1;
 7421:         }
 7422:         if ($role eq 'login') {
 7423:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
 7424:                 $changes->{$role}{'showlogo'}{$img} = 1;
 7425:             }
 7426:         }
 7427:     }
 7428:     if ($confhash->{$role}{'font'}) {
 7429:         $changes->{$role}{'font'} = 1;
 7430:     }
 7431: }
 7432: 
 7433: sub display_colorchgs {
 7434:     my ($dom,$changes,$roles,$confhash) = @_;
 7435:     my (%choices,$resulttext);
 7436:     if (!grep(/^login$/,@{$roles})) {
 7437:         $resulttext = &mt('Changes made:').'<br />';
 7438:     }
 7439:     foreach my $role (@{$roles}) {
 7440:         if ($role eq 'login') {
 7441:             %choices = &login_choices();
 7442:         } else {
 7443:             %choices = &color_font_choices();
 7444:         }
 7445:         if (ref($changes->{$role}) eq 'HASH') {
 7446:             if ($role ne 'login') {
 7447:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
 7448:             }
 7449:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
 7450:                 if ($role ne 'login') {
 7451:                     $resulttext .= '<ul>';
 7452:                 }
 7453:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
 7454:                     if ($role ne 'login') {
 7455:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
 7456:                     }
 7457:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
 7458:                         if (($role eq 'login') && ($key eq 'showlogo')) {
 7459:                             if ($confhash->{$role}{$key}{$item}) {
 7460:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
 7461:                             } else {
 7462:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
 7463:                             }
 7464:                         } elsif ($confhash->{$role}{$item} eq '') {
 7465:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
 7466:                         } else {
 7467:                             my $newitem = $confhash->{$role}{$item};
 7468:                             if ($key eq 'images') {
 7469:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" valign="bottom" />';
 7470:                             }
 7471:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
 7472:                         }
 7473:                     }
 7474:                     if ($role ne 'login') {
 7475:                         $resulttext .= '</ul></li>';
 7476:                     }
 7477:                 } else {
 7478:                     if ($confhash->{$role}{$key} eq '') {
 7479:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
 7480:                     } else {
 7481:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
 7482:                     }
 7483:                 }
 7484:                 if ($role ne 'login') {
 7485:                     $resulttext .= '</ul>';
 7486:                 }
 7487:             }
 7488:         }
 7489:     }
 7490:     return $resulttext;
 7491: }
 7492: 
 7493: sub thumb_dimensions {
 7494:     return ('200','50');
 7495: }
 7496: 
 7497: sub check_dimensions {
 7498:     my ($inputfile) = @_;
 7499:     my ($fullwidth,$fullheight);
 7500:     if ($inputfile =~ m|^[/\w.\-]+$|) {
 7501:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
 7502:             my $imageinfo = <PIPE>;
 7503:             if (!close(PIPE)) {
 7504:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
 7505:             }
 7506:             chomp($imageinfo);
 7507:             my ($fullsize) = 
 7508:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
 7509:             if ($fullsize) {
 7510:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
 7511:             }
 7512:         }
 7513:     }
 7514:     return ($fullwidth,$fullheight);
 7515: }
 7516: 
 7517: sub check_configuser {
 7518:     my ($uhome,$dom,$confname,$servadm) = @_;
 7519:     my ($configuserok,%currroles);
 7520:     if ($uhome eq 'no_host') {
 7521:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
 7522:         my $configpass = &LONCAPA::Enrollment::create_password();
 7523:         $configuserok = 
 7524:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
 7525:                              $configpass,'','','','','',undef,$servadm);
 7526:     } else {
 7527:         $configuserok = 'ok';
 7528:         %currroles = 
 7529:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
 7530:     }
 7531:     return ($configuserok,%currroles);
 7532: }
 7533: 
 7534: sub check_authorstatus {
 7535:     my ($dom,$confname,%currroles) = @_;
 7536:     my $author_ok;
 7537:     if (!$currroles{':'.$dom.':au'}) {
 7538:         my $start = time;
 7539:         my $end = 0;
 7540:         $author_ok = 
 7541:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
 7542:                                         'au',$end,$start,'','','domconfig');
 7543:     } else {
 7544:         $author_ok = 'ok';
 7545:     }
 7546:     return $author_ok;
 7547: }
 7548: 
 7549: sub publishlogo {
 7550:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
 7551:     my ($output,$fname,$logourl);
 7552:     if ($action eq 'upload') {
 7553:         $fname=$env{'form.'.$formname.'.filename'};
 7554:         chop($env{'form.'.$formname});
 7555:     } else {
 7556:         ($fname) = ($formname =~ /([^\/]+)$/);
 7557:     }
 7558:     if ($savefileas ne '') {
 7559:         $fname = $savefileas;
 7560:     }
 7561:     $fname=&Apache::lonnet::clean_filename($fname);
 7562: # See if there is anything left
 7563:     unless ($fname) { return ('error: no uploaded file'); }
 7564:     $fname="$subdir/$fname";
 7565:     my $docroot=$r->dir_config('lonDocRoot');
 7566:     my $filepath="$docroot/priv";
 7567:     my $relpath = "$dom/$confname";
 7568:     my ($fnamepath,$file,$fetchthumb);
 7569:     $file=$fname;
 7570:     if ($fname=~m|/|) {
 7571:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 7572:     }
 7573:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
 7574:     my $count;
 7575:     for ($count=5;$count<=$#parts;$count++) {
 7576:         $filepath.="/$parts[$count]";
 7577:         if ((-e $filepath)!=1) {
 7578:             mkdir($filepath,02770);
 7579:         }
 7580:     }
 7581:     # Check for bad extension and disallow upload
 7582:     if ($file=~/\.(\w+)$/ &&
 7583:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 7584:         $output = 
 7585:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
 7586:     } elsif ($file=~/\.(\w+)$/ &&
 7587:         !defined(&Apache::loncommon::fileembstyle($1))) {
 7588:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 7589:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
 7590:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 7591:     } elsif (-d "$filepath/$file") {
 7592:         $output = &mt('Filename is a directory name - rename the file and re-upload');
 7593:     } else {
 7594:         my $source = $filepath.'/'.$file;
 7595:         my $logfile;
 7596:         if (!open($logfile,">>$source".'.log')) {
 7597:             return (&mt('No write permission to Authoring Space'));
 7598:         }
 7599:         print $logfile
 7600: "\n================= Publish ".localtime()." ================\n".
 7601: $env{'user.name'}.':'.$env{'user.domain'}."\n";
 7602: # Save the file
 7603:         if (!open(FH,'>'.$source)) {
 7604:             &Apache::lonnet::logthis('Failed to create '.$source);
 7605:             return (&mt('Failed to create file'));
 7606:         }
 7607:         if ($action eq 'upload') {
 7608:             if (!print FH ($env{'form.'.$formname})) {
 7609:                 &Apache::lonnet::logthis('Failed to write to '.$source);
 7610:                 return (&mt('Failed to write file'));
 7611:             }
 7612:         } else {
 7613:             my $original = &Apache::lonnet::filelocation('',$formname);
 7614:             if(!copy($original,$source)) {
 7615:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
 7616:                 return (&mt('Failed to write file'));
 7617:             }
 7618:         }
 7619:         close(FH);
 7620:         chmod(0660, $source); # Permissions to rw-rw---.
 7621: 
 7622:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
 7623:         my $copyfile=$targetdir.'/'.$file;
 7624: 
 7625:         my @parts=split(/\//,$targetdir);
 7626:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 7627:         for (my $count=5;$count<=$#parts;$count++) {
 7628:             $path.="/$parts[$count]";
 7629:             if (!-e $path) {
 7630:                 print $logfile "\nCreating directory ".$path;
 7631:                 mkdir($path,02770);
 7632:             }
 7633:         }
 7634:         my $versionresult;
 7635:         if (-e $copyfile) {
 7636:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
 7637:         } else {
 7638:             $versionresult = 'ok';
 7639:         }
 7640:         if ($versionresult eq 'ok') {
 7641:             if (copy($source,$copyfile)) {
 7642:                 print $logfile "\nCopied original source to ".$copyfile."\n";
 7643:                 $output = 'ok';
 7644:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
 7645:                 push(@{$modified_urls},[$copyfile,$source]);
 7646:                 my $metaoutput = 
 7647:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
 7648:                 unless ($registered_cleanup) {
 7649:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
 7650:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
 7651:                     $registered_cleanup=1;
 7652:                 }
 7653:             } else {
 7654:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
 7655:                 $output = &mt('Failed to copy file to RES space').", $!";
 7656:             }
 7657:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 7658:                 my $inputfile = $filepath.'/'.$file;
 7659:                 my $outfile = $filepath.'/'.'tn-'.$file;
 7660:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
 7661:                 if ($fullwidth ne '' && $fullheight ne '') { 
 7662:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
 7663:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 7664:                         system("convert -sample $thumbsize $inputfile $outfile");
 7665:                         chmod(0660, $filepath.'/tn-'.$file);
 7666:                         if (-e $outfile) {
 7667:                             my $copyfile=$targetdir.'/tn-'.$file;
 7668:                             if (copy($outfile,$copyfile)) {
 7669:                                 print $logfile "\nCopied source to ".$copyfile."\n";
 7670:                                 my $thumb_metaoutput = 
 7671:                                     &write_metadata($dom,$confname,$formname,
 7672:                                                     $targetdir,'tn-'.$file,$logfile);
 7673:                                 push(@{$modified_urls},[$copyfile,$outfile]);
 7674:                                 unless ($registered_cleanup) {
 7675:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
 7676:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
 7677:                                     $registered_cleanup=1;
 7678:                                 }
 7679:                             } else {
 7680:                                 print $logfile "\nUnable to write ".$copyfile.
 7681:                                                ':'.$!."\n";
 7682:                             }
 7683:                         }
 7684:                     }
 7685:                 }
 7686:             }
 7687:         } else {
 7688:             $output = $versionresult;
 7689:         }
 7690:     }
 7691:     return ($output,$logourl);
 7692: }
 7693: 
 7694: sub logo_versioning {
 7695:     my ($targetdir,$file,$logfile) = @_;
 7696:     my $target = $targetdir.'/'.$file;
 7697:     my ($maxversion,$fn,$extn,$output);
 7698:     $maxversion = 0;
 7699:     if ($file =~ /^(.+)\.(\w+)$/) {
 7700:         $fn=$1;
 7701:         $extn=$2;
 7702:     }
 7703:     opendir(DIR,$targetdir);
 7704:     while (my $filename=readdir(DIR)) {
 7705:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
 7706:             $maxversion=($1>$maxversion)?$1:$maxversion;
 7707:         }
 7708:     }
 7709:     $maxversion++;
 7710:     print $logfile "\nCreating old version ".$maxversion."\n";
 7711:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
 7712:     if (copy($target,$copyfile)) {
 7713:         print $logfile "Copied old target to ".$copyfile."\n";
 7714:         $copyfile=$copyfile.'.meta';
 7715:         if (copy($target.'.meta',$copyfile)) {
 7716:             print $logfile "Copied old target metadata to ".$copyfile."\n";
 7717:             $output = 'ok';
 7718:         } else {
 7719:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
 7720:             $output = &mt('Failed to copy old meta').", $!, ";
 7721:         }
 7722:     } else {
 7723:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
 7724:         $output = &mt('Failed to copy old target').", $!, ";
 7725:     }
 7726:     return $output;
 7727: }
 7728: 
 7729: sub write_metadata {
 7730:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
 7731:     my (%metadatafields,%metadatakeys,$output);
 7732:     $metadatafields{'title'}=$formname;
 7733:     $metadatafields{'creationdate'}=time;
 7734:     $metadatafields{'lastrevisiondate'}=time;
 7735:     $metadatafields{'copyright'}='public';
 7736:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
 7737:                                          $env{'user.domain'};
 7738:     $metadatafields{'authorspace'}=$confname.':'.$dom;
 7739:     $metadatafields{'domain'}=$dom;
 7740:     {
 7741:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
 7742:         my $mfh;
 7743:         if (open($mfh,'>'.$targetdir.'/'.$file.'.meta')) {
 7744:             foreach (sort(keys(%metadatafields))) {
 7745:                 unless ($_=~/\./) {
 7746:                     my $unikey=$_;
 7747:                     $unikey=~/^([A-Za-z]+)/;
 7748:                     my $tag=$1;
 7749:                     $tag=~tr/A-Z/a-z/;
 7750:                     print $mfh "\n\<$tag";
 7751:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
 7752:                         my $value=$metadatafields{$unikey.'.'.$_};
 7753:                         $value=~s/\"/\'\'/g;
 7754:                         print $mfh ' '.$_.'="'.$value.'"';
 7755:                     }
 7756:                     print $mfh '>'.
 7757:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
 7758:                             .'</'.$tag.'>';
 7759:                 }
 7760:             }
 7761:             $output = 'ok';
 7762:             print $logfile "\nWrote metadata";
 7763:             close($mfh);
 7764:         } else {
 7765:             print $logfile "\nFailed to open metadata file";
 7766:             $output = &mt('Could not write metadata');
 7767:         }
 7768:     }
 7769:     return $output;
 7770: }
 7771: 
 7772: sub notifysubscribed {
 7773:     foreach my $targetsource (@{$modified_urls}){
 7774:         next unless (ref($targetsource) eq 'ARRAY');
 7775:         my ($target,$source)=@{$targetsource};
 7776:         if ($source ne '') {
 7777:             if (open(my $logfh,'>>'.$source.'.log')) {
 7778:                 print $logfh "\nCleanup phase: Notifications\n";
 7779:                 my @subscribed=&subscribed_hosts($target);
 7780:                 foreach my $subhost (@subscribed) {
 7781:                     print $logfh "\nNotifying host ".$subhost.':';
 7782:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
 7783:                     print $logfh $reply;
 7784:                 }
 7785:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
 7786:                 foreach my $subhost (@subscribedmeta) {
 7787:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
 7788:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
 7789:                                                         $subhost);
 7790:                     print $logfh $reply;
 7791:                 }
 7792:                 print $logfh "\n============ Done ============\n";
 7793:                 close($logfh);
 7794:             }
 7795:         }
 7796:     }
 7797:     return OK;
 7798: }
 7799: 
 7800: sub subscribed_hosts {
 7801:     my ($target) = @_;
 7802:     my @subscribed;
 7803:     if (open(my $fh,"<$target.subscription")) {
 7804:         while (my $subline=<$fh>) {
 7805:             if ($subline =~ /^($match_lonid):/) {
 7806:                 my $host = $1;
 7807:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
 7808:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
 7809:                         push(@subscribed,$host);
 7810:                     }
 7811:                 }
 7812:             }
 7813:         }
 7814:     }
 7815:     return @subscribed;
 7816: }
 7817: 
 7818: sub check_switchserver {
 7819:     my ($dom,$confname) = @_;
 7820:     my ($allowed,$switchserver);
 7821:     my $home = &Apache::lonnet::homeserver($confname,$dom);
 7822:     if ($home eq 'no_host') {
 7823:         $home = &Apache::lonnet::domain($dom,'primary');
 7824:     }
 7825:     my @ids=&Apache::lonnet::current_machine_ids();
 7826:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 7827:     if (!$allowed) {
 7828: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 7829:     }
 7830:     return $switchserver;
 7831: }
 7832: 
 7833: sub modify_quotas {
 7834:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
 7835:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
 7836:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
 7837:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
 7838:         $validationfieldsref);
 7839:     if ($action eq 'quotas') {
 7840:         $context = 'tools'; 
 7841:     } else {
 7842:         $context = $action;
 7843:     }
 7844:     if ($context eq 'requestcourses') {
 7845:         @usertools = ('official','unofficial','community','textbook');
 7846:         @options =('norequest','approval','validate','autolimit');
 7847:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 7848:         %titles = &courserequest_titles();
 7849:         $toolregexp = join('|',@usertools);
 7850:         %conditions = &courserequest_conditions();
 7851:         $confname = $dom.'-domainconfig';
 7852:         my $servadm = $r->dir_config('lonAdmEMail');
 7853:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 7854:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
 7855:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
 7856:     } elsif ($context eq 'requestauthor') {
 7857:         @usertools = ('author');
 7858:         %titles = &authorrequest_titles();
 7859:     } else {
 7860:         @usertools = ('aboutme','blog','webdav','portfolio');
 7861:         %titles = &tool_titles();
 7862:     }
 7863:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 7864:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7865:     foreach my $key (keys(%env)) {
 7866:         if ($context eq 'requestcourses') {
 7867:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
 7868:                 my $item = $1;
 7869:                 my $type = $2;
 7870:                 if ($type =~ /^limit_(.+)/) {
 7871:                     $limithash{$item}{$1} = $env{$key};
 7872:                 } else {
 7873:                     $confhash{$item}{$type} = $env{$key};
 7874:                 }
 7875:             }
 7876:         } elsif ($context eq 'requestauthor') {
 7877:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
 7878:                 $confhash{$1} = $env{$key};
 7879:             }
 7880:         } else {
 7881:             if ($key =~ /^form\.quota_(.+)$/) {
 7882:                 $confhash{'defaultquota'}{$1} = $env{$key};
 7883:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
 7884:                 $confhash{'authorquota'}{$1} = $env{$key};
 7885:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
 7886:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
 7887:             }
 7888:         }
 7889:     }
 7890:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 7891:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
 7892:         @approvalnotify = sort(@approvalnotify);
 7893:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
 7894:         my @crstypes = ('official','unofficial','community','textbook');
 7895:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
 7896:         foreach my $type (@hasuniquecode) {
 7897:             if (grep(/^\Q$type\E$/,@crstypes)) {
 7898:                 $confhash{'uniquecode'}{$type} = 1;
 7899:             }
 7900:         }
 7901:         my (%newbook,%allpos);
 7902:         if ($context eq 'requestcourses') {
 7903:             foreach my $type ('textbooks','templates') {
 7904:                 @{$allpos{$type}} = (); 
 7905:                 my $invalid;
 7906:                 if ($type eq 'textbooks') {
 7907:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
 7908:                 } else {
 7909:                     $invalid = &mt('Invalid LON-CAPA course for template');
 7910:                 }
 7911:                 if ($env{'form.'.$type.'_addbook'}) {
 7912:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
 7913:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
 7914:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
 7915:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
 7916:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
 7917:                         } else {
 7918:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
 7919:                             my $position = $env{'form.'.$type.'_addbook_pos'};
 7920:                             $position =~ s/\D+//g;
 7921:                             if ($position ne '') {
 7922:                                 $allpos{$type}[$position] = $newbook{$type};
 7923:                             }
 7924:                         }
 7925:                     } else {
 7926:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
 7927:                     }
 7928:                 }
 7929:             } 
 7930:         }
 7931:         if (ref($domconfig{$action}) eq 'HASH') {
 7932:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
 7933:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
 7934:                     $changes{'notify'}{'approval'} = 1;
 7935:                 }
 7936:             } else {
 7937:                 if ($confhash{'notify'}{'approval'}) {
 7938:                     $changes{'notify'}{'approval'} = 1;
 7939:                 }
 7940:             }
 7941:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
 7942:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
 7943:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
 7944:                         unless ($confhash{'uniquecode'}{$crstype}) {
 7945:                             $changes{'uniquecode'} = 1;
 7946:                         }
 7947:                     }
 7948:                     unless ($changes{'uniquecode'}) {
 7949:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
 7950:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
 7951:                                 $changes{'uniquecode'} = 1;
 7952:                             }
 7953:                         }
 7954:                     }
 7955:                } else {
 7956:                    $changes{'uniquecode'} = 1;
 7957:                }
 7958:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
 7959:                 $changes{'uniquecode'} = 1;
 7960:             }
 7961:             if ($context eq 'requestcourses') {
 7962:                 foreach my $type ('textbooks','templates') {
 7963:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
 7964:                         my %deletions;
 7965:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
 7966:                         if (@todelete) {
 7967:                             map { $deletions{$_} = 1; } @todelete;
 7968:                         }
 7969:                         my %imgdeletions;
 7970:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
 7971:                         if (@todeleteimages) {
 7972:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
 7973:                         }
 7974:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
 7975:                         for (my $i=0; $i<=$maxnum; $i++) {
 7976:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
 7977:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
 7978:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
 7979:                                 if ($deletions{$key}) {
 7980:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
 7981:                                         #FIXME need to obsolete item in RES space
 7982:                                     }
 7983:                                     next;
 7984:                                 } else {
 7985:                                     my $newpos = $env{'form.'.$itemid};
 7986:                                     $newpos =~ s/\D+//g;
 7987:                                     foreach my $item ('subject','title','publisher','author') {
 7988:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
 7989:                                                  ($type eq 'templates'));
 7990:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
 7991:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
 7992:                                             $changes{$type}{$key} = 1;
 7993:                                         }
 7994:                                     }
 7995:                                     $allpos{$type}[$newpos] = $key;
 7996:                                 }
 7997:                                 if ($imgdeletions{$key}) {
 7998:                                     $changes{$type}{$key} = 1;
 7999:                                     #FIXME need to obsolete item in RES space
 8000:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
 8001:                                     my ($cdom,$cnum) = split(/_/,$key);
 8002:                                     my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
 8003:                                                                                   $cdom,$cnum,$type,$configuserok,
 8004:                                                                                   $switchserver,$author_ok);
 8005:                                     if ($imgurl) {
 8006:                                         $confhash{$type}{$key}{'image'} = $imgurl;
 8007:                                         $changes{$type}{$key} = 1; 
 8008:                                     }
 8009:                                     if ($error) {
 8010:                                         &Apache::lonnet::logthis($error);
 8011:                                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 8012:                                     } 
 8013:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
 8014:                                     $confhash{$type}{$key}{'image'} = 
 8015:                                         $domconfig{$action}{$type}{$key}{'image'};
 8016:                                 }
 8017:                             }
 8018:                         }
 8019:                     }
 8020:                 }
 8021:             }
 8022:         } else {
 8023:             if ($confhash{'notify'}{'approval'}) {
 8024:                 $changes{'notify'}{'approval'} = 1;
 8025:             }
 8026:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
 8027:                 $changes{'uniquecode'} = 1;
 8028:             }
 8029:         }
 8030:         if ($context eq 'requestcourses') {
 8031:             foreach my $type ('textbooks','templates') {
 8032:                 if ($newbook{$type}) {
 8033:                     $changes{$type}{$newbook{$type}} = 1;
 8034:                     foreach my $item ('subject','title','publisher','author') {
 8035:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
 8036:                                  ($type eq 'template'));
 8037:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
 8038:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
 8039:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
 8040:                         }
 8041:                     }
 8042:                     if ($type eq 'textbooks') {
 8043:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
 8044:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
 8045:                             my ($imageurl,$error) =
 8046:                                 &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
 8047:                                                         $configuserok,$switchserver,$author_ok);
 8048:                             if ($imageurl) {
 8049:                                 $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
 8050:                             }
 8051:                             if ($error) {
 8052:                                 &Apache::lonnet::logthis($error);
 8053:                                 $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 8054:                             }
 8055:                         }
 8056:                     }
 8057:                 }
 8058:                 if (@{$allpos{$type}} > 0) {
 8059:                     my $idx = 0;
 8060:                     foreach my $item (@{$allpos{$type}}) {
 8061:                         if ($item ne '') {
 8062:                             $confhash{$type}{$item}{'order'} = $idx;
 8063:                             if (ref($domconfig{$action}) eq 'HASH') {
 8064:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
 8065:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
 8066:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
 8067:                                             $changes{$type}{$item} = 1;
 8068:                                         }
 8069:                                     }
 8070:                                 }
 8071:                             }
 8072:                             $idx ++;
 8073:                         }
 8074:                     }
 8075:                 }
 8076:             }
 8077:             if (ref($validationitemsref) eq 'ARRAY') {
 8078:                 foreach my $item (@{$validationitemsref}) {
 8079:                     if ($item eq 'fields') {
 8080:                         my @changed;
 8081:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
 8082:                         if (@{$confhash{'validation'}{$item}} > 0) {
 8083:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
 8084:                         }
 8085:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 8086:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 8087:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
 8088:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
 8089:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
 8090:                                 } else {
 8091:                                     @changed = @{$confhash{'validation'}{$item}};
 8092:                                 }
 8093:                             } else {
 8094:                                 @changed = @{$confhash{'validation'}{$item}};
 8095:                             }
 8096:                         } else {
 8097:                             @changed = @{$confhash{'validation'}{$item}};
 8098:                         }
 8099:                         if (@changed) {
 8100:                             if ($confhash{'validation'}{$item}) {
 8101:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
 8102:                             } else {
 8103:                                 $changes{'validation'}{$item} = &mt('None');
 8104:                             }
 8105:                         }
 8106:                     } else {
 8107:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
 8108:                         if ($item eq 'markup') {
 8109:                             if ($env{'form.requestcourses_validation_'.$item}) {
 8110:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
 8111:                             }
 8112:                         }
 8113:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 8114:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 8115:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
 8116:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
 8117:                                 }
 8118:                             } else {
 8119:                                 if ($confhash{'validation'}{$item} ne '') {
 8120:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
 8121:                                 }
 8122:                             }
 8123:                         } else {
 8124:                             if ($confhash{'validation'}{$item} ne '') {
 8125:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
 8126:                             }
 8127:                         }
 8128:                     }
 8129:                 }
 8130:             }
 8131:             if ($env{'form.validationdc'}) {
 8132:                 my $newval = $env{'form.validationdc'};
 8133:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
 8134:                 if (exists($domcoords{$newval})) {
 8135:                     $confhash{'validation'}{'dc'} = $newval;
 8136:                 }
 8137:             }
 8138:             if (ref($confhash{'validation'}) eq 'HASH') {
 8139:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 8140:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 8141:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
 8142:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
 8143:                                 if ($confhash{'validation'}{'dc'} eq '') {
 8144:                                     $changes{'validation'}{'dc'} = &mt('None');
 8145:                                 } else {
 8146:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 8147:                                 }
 8148:                             }
 8149:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
 8150:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 8151:                         }
 8152:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
 8153:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 8154:                     }
 8155:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
 8156:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 8157:                 }
 8158:             } else {
 8159:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 8160:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 8161:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
 8162:                             $changes{'validation'}{'dc'} = &mt('None');
 8163:                         }
 8164:                     }
 8165:                 }
 8166:             }
 8167:         }
 8168:     } else {
 8169:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
 8170:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
 8171:     }
 8172:     foreach my $item (@usertools) {
 8173:         foreach my $type (@{$types},'default','_LC_adv') {
 8174:             my $unset; 
 8175:             if ($context eq 'requestcourses') {
 8176:                 $unset = '0';
 8177:                 if ($type eq '_LC_adv') {
 8178:                     $unset = '';
 8179:                 }
 8180:                 if ($confhash{$item}{$type} eq 'autolimit') {
 8181:                     $confhash{$item}{$type} .= '=';
 8182:                     unless ($limithash{$item}{$type} =~ /\D/) {
 8183:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
 8184:                     }
 8185:                 }
 8186:             } elsif ($context eq 'requestauthor') {
 8187:                 $unset = '0';
 8188:                 if ($type eq '_LC_adv') {
 8189:                     $unset = '';
 8190:                 }
 8191:             } else {
 8192:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
 8193:                     $confhash{$item}{$type} = 1;
 8194:                 } else {
 8195:                     $confhash{$item}{$type} = 0;
 8196:                 }
 8197:             }
 8198:             if (ref($domconfig{$action}) eq 'HASH') {
 8199:                 if ($action eq 'requestauthor') {
 8200:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
 8201:                         $changes{$type} = 1;
 8202:                     }
 8203:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
 8204:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
 8205:                         $changes{$item}{$type} = 1;
 8206:                     }
 8207:                 } else {
 8208:                     if ($context eq 'requestcourses') {
 8209:                         if ($confhash{$item}{$type} ne $unset) {
 8210:                             $changes{$item}{$type} = 1;
 8211:                         }
 8212:                     } else {
 8213:                         if (!$confhash{$item}{$type}) {
 8214:                             $changes{$item}{$type} = 1;
 8215:                         }
 8216:                     }
 8217:                 }
 8218:             } else {
 8219:                 if ($context eq 'requestcourses') {
 8220:                     if ($confhash{$item}{$type} ne $unset) {
 8221:                         $changes{$item}{$type} = 1;
 8222:                     }
 8223:                 } elsif ($context eq 'requestauthor') {
 8224:                     if ($confhash{$type} ne $unset) {
 8225:                         $changes{$type} = 1;
 8226:                     }
 8227:                 } else {
 8228:                     if (!$confhash{$item}{$type}) {
 8229:                         $changes{$item}{$type} = 1;
 8230:                     }
 8231:                 }
 8232:             }
 8233:         }
 8234:     }
 8235:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 8236:         if (ref($domconfig{'quotas'}) eq 'HASH') {
 8237:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 8238:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
 8239:                     if (exists($confhash{'defaultquota'}{$key})) {
 8240:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
 8241:                             $changes{'defaultquota'}{$key} = 1;
 8242:                         }
 8243:                     } else {
 8244:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
 8245:                     }
 8246:                 }
 8247:             } else {
 8248:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
 8249:                     if (exists($confhash{'defaultquota'}{$key})) {
 8250:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
 8251:                             $changes{'defaultquota'}{$key} = 1;
 8252:                         }
 8253:                     } else {
 8254:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
 8255:                     }
 8256:                 }
 8257:             }
 8258:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 8259:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
 8260:                     if (exists($confhash{'authorquota'}{$key})) {
 8261:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
 8262:                             $changes{'authorquota'}{$key} = 1;
 8263:                         }
 8264:                     } else {
 8265:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
 8266:                     }
 8267:                 }
 8268:             }
 8269:         }
 8270:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
 8271:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
 8272:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
 8273:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 8274:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
 8275:                             $changes{'defaultquota'}{$key} = 1;
 8276:                         }
 8277:                     } else {
 8278:                         if (!exists($domconfig{'quotas'}{$key})) {
 8279:                             $changes{'defaultquota'}{$key} = 1;
 8280:                         }
 8281:                     }
 8282:                 } else {
 8283:                     $changes{'defaultquota'}{$key} = 1;
 8284:                 }
 8285:             }
 8286:         }
 8287:         if (ref($confhash{'authorquota'}) eq 'HASH') {
 8288:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
 8289:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
 8290:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 8291:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
 8292:                             $changes{'authorquota'}{$key} = 1;
 8293:                         }
 8294:                     } else {
 8295:                         $changes{'authorquota'}{$key} = 1;
 8296:                     }
 8297:                 } else {
 8298:                     $changes{'authorquota'}{$key} = 1;
 8299:                 }
 8300:             }
 8301:         }
 8302:     }
 8303: 
 8304:     if ($context eq 'requestauthor') {
 8305:         $domdefaults{'requestauthor'} = \%confhash;
 8306:     } else {
 8307:         foreach my $key (keys(%confhash)) {
 8308:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
 8309:                 $domdefaults{$key} = $confhash{$key};
 8310:             }
 8311:         }
 8312:     }
 8313: 
 8314:     my %quotahash = (
 8315:                       $action => { %confhash }
 8316:                     );
 8317:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
 8318:                                              $dom);
 8319:     if ($putresult eq 'ok') {
 8320:         if (keys(%changes) > 0) {
 8321:             my $cachetime = 24*60*60;
 8322:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
 8323:             if (ref($lastactref) eq 'HASH') {
 8324:                 $lastactref->{'domdefaults'} = 1;
 8325:             }
 8326:             $resulttext = &mt('Changes made:').'<ul>';
 8327:             unless (($context eq 'requestcourses') ||
 8328:                     ($context eq 'requestauthor')) {
 8329:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
 8330:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
 8331:                     foreach my $type (@{$types},'default') {
 8332:                         if (defined($changes{'defaultquota'}{$type})) {
 8333:                             my $typetitle = $usertypes->{$type};
 8334:                             if ($type eq 'default') {
 8335:                                 $typetitle = $othertitle;
 8336:                             }
 8337:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
 8338:                         }
 8339:                     }
 8340:                     $resulttext .= '</ul></li>';
 8341:                 }
 8342:                 if (ref($changes{'authorquota'}) eq 'HASH') {
 8343:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
 8344:                     foreach my $type (@{$types},'default') {
 8345:                         if (defined($changes{'authorquota'}{$type})) {
 8346:                             my $typetitle = $usertypes->{$type};
 8347:                             if ($type eq 'default') {
 8348:                                 $typetitle = $othertitle;
 8349:                             }
 8350:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
 8351:                         }
 8352:                     }
 8353:                     $resulttext .= '</ul></li>';
 8354:                 }
 8355:             }
 8356:             my %newenv;
 8357:             foreach my $item (@usertools) {
 8358:                 my (%haschgs,%inconf);
 8359:                 if ($context eq 'requestauthor') {
 8360:                     %haschgs = %changes;
 8361:                     %inconf = %confhash;
 8362:                 } else {
 8363:                     if (ref($changes{$item}) eq 'HASH') {
 8364:                         %haschgs = %{$changes{$item}};
 8365:                     }
 8366:                     if (ref($confhash{$item}) eq 'HASH') {
 8367:                         %inconf = %{$confhash{$item}};
 8368:                     }
 8369:                 }
 8370:                 if (keys(%haschgs) > 0) {
 8371:                     my $newacc = 
 8372:                         &Apache::lonnet::usertools_access($env{'user.name'},
 8373:                                                           $env{'user.domain'},
 8374:                                                           $item,'reload',$context);
 8375:                     if (($context eq 'requestcourses') ||
 8376:                         ($context eq 'requestauthor')) {
 8377:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
 8378:                             $newenv{'environment.canrequest.'.$item} = $newacc;
 8379:                         }
 8380:                     } else {
 8381:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
 8382:                             $newenv{'environment.availabletools.'.$item} = $newacc;
 8383:                         }
 8384:                     }
 8385:                     unless ($context eq 'requestauthor') {
 8386:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
 8387:                     }
 8388:                     foreach my $type (@{$types},'default','_LC_adv') {
 8389:                         if ($haschgs{$type}) {
 8390:                             my $typetitle = $usertypes->{$type};
 8391:                             if ($type eq 'default') {
 8392:                                 $typetitle = $othertitle;
 8393:                             } elsif ($type eq '_LC_adv') {
 8394:                                 $typetitle = 'LON-CAPA Advanced Users'; 
 8395:                             }
 8396:                             if ($inconf{$type}) {
 8397:                                 if ($context eq 'requestcourses') {
 8398:                                     my $cond;
 8399:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
 8400:                                         if ($1 eq '') {
 8401:                                             $cond = &mt('(Automatic processing of any request).');
 8402:                                         } else {
 8403:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
 8404:                                         }
 8405:                                     } else { 
 8406:                                         $cond = $conditions{$inconf{$type}};
 8407:                                     }
 8408:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
 8409:                                 } elsif ($context eq 'requestauthor') {
 8410:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
 8411:                                                              $titles{$inconf{$type}},$typetitle);
 8412: 
 8413:                                 } else {
 8414:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
 8415:                                 }
 8416:                             } else {
 8417:                                 if ($type eq '_LC_adv') {
 8418:                                     if ($inconf{$type} eq '0') {
 8419:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
 8420:                                     } else { 
 8421:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
 8422:                                     }
 8423:                                 } else {
 8424:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
 8425:                                 }
 8426:                             }
 8427:                         }
 8428:                     }
 8429:                     unless ($context eq 'requestauthor') {
 8430:                         $resulttext .= '</ul></li>';
 8431:                     }
 8432:                 }
 8433:             }
 8434:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
 8435:                 if (ref($changes{'notify'}) eq 'HASH') {
 8436:                     if ($changes{'notify'}{'approval'}) {
 8437:                         if (ref($confhash{'notify'}) eq 'HASH') {
 8438:                             if ($confhash{'notify'}{'approval'}) {
 8439:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
 8440:                             } else {
 8441:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
 8442:                             }
 8443:                         }
 8444:                     }
 8445:                 }
 8446:             }
 8447:             if ($action eq 'requestcourses') {
 8448:                 my @offon = ('off','on');
 8449:                 if ($changes{'uniquecode'}) {
 8450:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
 8451:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
 8452:                         $resulttext .= '<li>'.
 8453:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
 8454:                                        '</li>';
 8455:                     } else {
 8456:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
 8457:                                        '</li>';
 8458:                     }
 8459:                 }
 8460:                 foreach my $type ('textbooks','templates') {
 8461:                     if (ref($changes{$type}) eq 'HASH') {
 8462:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
 8463:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
 8464:                             my %coursehash = &Apache::lonnet::coursedescription($key);
 8465:                             my $coursetitle = $coursehash{'description'};
 8466:                             my $position = $confhash{$type}{$key}{'order'} + 1;
 8467:                             $resulttext .= '<li>';
 8468:                             foreach my $item ('subject','title','publisher','author') {
 8469:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
 8470:                                          ($type eq 'templates'));
 8471:                                 my $name = $item.':';
 8472:                                 $name =~ s/^(\w)/\U$1/;
 8473:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
 8474:                             }
 8475:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
 8476:                             if ($type eq 'textbooks') {
 8477:                                 if ($confhash{$type}{$key}{'image'}) {
 8478:                                     $resulttext .= ' '.&mt('Image: [_1]',
 8479:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
 8480:                                                    ' alt="Textbook cover" />').'<br />';
 8481:                                 }
 8482:                             }
 8483:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
 8484:                         }
 8485:                         $resulttext .= '</ul></li>';
 8486:                     }
 8487:                 }
 8488:                 if (ref($changes{'validation'}) eq 'HASH') {
 8489:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
 8490:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
 8491:                         foreach my $item (@{$validationitemsref}) {
 8492:                             if (exists($changes{'validation'}{$item})) {
 8493:                                 if ($item eq 'markup') {
 8494:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
 8495:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
 8496:                                 } else {
 8497:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
 8498:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
 8499:                                 }
 8500:                             }
 8501:                         }
 8502:                         if (exists($changes{'validation'}{'dc'})) {
 8503:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
 8504:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
 8505:                         }
 8506:                     }
 8507:                 }
 8508:             }
 8509:             $resulttext .= '</ul>';
 8510:             if (keys(%newenv)) {
 8511:                 &Apache::lonnet::appenv(\%newenv);
 8512:             }
 8513:         } else {
 8514:             if ($context eq 'requestcourses') {
 8515:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
 8516:             } elsif ($context eq 'requestauthor') {
 8517:                 $resulttext = &mt('No changes made to rights to request author space.');
 8518:             } else {
 8519:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
 8520:             }
 8521:         }
 8522:     } else {
 8523:         $resulttext = '<span class="LC_error">'.
 8524: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 8525:     }
 8526:     if ($errors) {
 8527:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
 8528:                        '<ul>'.$errors.'</ul></p>';
 8529:     }
 8530:     return $resulttext;
 8531: }
 8532: 
 8533: sub process_textbook_image {
 8534:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
 8535:     my $filename = $env{'form.'.$caller.'.filename'};
 8536:     my ($error,$url);
 8537:     my ($width,$height) = (50,50);
 8538:     if ($configuserok eq 'ok') {
 8539:         if ($switchserver) {
 8540:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
 8541:                          $switchserver);
 8542:         } elsif ($author_ok eq 'ok') {
 8543:             my ($result,$imageurl) =
 8544:                 &publishlogo($r,'upload',$caller,$dom,$confname,
 8545:                              "$type/$dom/$cnum/cover",$width,$height);
 8546:             if ($result eq 'ok') {
 8547:                 $url = $imageurl;
 8548:             } else {
 8549:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
 8550:             }
 8551:         } else {
 8552:             $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);
 8553:         }
 8554:     } else {
 8555:         $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);
 8556:     }
 8557:     return ($url,$error);
 8558: }
 8559: 
 8560: sub modify_autoenroll {
 8561:     my ($dom,$lastactref,%domconfig) = @_;
 8562:     my ($resulttext,%changes);
 8563:     my %currautoenroll;
 8564:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8565:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
 8566:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
 8567:         }
 8568:     }
 8569:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 8570:     my %title = ( run => 'Auto-enrollment active',
 8571:                   sender => 'Sender for notification messages',
 8572:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
 8573:                   failsafe => 'Failsafe for no drops if institutional data missing for a section');
 8574:     my @offon = ('off','on');
 8575:     my $sender_uname = $env{'form.sender_uname'};
 8576:     my $sender_domain = $env{'form.sender_domain'};
 8577:     if ($sender_domain eq '') {
 8578:         $sender_uname = '';
 8579:     } elsif ($sender_uname eq '') {
 8580:         $sender_domain = '';
 8581:     }
 8582:     my $coowners = $env{'form.autoassign_coowners'};
 8583:     my $failsafe = $env{'form.autoenroll_failsafe'};
 8584:     $failsafe =~ s{^\s+|\s+$}{}g;
 8585:     if ($failsafe =~ /\D/) {
 8586:         undef($failsafe);
 8587:     }
 8588:     my %autoenrollhash =  (
 8589:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
 8590:                                        'sender_uname' => $sender_uname,
 8591:                                        'sender_domain' => $sender_domain,
 8592:                                        'co-owners' => $coowners,
 8593:                                        'autofailsafe' => $failsafe,
 8594:                                 }
 8595:                      );
 8596:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
 8597:                                              $dom);
 8598:     if ($putresult eq 'ok') {
 8599:         if (exists($currautoenroll{'run'})) {
 8600:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
 8601:                  $changes{'run'} = 1;
 8602:              }
 8603:         } elsif ($autorun) {
 8604:             if ($env{'form.autoenroll_run'} ne '1') {
 8605:                  $changes{'run'} = 1;
 8606:             }
 8607:         }
 8608:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
 8609:             $changes{'sender'} = 1;
 8610:         }
 8611:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
 8612:             $changes{'sender'} = 1;
 8613:         }
 8614:         if ($currautoenroll{'co-owners'} ne '') {
 8615:             if ($currautoenroll{'co-owners'} ne $coowners) {
 8616:                 $changes{'coowners'} = 1;
 8617:             }
 8618:         } elsif ($coowners) {
 8619:             $changes{'coowners'} = 1;
 8620:         }
 8621:         if ($currautoenroll{'autofailsafe'} ne $failsafe) {
 8622:             $changes{'autofailsafe'} = 1;
 8623:         }
 8624:         if (keys(%changes) > 0) {
 8625:             $resulttext = &mt('Changes made:').'<ul>';
 8626:             if ($changes{'run'}) {
 8627:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
 8628:             }
 8629:             if ($changes{'sender'}) {
 8630:                 if ($sender_uname eq '' || $sender_domain eq '') {
 8631:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
 8632:                 } else {
 8633:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
 8634:                 }
 8635:             }
 8636:             if ($changes{'coowners'}) {
 8637:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
 8638:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
 8639:                 if (ref($lastactref) eq 'HASH') {
 8640:                     $lastactref->{'domainconfig'} = 1;
 8641:                 }
 8642:             }
 8643:             if ($changes{'autofailsafe'}) {
 8644:                 if ($failsafe ne '') {
 8645:                     $resulttext .= '<li>'.&mt("$title{'failsafe'} set to [_1]",$failsafe).'</li>';
 8646:                 } else {
 8647:                     $resulttext .= '<li>'.&mt("$title{'failsafe'} deleted");
 8648:                 }
 8649:                 &Apache::lonnet::get_domain_defaults($dom,1);
 8650:                 if (ref($lastactref) eq 'HASH') {
 8651:                     $lastactref->{'domdefaults'} = 1;
 8652:                 }
 8653:             }
 8654:             $resulttext .= '</ul>';
 8655:         } else {
 8656:             $resulttext = &mt('No changes made to auto-enrollment settings');
 8657:         }
 8658:     } else {
 8659:         $resulttext = '<span class="LC_error">'.
 8660: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 8661:     }
 8662:     return $resulttext;
 8663: }
 8664: 
 8665: sub modify_autoupdate {
 8666:     my ($dom,%domconfig) = @_;
 8667:     my ($resulttext,%currautoupdate,%fields,%changes);
 8668:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
 8669:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
 8670:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
 8671:         }
 8672:     }
 8673:     my @offon = ('off','on');
 8674:     my %title = &Apache::lonlocal::texthash (
 8675:                    run => 'Auto-update:',
 8676:                    classlists => 'Updates to user information in classlists?'
 8677:                 );
 8678:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 8679:     my %fieldtitles = &Apache::lonlocal::texthash (
 8680:                         id => 'Student/Employee ID',
 8681:                         permanentemail => 'E-mail address',
 8682:                         lastname => 'Last Name',
 8683:                         firstname => 'First Name',
 8684:                         middlename => 'Middle Name',
 8685:                         generation => 'Generation',
 8686:                       );
 8687:     $othertitle = &mt('All users');
 8688:     if (keys(%{$usertypes}) >  0) {
 8689:         $othertitle = &mt('Other users');
 8690:     }
 8691:     foreach my $key (keys(%env)) {
 8692:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
 8693:             my ($usertype,$item) = ($1,$2);
 8694:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
 8695:                 if ($usertype eq 'default') {   
 8696:                     push(@{$fields{$1}},$2);
 8697:                 } elsif (ref($types) eq 'ARRAY') {
 8698:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
 8699:                         push(@{$fields{$1}},$2);
 8700:                     }
 8701:                 }
 8702:             }
 8703:         }
 8704:     }
 8705:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
 8706:     @lockablenames = sort(@lockablenames);
 8707:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
 8708:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
 8709:         if (@changed) {
 8710:             $changes{'lockablenames'} = 1;
 8711:         }
 8712:     } else {
 8713:         if (@lockablenames) {
 8714:             $changes{'lockablenames'} = 1;
 8715:         }
 8716:     }
 8717:     my %updatehash = (
 8718:                       autoupdate => { run => $env{'form.autoupdate_run'},
 8719:                                       classlists => $env{'form.classlists'},
 8720:                                       fields => {%fields},
 8721:                                       lockablenames => \@lockablenames,
 8722:                                     }
 8723:                      );
 8724:     foreach my $key (keys(%currautoupdate)) {
 8725:         if (($key eq 'run') || ($key eq 'classlists')) {
 8726:             if (exists($updatehash{autoupdate}{$key})) {
 8727:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
 8728:                     $changes{$key} = 1;
 8729:                 }
 8730:             }
 8731:         } elsif ($key eq 'fields') {
 8732:             if (ref($currautoupdate{$key}) eq 'HASH') {
 8733:                 foreach my $item (@{$types},'default') {
 8734:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
 8735:                         my $change = 0;
 8736:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
 8737:                             if (!exists($fields{$item})) {
 8738:                                 $change = 1;
 8739:                                 last;
 8740:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
 8741:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
 8742:                                     $change = 1;
 8743:                                     last;
 8744:                                 }
 8745:                             }
 8746:                         }
 8747:                         if ($change) {
 8748:                             push(@{$changes{$key}},$item);
 8749:                         }
 8750:                     } 
 8751:                 }
 8752:             }
 8753:         } elsif ($key eq 'lockablenames') {
 8754:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
 8755:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
 8756:                 if (@changed) {
 8757:                     $changes{'lockablenames'} = 1;
 8758:                 }
 8759:             } else {
 8760:                 if (@lockablenames) {
 8761:                     $changes{'lockablenames'} = 1;
 8762:                 }
 8763:             }
 8764:         }
 8765:     }
 8766:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
 8767:         if (@lockablenames) {
 8768:             $changes{'lockablenames'} = 1;
 8769:         }
 8770:     }
 8771:     foreach my $item (@{$types},'default') {
 8772:         if (defined($fields{$item})) {
 8773:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
 8774:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
 8775:                     my $change = 0;
 8776:                     if (ref($fields{$item}) eq 'ARRAY') {
 8777:                         foreach my $type (@{$fields{$item}}) {
 8778:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
 8779:                                 $change = 1;
 8780:                                 last;
 8781:                             }
 8782:                         }
 8783:                     }
 8784:                     if ($change) {
 8785:                         push(@{$changes{'fields'}},$item);
 8786:                     }
 8787:                 } else {
 8788:                     push(@{$changes{'fields'}},$item);
 8789:                 }
 8790:             } else {
 8791:                 push(@{$changes{'fields'}},$item);
 8792:             }
 8793:         }
 8794:     }
 8795:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
 8796:                                              $dom);
 8797:     if ($putresult eq 'ok') {
 8798:         if (keys(%changes) > 0) {
 8799:             $resulttext = &mt('Changes made:').'<ul>';
 8800:             foreach my $key (sort(keys(%changes))) {
 8801:                 if ($key eq 'lockablenames') {
 8802:                     $resulttext .= '<li>';
 8803:                     if (@lockablenames) {
 8804:                         $usertypes->{'default'} = $othertitle;
 8805:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
 8806:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
 8807:                     } else {
 8808:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
 8809:                     }
 8810:                     $resulttext .= '</li>';
 8811:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
 8812:                     foreach my $item (@{$changes{$key}}) {
 8813:                         my @newvalues;
 8814:                         foreach my $type (@{$fields{$item}}) {
 8815:                             push(@newvalues,$fieldtitles{$type});
 8816:                         }
 8817:                         my $newvaluestr;
 8818:                         if (@newvalues > 0) {
 8819:                             $newvaluestr = join(', ',@newvalues);
 8820:                         } else {
 8821:                             $newvaluestr = &mt('none');
 8822:                         }
 8823:                         if ($item eq 'default') {
 8824:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
 8825:                         } else {
 8826:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
 8827:                         }
 8828:                     }
 8829:                 } else {
 8830:                     my $newvalue;
 8831:                     if ($key eq 'run') {
 8832:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
 8833:                     } else {
 8834:                         $newvalue = $offon[$env{'form.'.$key}];
 8835:                     }
 8836:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
 8837:                 }
 8838:             }
 8839:             $resulttext .= '</ul>';
 8840:         } else {
 8841:             $resulttext = &mt('No changes made to autoupdates');
 8842:         }
 8843:     } else {
 8844:         $resulttext = '<span class="LC_error">'.
 8845: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 8846:     }
 8847:     return $resulttext;
 8848: }
 8849: 
 8850: sub modify_autocreate {
 8851:     my ($dom,%domconfig) = @_;
 8852:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
 8853:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
 8854:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
 8855:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
 8856:         }
 8857:     }
 8858:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
 8859:                  req => 'Auto-creation of validated requests for official courses',
 8860:                  xmldc => 'Identity of course creator of courses from XML files',
 8861:                );
 8862:     my @types = ('xml','req');
 8863:     foreach my $item (@types) {
 8864:         $newvals{$item} = $env{'form.autocreate_'.$item};
 8865:         $newvals{$item} =~ s/\D//g;
 8866:         $newvals{$item} = 0 if ($newvals{$item} eq '');
 8867:     }
 8868:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
 8869:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
 8870:     unless (exists($domcoords{$newvals{'xmldc'}})) {
 8871:         $newvals{'xmldc'} = '';
 8872:     } 
 8873:     %autocreatehash =  (
 8874:                         autocreate => { xml => $newvals{'xml'},
 8875:                                         req => $newvals{'req'},
 8876:                                       }
 8877:                        );
 8878:     if ($newvals{'xmldc'} ne '') {
 8879:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
 8880:     }
 8881:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
 8882:                                              $dom);
 8883:     if ($putresult eq 'ok') {
 8884:         my @items = @types;
 8885:         if ($newvals{'xml'}) {
 8886:             push(@items,'xmldc');
 8887:         }
 8888:         foreach my $item (@items) {
 8889:             if (exists($currautocreate{$item})) {
 8890:                 if ($currautocreate{$item} ne $newvals{$item}) {
 8891:                     $changes{$item} = 1;
 8892:                 }
 8893:             } elsif ($newvals{$item}) {
 8894:                 $changes{$item} = 1;
 8895:             }
 8896:         }
 8897:         if (keys(%changes) > 0) {
 8898:             my @offon = ('off','on'); 
 8899:             $resulttext = &mt('Changes made:').'<ul>';
 8900:             foreach my $item (@types) {
 8901:                 if ($changes{$item}) {
 8902:                     my $newtxt = $offon[$newvals{$item}];
 8903:                     $resulttext .= '<li>'.
 8904:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
 8905:                                        '<b>','</b>').
 8906:                                    '</li>';
 8907:                 }
 8908:             }
 8909:             if ($changes{'xmldc'}) {
 8910:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
 8911:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
 8912:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
 8913:             }
 8914:             $resulttext .= '</ul>';
 8915:         } else {
 8916:             $resulttext = &mt('No changes made to auto-creation settings');
 8917:         }
 8918:     } else {
 8919:         $resulttext = '<span class="LC_error">'.
 8920:             &mt('An error occurred: [_1]',$putresult).'</span>';
 8921:     }
 8922:     return $resulttext;
 8923: }
 8924: 
 8925: sub modify_directorysrch {
 8926:     my ($dom,%domconfig) = @_;
 8927:     my ($resulttext,%changes);
 8928:     my %currdirsrch;
 8929:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 8930:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
 8931:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
 8932:         }
 8933:     }
 8934:     my %title = ( available => 'Institutional directory search available',
 8935:                   localonly => 'Other domains can search institution',
 8936:                   lcavailable => 'LON-CAPA directory search available',
 8937:                   lclocalonly => 'Other domains can search LON-CAPA domain',
 8938:                   searchby => 'Search types',
 8939:                   searchtypes => 'Search latitude');
 8940:     my @offon = ('off','on');
 8941:     my @otherdoms = ('Yes','No');
 8942: 
 8943:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
 8944:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
 8945:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
 8946: 
 8947:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 8948:     if (keys(%{$usertypes}) == 0) {
 8949:         @cansearch = ('default');
 8950:     } else {
 8951:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
 8952:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
 8953:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
 8954:                     push(@{$changes{'cansearch'}},$type);
 8955:                 }
 8956:             }
 8957:             foreach my $type (@cansearch) {
 8958:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
 8959:                     push(@{$changes{'cansearch'}},$type);
 8960:                 }
 8961:             }
 8962:         } else {
 8963:             push(@{$changes{'cansearch'}},@cansearch);
 8964:         }
 8965:     }
 8966: 
 8967:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
 8968:         foreach my $by (@{$currdirsrch{'searchby'}}) {
 8969:             if (!grep(/^\Q$by\E$/,@searchby)) {
 8970:                 push(@{$changes{'searchby'}},$by);
 8971:             }
 8972:         }
 8973:         foreach my $by (@searchby) {
 8974:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
 8975:                 push(@{$changes{'searchby'}},$by);
 8976:             }
 8977:         }
 8978:     } else {
 8979:         push(@{$changes{'searchby'}},@searchby);
 8980:     }
 8981: 
 8982:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
 8983:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
 8984:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
 8985:                 push(@{$changes{'searchtypes'}},$type);
 8986:             }
 8987:         }
 8988:         foreach my $type (@searchtypes) {
 8989:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
 8990:                 push(@{$changes{'searchtypes'}},$type);
 8991:             }
 8992:         }
 8993:     } else {
 8994:         if (exists($currdirsrch{'searchtypes'})) {
 8995:             foreach my $type (@searchtypes) {  
 8996:                 if ($type ne $currdirsrch{'searchtypes'}) { 
 8997:                     push(@{$changes{'searchtypes'}},$type);
 8998:                 }
 8999:             }
 9000:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
 9001:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
 9002:             }   
 9003:         } else {
 9004:             push(@{$changes{'searchtypes'}},@searchtypes); 
 9005:         }
 9006:     }
 9007: 
 9008:     my %dirsrch_hash =  (
 9009:             directorysrch => { available => $env{'form.dirsrch_available'},
 9010:                                cansearch => \@cansearch,
 9011:                                localonly => $env{'form.dirsrch_instlocalonly'},
 9012:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
 9013:                                lcavailable => $env{'form.dirsrch_domavailable'},
 9014:                                searchby => \@searchby,
 9015:                                searchtypes => \@searchtypes,
 9016:                              }
 9017:             );
 9018:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
 9019:                                              $dom);
 9020:     if ($putresult eq 'ok') {
 9021:         if (exists($currdirsrch{'available'})) {
 9022:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
 9023:                  $changes{'available'} = 1;
 9024:              }
 9025:         } else {
 9026:             if ($env{'form.dirsrch_available'} eq '1') {
 9027:                 $changes{'available'} = 1;
 9028:             }
 9029:         }
 9030:         if (exists($currdirsrch{'lcavailable'})) {
 9031:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
 9032:                 $changes{'lcavailable'} = 1;
 9033:             }
 9034:         } else {
 9035:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
 9036:                 $changes{'lcavailable'} = 1;
 9037:             }
 9038:         }
 9039:         if (exists($currdirsrch{'localonly'})) {
 9040:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
 9041:                 $changes{'localonly'} = 1;
 9042:             }
 9043:         } else {
 9044:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
 9045:                 $changes{'localonly'} = 1;
 9046:             }
 9047:         }
 9048:         if (exists($currdirsrch{'lclocalonly'})) {
 9049:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
 9050:                 $changes{'lclocalonly'} = 1;
 9051:             }
 9052:         } else {
 9053:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
 9054:                 $changes{'lclocalonly'} = 1;
 9055:             }
 9056:         }
 9057:         if (keys(%changes) > 0) {
 9058:             $resulttext = &mt('Changes made:').'<ul>';
 9059:             if ($changes{'available'}) {
 9060:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
 9061:             }
 9062:             if ($changes{'lcavailable'}) {
 9063:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
 9064:             }
 9065:             if ($changes{'localonly'}) {
 9066:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
 9067:             }
 9068:             if ($changes{'lclocalonly'}) {
 9069:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
 9070:             }
 9071:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
 9072:                 my $chgtext;
 9073:                 if (ref($usertypes) eq 'HASH') {
 9074:                     if (keys(%{$usertypes}) > 0) {
 9075:                         foreach my $type (@{$types}) {
 9076:                             if (grep(/^\Q$type\E$/,@cansearch)) {
 9077:                                 $chgtext .= $usertypes->{$type}.'; ';
 9078:                             }
 9079:                         }
 9080:                         if (grep(/^default$/,@cansearch)) {
 9081:                             $chgtext .= $othertitle;
 9082:                         } else {
 9083:                             $chgtext =~ s/\; $//;
 9084:                         }
 9085:                         $resulttext .=
 9086:                             '<li>'.
 9087:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
 9088:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
 9089:                             '</li>';
 9090:                     }
 9091:                 }
 9092:             }
 9093:             if (ref($changes{'searchby'}) eq 'ARRAY') {
 9094:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
 9095:                 my $chgtext;
 9096:                 foreach my $type (@{$titleorder}) {
 9097:                     if (grep(/^\Q$type\E$/,@searchby)) {
 9098:                         if (defined($searchtitles->{$type})) {
 9099:                             $chgtext .= $searchtitles->{$type}.'; ';
 9100:                         }
 9101:                     }
 9102:                 }
 9103:                 $chgtext =~ s/\; $//;
 9104:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
 9105:             }
 9106:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
 9107:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
 9108:                 my $chgtext;
 9109:                 foreach my $type (@{$srchtypeorder}) {
 9110:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
 9111:                         if (defined($srchtypes_desc->{$type})) {
 9112:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
 9113:                         }
 9114:                     }
 9115:                 }
 9116:                 $chgtext =~ s/\; $//;
 9117:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
 9118:             }
 9119:             $resulttext .= '</ul>';
 9120:         } else {
 9121:             $resulttext = &mt('No changes made to directory search settings');
 9122:         }
 9123:     } else {
 9124:         $resulttext = '<span class="LC_error">'.
 9125:                       &mt('An error occurred: [_1]',$putresult).'</span>';
 9126:     }
 9127:     return $resulttext;
 9128: }
 9129: 
 9130: sub modify_contacts {
 9131:     my ($dom,$lastactref,%domconfig) = @_;
 9132:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
 9133:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 9134:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
 9135:             $currsetting{$key} = $domconfig{'contacts'}{$key};
 9136:         }
 9137:     }
 9138:     my (%others,%to,%bcc,%includestr,%includeloc);
 9139:     my @contacts = ('supportemail','adminemail');
 9140:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
 9141:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail');
 9142:     my @toggles = ('reporterrors','reportupdates');
 9143:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 9144:     foreach my $type (@mailings) {
 9145:         @{$newsetting{$type}} = 
 9146:             &Apache::loncommon::get_env_multiple('form.'.$type);
 9147:         foreach my $item (@contacts) {
 9148:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
 9149:                 $contacts_hash{contacts}{$type}{$item} = 1;
 9150:             } else {
 9151:                 $contacts_hash{contacts}{$type}{$item} = 0;
 9152:             }
 9153:         }
 9154:         $others{$type} = $env{'form.'.$type.'_others'};
 9155:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
 9156:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 9157:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
 9158:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
 9159:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
 9160:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
 9161:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
 9162:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
 9163:             }
 9164:         }
 9165:     }
 9166:     foreach my $item (@contacts) {
 9167:         $to{$item} = $env{'form.'.$item};
 9168:         $contacts_hash{'contacts'}{$item} = $to{$item};
 9169:     }
 9170:     foreach my $item (@toggles) {
 9171:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
 9172:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
 9173:         }
 9174:     }
 9175:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
 9176:         foreach my $field (@{$fields}) {
 9177:             if (ref($possoptions->{$field}) eq 'ARRAY') {
 9178:                 my $value = $env{'form.helpform_'.$field};
 9179:                 $value =~ s/^\s+|\s+$//g;
 9180:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
 9181:                     $contacts_hash{contacts}{'helpform'}{$field} = $value;
 9182:                     if ($field eq 'screenshot') {
 9183:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
 9184:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
 9185:                             $contacts_hash{contacts}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
 9186:                         }
 9187:                     }
 9188:                 }
 9189:             }
 9190:         }
 9191:     }
 9192:     if (keys(%currsetting) > 0) {
 9193:         foreach my $item (@contacts) {
 9194:             if ($to{$item} ne $currsetting{$item}) {
 9195:                 $changes{$item} = 1;
 9196:             }
 9197:         }
 9198:         foreach my $type (@mailings) {
 9199:             foreach my $item (@contacts) {
 9200:                 if (ref($currsetting{$type}) eq 'HASH') {
 9201:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
 9202:                         push(@{$changes{$type}},$item);
 9203:                     }
 9204:                 } else {
 9205:                     push(@{$changes{$type}},@{$newsetting{$type}});
 9206:                 }
 9207:             }
 9208:             if ($others{$type} ne $currsetting{$type}{'others'}) {
 9209:                 push(@{$changes{$type}},'others');
 9210:             }
 9211:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 9212:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
 9213:                     push(@{$changes{$type}},'bcc'); 
 9214:                 }
 9215:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
 9216:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
 9217:                     push(@{$changes{$type}},'include');
 9218:                 }
 9219:             }
 9220:         }
 9221:         if (ref($fields) eq 'ARRAY') {
 9222:             if (ref($currsetting{'helpform'}) eq 'HASH') {
 9223:                 foreach my $field (@{$fields}) {
 9224:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
 9225:                         push(@{$changes{'helpform'}},$field);
 9226:                     }
 9227:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
 9228:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
 9229:                             push(@{$changes{'helpform'}},'maxsize');
 9230:                         }
 9231:                     }
 9232:                 }
 9233:             } else {
 9234:                 foreach my $field (@{$fields}) {
 9235:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
 9236:                         push(@{$changes{'helpform'}},$field);
 9237:                     }
 9238:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
 9239:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
 9240:                             push(@{$changes{'helpform'}},'maxsize');
 9241:                         }
 9242:                     }
 9243:                 }
 9244:             }
 9245:         }
 9246:     } else {
 9247:         my %default;
 9248:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 9249:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 9250:         $default{'errormail'} = 'adminemail';
 9251:         $default{'packagesmail'} = 'adminemail';
 9252:         $default{'helpdeskmail'} = 'supportemail';
 9253:         $default{'otherdomsmail'} = 'supportemail';
 9254:         $default{'lonstatusmail'} = 'adminemail';
 9255:         $default{'requestsmail'} = 'adminemail';
 9256:         $default{'updatesmail'} = 'adminemail';
 9257:         foreach my $item (@contacts) {
 9258:            if ($to{$item} ne $default{$item}) {
 9259:                $changes{$item} = 1;
 9260:            }
 9261:         }
 9262:         foreach my $type (@mailings) {
 9263:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
 9264:                 push(@{$changes{$type}},@{$newsetting{$type}});
 9265:             }
 9266:             if ($others{$type} ne '') {
 9267:                 push(@{$changes{$type}},'others');
 9268:             }
 9269:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 9270:                 if ($bcc{$type} ne '') {
 9271:                     push(@{$changes{$type}},'bcc');
 9272:                 }
 9273:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
 9274:                     push(@{$changes{$type}},'include');
 9275:                 }
 9276:             }
 9277:         }
 9278:         if (ref($fields) eq 'ARRAY') {
 9279:             foreach my $field (@{$fields}) {
 9280:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
 9281:                     push(@{$changes{'helpform'}},$field);
 9282:                 }
 9283:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
 9284:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
 9285:                         push(@{$changes{'helpform'}},'maxsize');
 9286:                     }
 9287:                 }
 9288:             }
 9289:         }
 9290:     }
 9291:     foreach my $item (@toggles) {
 9292:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
 9293:             $changes{$item} = 1;
 9294:         } elsif ((!$env{'form.'.$item}) &&
 9295:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
 9296:             $changes{$item} = 1;
 9297:         }
 9298:     }
 9299:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
 9300:                                              $dom);
 9301:     if ($putresult eq 'ok') {
 9302:         if (keys(%changes) > 0) {
 9303:             &Apache::loncommon::devalidate_domconfig_cache($dom);
 9304:             if (ref($lastactref) eq 'HASH') {
 9305:                 $lastactref->{'domainconfig'} = 1;
 9306:             }
 9307:             my ($titles,$short_titles)  = &contact_titles();
 9308:             $resulttext = &mt('Changes made:').'<ul>';
 9309:             foreach my $item (@contacts) {
 9310:                 if ($changes{$item}) {
 9311:                     $resulttext .= '<li>'.$titles->{$item}.
 9312:                                     &mt(' set to: ').
 9313:                                     '<span class="LC_cusr_emph">'.
 9314:                                     $to{$item}.'</span></li>';
 9315:                 }
 9316:             }
 9317:             foreach my $type (@mailings) {
 9318:                 if (ref($changes{$type}) eq 'ARRAY') {
 9319:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 9320:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
 9321:                     } else {
 9322:                         $resulttext .= '<li>'.$titles->{$type}.': ';
 9323:                     }
 9324:                     my @text;
 9325:                     foreach my $item (@{$newsetting{$type}}) {
 9326:                         push(@text,$short_titles->{$item});
 9327:                     }
 9328:                     if ($others{$type} ne '') {
 9329:                         push(@text,$others{$type});
 9330:                     }
 9331:                     if (@text) {
 9332:                         $resulttext .= '<span class="LC_cusr_emph">'.
 9333:                                        join(', ',@text).'</span>';
 9334:                     }
 9335:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 9336:                         if ($bcc{$type} ne '') {
 9337:                             my $bcctext;
 9338:                             if (@text) {
 9339:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
 9340:                             } else {
 9341:                                 $bcctext = '(Bcc)';
 9342:                             }
 9343:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
 9344:                         } elsif (!@text) {
 9345:                             $resulttext .= &mt('No one');
 9346:                         }
 9347:                         if ($includestr{$type} ne '') {
 9348:                             if ($includeloc{$type} eq 'b') {
 9349:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
 9350:                             } elsif ($includeloc{$type} eq 's') {
 9351:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
 9352:                             }
 9353:                         }
 9354:                     } elsif (!@text) {
 9355:                         $resulttext .= &mt('No recipients');
 9356:                     }
 9357:                     $resulttext .= '</li>';
 9358:                 }
 9359:             }
 9360:             my @offon = ('off','on');
 9361:             if ($changes{'reporterrors'}) {
 9362:                 $resulttext .= '<li>'.
 9363:                                &mt('E-mail error reports to [_1] set to "'.
 9364:                                    $offon[$env{'form.reporterrors'}].'".',
 9365:                                    &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 9366:                                        &mt('LON-CAPA core group - MSU'),600,500)).
 9367:                                '</li>';
 9368:             }
 9369:             if ($changes{'reportupdates'}) {
 9370:                 $resulttext .= '<li>'.
 9371:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
 9372:                                     $offon[$env{'form.reportupdates'}].'".',
 9373:                                     &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 9374:                                         &mt('LON-CAPA core group - MSU'),600,500)).
 9375:                                 '</li>';
 9376:             }
 9377:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
 9378:                 my (@optional,@required,@unused,$maxsizechg);
 9379:                 foreach my $field (@{$changes{'helpform'}}) {
 9380:                     if ($field eq 'maxsize') {
 9381:                         $maxsizechg = 1;
 9382:                         next;
 9383:                     }
 9384:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
 9385:                         push(@optional,$field);
 9386:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
 9387:                         push(@unused,$field);
 9388:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
 9389:                         push(@required,$field);
 9390:                     }
 9391:                 }
 9392:                 if (@optional) {
 9393:                     $resulttext .= '<li>'.
 9394:                                    &mt('Help form fields changed to "Optional": [_1].',
 9395:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
 9396:                                    '</li>';
 9397:                 }
 9398:                 if (@required) {
 9399:                     $resulttext .= '<li>'.
 9400:                                    &mt('Help form fields changed to "Required": [_1].',
 9401:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
 9402:                                    '</li>';
 9403:                 }
 9404:                 if (@unused) {
 9405:                     $resulttext .= '<li>'.
 9406:                                    &mt('Help form fields changed to "Not shown": [_1].',
 9407:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
 9408:                                    '</li>';
 9409:                 }
 9410:                 if ($maxsizechg) {
 9411:                     $resulttext .= '<li>'.
 9412:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
 9413:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
 9414:                                    '</li>';
 9415: 
 9416:                 }
 9417:             }
 9418:             $resulttext .= '</ul>';
 9419:         } else {
 9420:             $resulttext = &mt('No changes made to contacts and form settings');
 9421:         }
 9422:     } else {
 9423:         $resulttext = '<span class="LC_error">'.
 9424:             &mt('An error occurred: [_1].',$putresult).'</span>';
 9425:     }
 9426:     return $resulttext;
 9427: }
 9428: 
 9429: sub modify_usercreation {
 9430:     my ($dom,%domconfig) = @_;
 9431:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
 9432:     my $warningmsg;
 9433:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9434:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
 9435:             if ($key eq 'cancreate') {
 9436:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
 9437:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
 9438:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
 9439:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
 9440:                             ($item eq 'recaptchaversion')) {
 9441:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
 9442:                         } else {
 9443:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
 9444:                         }
 9445:                     }
 9446:                 }
 9447:             } elsif ($key eq 'email_rule') {
 9448:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
 9449:             } else {
 9450:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
 9451:             }
 9452:         }
 9453:     }
 9454:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
 9455:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
 9456:     my @contexts = ('author','course','requestcrs');
 9457:     foreach my $item(@contexts) {
 9458:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
 9459:     }
 9460:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
 9461:         foreach my $item (@contexts) {
 9462:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
 9463:                 push(@{$changes{'cancreate'}},$item);
 9464:             }
 9465:         }
 9466:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
 9467:         foreach my $item (@contexts) {
 9468:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
 9469:                 if ($cancreate{$item} ne 'any') {
 9470:                     push(@{$changes{'cancreate'}},$item);
 9471:                 }
 9472:             } else {
 9473:                 if ($cancreate{$item} ne 'none') {
 9474:                     push(@{$changes{'cancreate'}},$item);
 9475:                 }
 9476:             }
 9477:         }
 9478:     } else {
 9479:         foreach my $item (@contexts)  {
 9480:             push(@{$changes{'cancreate'}},$item);
 9481:         }
 9482:     }
 9483: 
 9484:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
 9485:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
 9486:             if (!grep(/^\Q$type\E$/,@username_rule)) {
 9487:                 push(@{$changes{'username_rule'}},$type);
 9488:             }
 9489:         }
 9490:         foreach my $type (@username_rule) {
 9491:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
 9492:                 push(@{$changes{'username_rule'}},$type);
 9493:             }
 9494:         }
 9495:     } else {
 9496:         push(@{$changes{'username_rule'}},@username_rule);
 9497:     }
 9498: 
 9499:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
 9500:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
 9501:             if (!grep(/^\Q$type\E$/,@id_rule)) {
 9502:                 push(@{$changes{'id_rule'}},$type);
 9503:             }
 9504:         }
 9505:         foreach my $type (@id_rule) {
 9506:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
 9507:                 push(@{$changes{'id_rule'}},$type);
 9508:             }
 9509:         }
 9510:     } else {
 9511:         push(@{$changes{'id_rule'}},@id_rule);
 9512:     }
 9513: 
 9514:     my @authen_contexts = ('author','course','domain');
 9515:     my @authtypes = ('int','krb4','krb5','loc');
 9516:     my %authhash;
 9517:     foreach my $item (@authen_contexts) {
 9518:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
 9519:         foreach my $auth (@authtypes) {
 9520:             if (grep(/^\Q$auth\E$/,@authallowed)) {
 9521:                 $authhash{$item}{$auth} = 1;
 9522:             } else {
 9523:                 $authhash{$item}{$auth} = 0;
 9524:             }
 9525:         }
 9526:     }
 9527:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
 9528:         foreach my $item (@authen_contexts) {
 9529:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
 9530:                 foreach my $auth (@authtypes) {
 9531:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
 9532:                         push(@{$changes{'authtypes'}},$item);
 9533:                         last;
 9534:                     }
 9535:                 }
 9536:             }
 9537:         }
 9538:     } else {
 9539:         foreach my $item (@authen_contexts) {
 9540:             push(@{$changes{'authtypes'}},$item);
 9541:         }
 9542:     }
 9543: 
 9544:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
 9545:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
 9546:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
 9547:     $save_usercreate{'id_rule'} = \@id_rule;
 9548:     $save_usercreate{'username_rule'} = \@username_rule,
 9549:     $save_usercreate{'authtypes'} = \%authhash;
 9550: 
 9551:     my %usercreation_hash =  (
 9552:         usercreation     => \%save_usercreate,
 9553:     );
 9554: 
 9555:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
 9556:                                              $dom);
 9557: 
 9558:     if ($putresult eq 'ok') {
 9559:         if (keys(%changes) > 0) {
 9560:             $resulttext = &mt('Changes made:').'<ul>';
 9561:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
 9562:                 my %lt = &usercreation_types();
 9563:                 foreach my $type (@{$changes{'cancreate'}}) {
 9564:                     my $chgtext = $lt{$type}.', ';
 9565:                     if ($cancreate{$type} eq 'none') {
 9566:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
 9567:                     } elsif ($cancreate{$type} eq 'any') {
 9568:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
 9569:                     } elsif ($cancreate{$type} eq 'official') {
 9570:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
 9571:                     } elsif ($cancreate{$type} eq 'unofficial') {
 9572:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
 9573:                     }
 9574:                     $resulttext .= '<li>'.$chgtext.'</li>';
 9575:                 }
 9576:             }
 9577:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
 9578:                 my ($rules,$ruleorder) = 
 9579:                     &Apache::lonnet::inst_userrules($dom,'username');
 9580:                 my $chgtext = '<ul>';
 9581:                 foreach my $type (@username_rule) {
 9582:                     if (ref($rules->{$type}) eq 'HASH') {
 9583:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
 9584:                     }
 9585:                 }
 9586:                 $chgtext .= '</ul>';
 9587:                 if (@username_rule > 0) {
 9588:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
 9589:                 } else {
 9590:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
 9591:                 }
 9592:             }
 9593:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
 9594:                 my ($idrules,$idruleorder) = 
 9595:                     &Apache::lonnet::inst_userrules($dom,'id');
 9596:                 my $chgtext = '<ul>';
 9597:                 foreach my $type (@id_rule) {
 9598:                     if (ref($idrules->{$type}) eq 'HASH') {
 9599:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
 9600:                     }
 9601:                 }
 9602:                 $chgtext .= '</ul>';
 9603:                 if (@id_rule > 0) {
 9604:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
 9605:                 } else {
 9606:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
 9607:                 }
 9608:             }
 9609:             my %authname = &authtype_names();
 9610:             my %context_title = &context_names();
 9611:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
 9612:                 my $chgtext = '<ul>';
 9613:                 foreach my $type (@{$changes{'authtypes'}}) {
 9614:                     my @allowed;
 9615:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
 9616:                     foreach my $auth (@authtypes) {
 9617:                         if ($authhash{$type}{$auth}) {
 9618:                             push(@allowed,$authname{$auth});
 9619:                         }
 9620:                     }
 9621:                     if (@allowed > 0) {
 9622:                         $chgtext .= join(', ',@allowed).'</li>';
 9623:                     } else {
 9624:                         $chgtext .= &mt('none').'</li>';
 9625:                     }
 9626:                 }
 9627:                 $chgtext .= '</ul>';
 9628:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
 9629:                 $resulttext .= '</li>';
 9630:             }
 9631:             $resulttext .= '</ul>';
 9632:         } else {
 9633:             $resulttext = &mt('No changes made to user creation settings');
 9634:         }
 9635:     } else {
 9636:         $resulttext = '<span class="LC_error">'.
 9637:             &mt('An error occurred: [_1]',$putresult).'</span>';
 9638:     }
 9639:     if ($warningmsg ne '') {
 9640:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
 9641:     }
 9642:     return $resulttext;
 9643: }
 9644: 
 9645: sub modify_selfcreation {
 9646:     my ($dom,%domconfig) = @_;
 9647:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%changes,%cancreate);
 9648:     my (%save_usercreate,%save_usermodify);
 9649:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 9650:     if (ref($types) eq 'ARRAY') {
 9651:         $usertypes->{'default'} = $othertitle;
 9652:         push(@{$types},'default');
 9653:     }
 9654: #
 9655: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
 9656: #
 9657:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9658:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
 9659:             if ($key eq 'cancreate') {
 9660:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
 9661:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
 9662:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
 9663:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') || 
 9664:                             ($item eq 'recaptchaversion') ||
 9665:                             ($item eq 'emailusername') || ($item eq 'notify') ||
 9666:                             ($item eq 'selfcreateprocessing') || ($item eq 'shibenv')) {
 9667:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
 9668:                         } else {
 9669:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
 9670:                         }
 9671:                     }
 9672:                 }
 9673:             } elsif ($key eq 'email_rule') {
 9674:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
 9675:             } else {
 9676:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
 9677:             }
 9678:         }
 9679:     }
 9680: #
 9681: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
 9682: #
 9683:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
 9684:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
 9685:             if ($key eq 'selfcreate') {
 9686:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
 9687:             } else {
 9688:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
 9689:             }
 9690:         }
 9691:     }
 9692: 
 9693:     my @contexts = ('selfcreate');
 9694:     @{$cancreate{'selfcreate'}} = ();
 9695:     %{$cancreate{'emailusername'}} = ();
 9696:     @{$cancreate{'statustocreate'}} = ();
 9697:     %{$cancreate{'selfcreateprocessing'}} = ();
 9698:     %{$cancreate{'shibenv'}} = ();
 9699:     my %selfcreatetypes = (
 9700:                              sso   => 'users authenticated by institutional single sign on',
 9701:                              login => 'users authenticated by institutional log-in',
 9702:                              email => 'users who provide a valid e-mail address for use as username',
 9703:                           );
 9704: #
 9705: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
 9706: # is permitted.
 9707: #
 9708: 
 9709:     my @statuses;
 9710:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 9711:         if (ref($domconfig{'inststatus'}{'inststatusguest'}) eq 'ARRAY') {
 9712:             @statuses = @{$domconfig{'inststatus'}{'inststatusguest'}};
 9713:         }
 9714:     }
 9715:     push(@statuses,'default');
 9716: 
 9717:     foreach my $item ('login','sso','email') {
 9718:         if ($item eq 'email') {
 9719:             if ($env{'form.cancreate_email'}) {
 9720:                 push(@{$cancreate{'selfcreate'}},'email');
 9721:                 push(@contexts,'selfcreateprocessing');
 9722:                 foreach my $type (@statuses) {
 9723:                     if ($type eq 'default') {
 9724:                         $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess'};
 9725:                     } else { 
 9726:                         $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
 9727:                     }
 9728:                 }
 9729:             }
 9730:         } else {
 9731:             if ($env{'form.cancreate_'.$item}) {
 9732:                 push(@{$cancreate{'selfcreate'}},$item);
 9733:             }
 9734:         }
 9735:     }
 9736:     my (@email_rule,%userinfo,%savecaptcha);
 9737:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 9738: #
 9739: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
 9740: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
 9741: #
 9742: 
 9743:     if ($env{'form.cancreate_email'}) {
 9744:         push(@contexts,'emailusername');
 9745:         if (ref($types) eq 'ARRAY') {
 9746:             foreach my $type (@{$types}) {
 9747:                 if (ref($infofields) eq 'ARRAY') {
 9748:                     foreach my $field (@{$infofields}) {
 9749:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
 9750:                             $cancreate{'emailusername'}{$type}{$field} = $1;
 9751:                         }
 9752:                     }
 9753:                 }
 9754:             }
 9755:         }
 9756: #
 9757: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
 9758: # queued requests for self-creation of account using e-mail address as username
 9759: #
 9760: 
 9761:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
 9762:         @approvalnotify = sort(@approvalnotify);
 9763:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
 9764:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
 9765:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
 9766:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
 9767:                     push(@{$changes{'cancreate'}},'notify');
 9768:                 }
 9769:             } else {
 9770:                 if ($cancreate{'notify'}{'approval'}) {
 9771:                     push(@{$changes{'cancreate'}},'notify');
 9772:                 }
 9773:             }
 9774:         } elsif ($cancreate{'notify'}{'approval'}) {
 9775:             push(@{$changes{'cancreate'}},'notify');
 9776:         }
 9777: 
 9778: #
 9779: # Retrieve rules (if any) governing types of e-mail address which may be used as a username
 9780: #
 9781:         @email_rule = &Apache::loncommon::get_env_multiple('form.email_rule');
 9782:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
 9783:         if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
 9784:             if (@{$curr_usercreation{'email_rule'}} > 0) {
 9785:                 foreach my $type (@{$curr_usercreation{'email_rule'}}) {
 9786:                     if (!grep(/^\Q$type\E$/,@email_rule)) {
 9787:                         push(@{$changes{'email_rule'}},$type);
 9788:                     }
 9789:                 }
 9790:             }
 9791:             if (@email_rule > 0) {
 9792:                 foreach my $type (@email_rule) {
 9793:                     if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'email_rule'}})) {
 9794:                         push(@{$changes{'email_rule'}},$type);
 9795:                     }
 9796:                 }
 9797:             }
 9798:         } elsif (@email_rule > 0) {
 9799:             push(@{$changes{'email_rule'}},@email_rule);
 9800:         }
 9801:     }
 9802: #  
 9803: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
 9804: # institutional log-in.
 9805: #
 9806:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
 9807:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 9808:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
 9809:                ($domdefaults{'auth_def'} eq 'localauth'))) {
 9810:             $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.').' '.
 9811:                           &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.');
 9812:         }
 9813:     }
 9814:     my @fields = ('lastname','firstname','middlename','generation',
 9815:                   'permanentemail','id');
 9816:     my @shibfields = (@fields,'inststatus');
 9817:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 9818: #
 9819: # Where usernames may created for institutional log-in and/or institutional single sign on:
 9820: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
 9821: # may self-create accounts 
 9822: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
 9823: # which the user may supply, if institutional data is unavailable.
 9824: #
 9825:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
 9826:         if (ref($types) eq 'ARRAY') {
 9827:             if (@{$types} > 1) {
 9828:                 @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
 9829:                 push(@contexts,'statustocreate');
 9830:             } else {
 9831:                 undef($cancreate{'statustocreate'});
 9832:             } 
 9833:             foreach my $type (@{$types}) {
 9834:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
 9835:                 foreach my $field (@fields) {
 9836:                     if (grep(/^\Q$field\E$/,@modifiable)) {
 9837:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
 9838:                     } else {
 9839:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
 9840:                     }
 9841:                 }
 9842:             }
 9843:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
 9844:                 foreach my $type (@{$types}) {
 9845:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
 9846:                         foreach my $field (@fields) {
 9847:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
 9848:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
 9849:                                 push(@{$changes{'selfcreate'}},$type);
 9850:                                 last;
 9851:                             }
 9852:                         }
 9853:                     }
 9854:                 }
 9855:             } else {
 9856:                 foreach my $type (@{$types}) {
 9857:                     push(@{$changes{'selfcreate'}},$type);
 9858:                 }
 9859:             }
 9860:         }
 9861:         foreach my $field (@shibfields) {
 9862:             if ($env{'form.shibenv_'.$field} ne '') {
 9863:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
 9864:             }
 9865:         }
 9866:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
 9867:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
 9868:                 foreach my $field (@shibfields) {
 9869:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
 9870:                         push(@{$changes{'cancreate'}},'shibenv');
 9871:                     }
 9872:                 }
 9873:             } else {
 9874:                 foreach my $field (@shibfields) {
 9875:                     if ($env{'form.shibenv_'.$field}) {
 9876:                         push(@{$changes{'cancreate'}},'shibenv');
 9877:                         last;
 9878:                     }
 9879:                 }
 9880:             }
 9881:         }
 9882:     }
 9883:     foreach my $item (@contexts) {
 9884:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
 9885:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
 9886:                 if (ref($cancreate{$item}) eq 'ARRAY') {
 9887:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
 9888:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
 9889:                             push(@{$changes{'cancreate'}},$item);
 9890:                         }
 9891:                     }
 9892:                 }
 9893:             }
 9894:             if (ref($cancreate{$item}) eq 'ARRAY') {
 9895:                 foreach my $type (@{$cancreate{$item}}) {
 9896:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
 9897:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
 9898:                             push(@{$changes{'cancreate'}},$item);
 9899:                         }
 9900:                     }
 9901:                 }
 9902:             }
 9903:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
 9904:             if (ref($cancreate{$item}) eq 'HASH') {
 9905:                 foreach my $curr (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
 9906:                     if (ref($curr_usercreation{'cancreate'}{$item}{$curr}) eq 'HASH') {
 9907:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$curr}})) {
 9908:                             unless ($curr_usercreation{'cancreate'}{$item}{$curr}{$field} eq $cancreate{$item}{$curr}{$field}) {
 9909:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
 9910:                                     push(@{$changes{'cancreate'}},$item);
 9911:                                 }
 9912:                             }
 9913:                         }
 9914:                     } elsif ($item eq 'selfcreateprocessing') {
 9915:                         if ($cancreate{$item}{$curr} ne $curr_usercreation{'cancreate'}{$item}{$curr}) {
 9916:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
 9917:                                 push(@{$changes{'cancreate'}},$item);
 9918:                             }
 9919:                         }
 9920:                     } else {
 9921:                         if (!$cancreate{$item}{$curr}) {
 9922:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
 9923:                                 push(@{$changes{'cancreate'}},$item);
 9924:                             }
 9925:                         }
 9926:                     }
 9927:                 }
 9928:                 foreach my $field (keys(%{$cancreate{$item}})) {
 9929:                     if (ref($cancreate{$item}{$field}) eq 'HASH') {
 9930:                         foreach my $inner (keys(%{$cancreate{$item}{$field}})) {
 9931:                             if (ref($curr_usercreation{'cancreate'}{$item}{$field}) eq 'HASH') {
 9932:                                 unless ($curr_usercreation{'cancreate'}{$item}{$field}{$inner} eq $cancreate{$item}{$field}{$inner}) {
 9933:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
 9934:                                         push(@{$changes{'cancreate'}},$item);
 9935:                                     }
 9936:                                 }
 9937:                             } else {
 9938:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
 9939:                                     push(@{$changes{'cancreate'}},$item);
 9940:                                 }
 9941:                             }
 9942:                         }
 9943:                     } elsif ($item eq 'selfcreateprocessing') {
 9944:                         if ($cancreate{$item}{$field} ne $curr_usercreation{'cancreate'}{$item}{$field}) {
 9945:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
 9946:                                 push(@{$changes{'cancreate'}},$item);
 9947:                             }
 9948:                         }
 9949:                     } else {
 9950:                         if (!$curr_usercreation{'cancreate'}{$item}{$field}) {
 9951:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
 9952:                                 push(@{$changes{'cancreate'}},$item);
 9953:                             }
 9954:                         }
 9955:                     }
 9956:                 }
 9957:             }
 9958:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
 9959:             if (ref($cancreate{$item}) eq 'ARRAY') {
 9960:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
 9961:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
 9962:                         push(@{$changes{'cancreate'}},$item);
 9963:                     }
 9964:                 }
 9965:             } elsif (ref($cancreate{$item}) eq 'HASH') {
 9966:                 if (!$cancreate{$item}{$curr_usercreation{'cancreate'}{$item}}) {
 9967:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
 9968:                         push(@{$changes{'cancreate'}},$item);
 9969:                     }
 9970:                 }
 9971:             }
 9972:         } elsif ($item eq 'emailusername') {
 9973:             if (ref($cancreate{$item}) eq 'HASH') {
 9974:                 foreach my $type (keys(%{$cancreate{$item}})) {
 9975:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
 9976:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
 9977:                             if ($cancreate{$item}{$type}{$field}) {
 9978:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
 9979:                                     push(@{$changes{'cancreate'}},$item);
 9980:                                 }
 9981:                                 last;
 9982:                             }
 9983:                         }
 9984:                     }
 9985:                 }
 9986:             }
 9987:         }
 9988:     }
 9989: #
 9990: # Populate %save_usercreate hash with updates to self-creation configuration.
 9991: #
 9992:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
 9993:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
 9994:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
 9995:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
 9996:     if (ref($cancreate{'notify'}) eq 'HASH') {
 9997:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
 9998:     }
 9999:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
10000:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
10001:     }
10002:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
10003:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
10004:     }
10005:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
10006:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
10007:     }
10008:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
10009:     $save_usercreate{'emailrule'} = \@email_rule;
10010: 
10011:     my %userconfig_hash = (
10012:             usercreation     => \%save_usercreate,
10013:             usermodification => \%save_usermodify,
10014:     );
10015:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
10016:                                              $dom);
10017: #
10018: # Accumulate details of changes to domain cofiguration for self-creation of usernames in $resulttext
10019: #
10020:     if ($putresult eq 'ok') {
10021:         if (keys(%changes) > 0) {
10022:             $resulttext = &mt('Changes made:').'<ul>';
10023:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
10024:                 my %lt = &selfcreation_types();
10025:                 foreach my $type (@{$changes{'cancreate'}}) {
10026:                     my $chgtext;
10027:                     if ($type eq 'selfcreate') {
10028:                         if (@{$cancreate{$type}} == 0) {
10029:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
10030:                         } else {
10031:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
10032:                                         '<ul>';
10033:                             foreach my $case (@{$cancreate{$type}}) {
10034:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
10035:                             }
10036:                             $chgtext .= '</ul>';
10037:                             if (ref($cancreate{$type}) eq 'ARRAY') {
10038:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
10039:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
10040:                                         if (@{$cancreate{'statustocreate'}} == 0) {
10041:                                             $chgtext .= '<br />'.
10042:                                                         '<span class="LC_warning">'.
10043:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
10044:                                                         '</span>';
10045:                                         }
10046:                                     }
10047:                                 }
10048:                             }
10049:                         }
10050:                     } elsif ($type eq 'shibenv') {
10051:                         if (keys(%{$cancreate{$type}}) == 0) {
10052:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information'); 
10053:                         } else {
10054:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
10055:                                         '<ul>';
10056:                             foreach my $field (@shibfields) {
10057:                                 next if ($cancreate{$type}{$field} eq '');
10058:                                 if ($field eq 'inststatus') {
10059:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
10060:                                 } else {
10061:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
10062:                                 }
10063:                             }
10064:                             $chgtext .= '</ul>';
10065:                         }  
10066:                     } elsif ($type eq 'statustocreate') {
10067:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
10068:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
10069:                             if (@{$cancreate{'selfcreate'}} > 0) {
10070:                                 if (@{$cancreate{'statustocreate'}} == 0) {
10071:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
10072:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
10073:                                         $chgtext .= '<br />'.
10074:                                                     '<span class="LC_warning">'.
10075:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
10076:                                                     '</span>';
10077:                                     }
10078:                                 } elsif (ref($usertypes) eq 'HASH') {
10079:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
10080:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
10081:                                     } else {
10082:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
10083:                                     }
10084:                                     $chgtext .= '<ul>';
10085:                                     foreach my $case (@{$cancreate{$type}}) {
10086:                                         if ($case eq 'default') {
10087:                                             $chgtext .= '<li>'.$othertitle.'</li>';
10088:                                         } else {
10089:                                             $chgtext .= '<li>'.$usertypes->{$case}.'</li>';
10090:                                         }
10091:                                     }
10092:                                     $chgtext .= '</ul>';
10093:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
10094:                                         $chgtext .= '<br /><span class="LC_warning">'.
10095:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
10096:                                                     '</span>';
10097:                                     }
10098:                                 }
10099:                             } else {
10100:                                 if (@{$cancreate{$type}} == 0) {
10101:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
10102:                                 } else {
10103:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
10104:                                 }
10105:                             }
10106:                         }
10107:                     } elsif ($type eq 'selfcreateprocessing') {
10108:                         my %choices = &Apache::lonlocal::texthash (
10109:                                                                     automatic => 'Automatic approval',
10110:                                                                     approval  => 'Queued for approval',
10111:                                                                   );
10112:                         if (@statuses > 1) {
10113:                             $chgtext .= &mt('Processing of requests to create account with e-mail address as username set as follows:'). 
10114:                                         '<ul>';
10115:                            foreach my $type (@statuses) {
10116:                                if ($type eq 'default') {
10117:                                    $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$type}}.'</li>';
10118:                                } else {
10119:                                    $chgtext .= '<li>'.$usertypes->{$type}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$type}}.'</li>';
10120:                                }
10121:                            }
10122:                            $chgtext .= '</ul>';
10123:                         } else {
10124:                            $chgtext .= &mt('Processing of requests to create account with e-mail address as username set to: "[_1]"',
10125:                                          $choices{$cancreate{'selfcreateprocessing'}{'default'}});
10126:                         }
10127:                     } elsif ($type eq 'captcha') {
10128:                         if ($savecaptcha{$type} eq 'notused') {
10129:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
10130:                         } else {
10131:                             my %captchas = &captcha_phrases();
10132:                             if ($captchas{$savecaptcha{$type}}) {
10133:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
10134:                             } else {
10135:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
10136:                             }
10137:                         }
10138:                     } elsif ($type eq 'recaptchakeys') {
10139:                         my ($privkey,$pubkey);
10140:                         if (ref($savecaptcha{$type}) eq 'HASH') {
10141:                             $pubkey = $savecaptcha{$type}{'public'};
10142:                             $privkey = $savecaptcha{$type}{'private'};
10143:                         }
10144:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
10145:                         if (!$pubkey) {
10146:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
10147:                         } else {
10148:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
10149:                         }
10150:                         if (!$privkey) {
10151:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
10152:                         } else {
10153:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
10154:                         }
10155:                         $chgtext .= '</ul>';
10156:                     } elsif ($type eq 'recaptchaversion') {
10157:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
10158:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
10159:                         }
10160:                     } elsif ($type eq 'emailusername') {
10161:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
10162:                             if (ref($types) eq 'ARRAY') {
10163:                                 foreach my $type (@{$types}) {
10164:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
10165:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
10166:                                             $chgtext .= &mt('When self-creating account with e-mail as username, the following information will be provided by [_1]:',"'$usertypes->{$type}'").
10167:                                                     '<ul>';
10168:                                             foreach my $field (@{$infofields}) {
10169:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
10170:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
10171:                                                 }
10172:                                             }
10173:                                             $chgtext .= '</ul>';
10174:                                         } else {
10175:                                             $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 />';
10176:                                         }
10177:                                     } else {
10178:                                         $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 />';
10179:                                     }
10180:                                 }
10181:                             }
10182:                         }
10183:                     } elsif ($type eq 'notify') {
10184:                         $chgtext = &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
10185:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
10186:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
10187:                                 if ($cancreate{'notify'}{'approval'}) {
10188:                                     $chgtext = &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
10189:                                 }
10190:                             }
10191:                         }
10192:                     }
10193:                     if ($chgtext) {
10194:                         $resulttext .= '<li>'.$chgtext.'</li>';
10195:                     }
10196:                 }
10197:             }
10198:             if (ref($changes{'email_rule'}) eq 'ARRAY') {
10199:                 my ($emailrules,$emailruleorder) =
10200:                     &Apache::lonnet::inst_userrules($dom,'email');
10201:                 my $chgtext = '<ul>';
10202:                 foreach my $type (@email_rule) {
10203:                     if (ref($emailrules->{$type}) eq 'HASH') {
10204:                         $chgtext .= '<li>'.$emailrules->{$type}{'name'}.'</li>';
10205:                     }
10206:                 }
10207:                 $chgtext .= '</ul>';
10208:                 if (@email_rule > 0) {
10209:                     $resulttext .= '<li>'.
10210:                                    &mt('Accounts may not be created by users self-enrolling with e-mail addresses of the following types: ').
10211:                                        $chgtext.
10212:                                    '</li>';
10213:                 } else {
10214:                     $resulttext .= '<li>'.
10215:                                    &mt('There are now no restrictions on e-mail addresses which may be used as a username when self-enrolling.').
10216:                                    '</li>';
10217:                 }
10218:             }
10219:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
10220:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
10221:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
10222:                 foreach my $type (@{$changes{'selfcreate'}}) {
10223:                     my $typename = $type;
10224:                     if (ref($usertypes) eq 'HASH') {
10225:                         if ($usertypes->{$type} ne '') {
10226:                             $typename = $usertypes->{$type};
10227:                         }
10228:                     }
10229:                     my @modifiable;
10230:                     $resulttext .= '<li>'.
10231:                                     &mt('Self-creation of account by users with status: [_1]',
10232:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
10233:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
10234:                     foreach my $field (@fields) {
10235:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
10236:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
10237:                         }
10238:                     }
10239:                     if (@modifiable > 0) {
10240:                         $resulttext .= join(', ',@modifiable);
10241:                     } else {
10242:                         $resulttext .= &mt('none');
10243:                     }
10244:                     $resulttext .= '</li>';
10245:                 }
10246:                 $resulttext .= '</ul></li>';
10247:             }
10248:             $resulttext .= '</ul>';
10249:         } else {
10250:             $resulttext = &mt('No changes made to self-creation settings');
10251:         }
10252:     } else {
10253:         $resulttext = '<span class="LC_error">'.
10254:             &mt('An error occurred: [_1]',$putresult).'</span>';
10255:     }
10256:     if ($warningmsg ne '') {
10257:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
10258:     }
10259:     return $resulttext;
10260: }
10261: 
10262: sub process_captcha {
10263:     my ($container,$changes,$newsettings,$current) = @_;
10264:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH') || (ref($current) eq 'HASH'));
10265:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
10266:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
10267:         $newsettings->{'captcha'} = 'original';
10268:     }
10269:     if ($current->{'captcha'} ne $newsettings->{'captcha'}) {
10270:         if ($container eq 'cancreate') {
10271:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
10272:                 push(@{$changes->{'cancreate'}},'captcha');
10273:             } elsif (!defined($changes->{'cancreate'})) {
10274:                 $changes->{'cancreate'} = ['captcha'];
10275:             }
10276:         } else {
10277:             $changes->{'captcha'} = 1;
10278:         }
10279:     }
10280:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
10281:     if ($newsettings->{'captcha'} eq 'recaptcha') {
10282:         $newpub = $env{'form.'.$container.'_recaptchapub'};
10283:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
10284:         $newpub =~ s/[^\w\-]//g;
10285:         $newpriv =~ s/[^\w\-]//g;
10286:         $newsettings->{'recaptchakeys'} = {
10287:                                              public  => $newpub,
10288:                                              private => $newpriv,
10289:                                           };
10290:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
10291:         $newversion =~ s/\D//g;
10292:         if ($newversion ne '2') {
10293:             $newversion = 1;
10294:         }
10295:         $newsettings->{'recaptchaversion'} = $newversion;
10296:     }
10297:     if (ref($current->{'recaptchakeys'}) eq 'HASH') {
10298:         $currpub = $current->{'recaptchakeys'}{'public'};
10299:         $currpriv = $current->{'recaptchakeys'}{'private'};
10300:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
10301:             $newsettings->{'recaptchakeys'} = {
10302:                                                  public  => '',
10303:                                                  private => '',
10304:                                               }
10305:         }
10306:     }
10307:     if ($current->{'captcha'} eq 'recaptcha') {
10308:         $currversion = $current->{'recaptchaversion'};
10309:         if ($currversion ne '2') {
10310:             $currversion = 1;
10311:         }
10312:     }
10313:     if ($currversion ne $newversion) {
10314:         if ($container eq 'cancreate') {
10315:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
10316:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
10317:             } elsif (!defined($changes->{'cancreate'})) {
10318:                 $changes->{'cancreate'} = ['recaptchaversion'];
10319:             }
10320:         } else {
10321:             $changes->{'recaptchaversion'} = 1;
10322:         }
10323:     }
10324:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
10325:         if ($container eq 'cancreate') {
10326:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
10327:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
10328:             } elsif (!defined($changes->{'cancreate'})) {
10329:                 $changes->{'cancreate'} = ['recaptchakeys'];
10330:             }
10331:         } else {
10332:             $changes->{'recaptchakeys'} = 1;
10333:         }
10334:     }
10335:     return;
10336: }
10337: 
10338: sub modify_usermodification {
10339:     my ($dom,%domconfig) = @_;
10340:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
10341:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
10342:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
10343:             if ($key eq 'selfcreate') {
10344:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
10345:             } else {  
10346:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
10347:             }
10348:         }
10349:     }
10350:     my @contexts = ('author','course');
10351:     my %context_title = (
10352:                            author => 'In author context',
10353:                            course => 'In course context',
10354:                         );
10355:     my @fields = ('lastname','firstname','middlename','generation',
10356:                   'permanentemail','id');
10357:     my %roles = (
10358:                   author => ['ca','aa'],
10359:                   course => ['st','ep','ta','in','cr'],
10360:                 );
10361:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
10362:     foreach my $context (@contexts) {
10363:         foreach my $role (@{$roles{$context}}) {
10364:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
10365:             foreach my $item (@fields) {
10366:                 if (grep(/^\Q$item\E$/,@modifiable)) {
10367:                     $modifyhash{$context}{$role}{$item} = 1;
10368:                 } else {
10369:                     $modifyhash{$context}{$role}{$item} = 0;
10370:                 }
10371:             }
10372:         }
10373:         if (ref($curr_usermodification{$context}) eq 'HASH') {
10374:             foreach my $role (@{$roles{$context}}) {
10375:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
10376:                     foreach my $field (@fields) {
10377:                         if ($modifyhash{$context}{$role}{$field} ne 
10378:                                 $curr_usermodification{$context}{$role}{$field}) {
10379:                             push(@{$changes{$context}},$role);
10380:                             last;
10381:                         }
10382:                     }
10383:                 }
10384:             }
10385:         } else {
10386:             foreach my $context (@contexts) {
10387:                 foreach my $role (@{$roles{$context}}) {
10388:                     push(@{$changes{$context}},$role);
10389:                 }
10390:             }
10391:         }
10392:     }
10393:     my %usermodification_hash =  (
10394:                                    usermodification => \%modifyhash,
10395:                                  );
10396:     my $putresult = &Apache::lonnet::put_dom('configuration',
10397:                                              \%usermodification_hash,$dom);
10398:     if ($putresult eq 'ok') {
10399:         if (keys(%changes) > 0) {
10400:             $resulttext = &mt('Changes made: ').'<ul>';
10401:             foreach my $context (@contexts) {
10402:                 if (ref($changes{$context}) eq 'ARRAY') {
10403:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
10404:                     if (ref($changes{$context}) eq 'ARRAY') {
10405:                         foreach my $role (@{$changes{$context}}) {
10406:                             my $rolename;
10407:                             if ($role eq 'cr') {
10408:                                 $rolename = &mt('Custom');
10409:                             } else {
10410:                                 $rolename = &Apache::lonnet::plaintext($role);
10411:                             }
10412:                             my @modifiable;
10413:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
10414:                             foreach my $field (@fields) {
10415:                                 if ($modifyhash{$context}{$role}{$field}) {
10416:                                     push(@modifiable,$fieldtitles{$field});
10417:                                 }
10418:                             }
10419:                             if (@modifiable > 0) {
10420:                                 $resulttext .= join(', ',@modifiable);
10421:                             } else {
10422:                                 $resulttext .= &mt('none'); 
10423:                             }
10424:                             $resulttext .= '</li>';
10425:                         }
10426:                         $resulttext .= '</ul></li>';
10427:                     }
10428:                 }
10429:             }
10430:             $resulttext .= '</ul>';
10431:         } else {
10432:             $resulttext = &mt('No changes made to user modification settings');
10433:         }
10434:     } else {
10435:         $resulttext = '<span class="LC_error">'.
10436:             &mt('An error occurred: [_1]',$putresult).'</span>';
10437:     }
10438:     return $resulttext;
10439: }
10440: 
10441: sub modify_defaults {
10442:     my ($dom,$lastactref,%domconfig) = @_;
10443:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
10444:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
10445:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def','portal_def');
10446:     my @authtypes = ('internal','krb4','krb5','localauth');
10447:     foreach my $item (@items) {
10448:         $newvalues{$item} = $env{'form.'.$item};
10449:         if ($item eq 'auth_def') {
10450:             if ($newvalues{$item} ne '') {
10451:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
10452:                     push(@errors,$item);
10453:                 }
10454:             }
10455:         } elsif ($item eq 'lang_def') {
10456:             if ($newvalues{$item} ne '') {
10457:                 if ($newvalues{$item} =~ /^(\w+)/) {
10458:                     my $langcode = $1;
10459:                     if ($langcode ne 'x_chef') {
10460:                         if (code2language($langcode) eq '') {
10461:                             push(@errors,$item);
10462:                         }
10463:                     }
10464:                 } else {
10465:                     push(@errors,$item);
10466:                 }
10467:             }
10468:         } elsif ($item eq 'timezone_def') {
10469:             if ($newvalues{$item} ne '') {
10470:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
10471:                     push(@errors,$item);   
10472:                 }
10473:             }
10474:         } elsif ($item eq 'datelocale_def') {
10475:             if ($newvalues{$item} ne '') {
10476:                 my @datelocale_ids = DateTime::Locale->ids();
10477:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
10478:                     push(@errors,$item);
10479:                 }
10480:             }
10481:         } elsif ($item eq 'portal_def') {
10482:             if ($newvalues{$item} ne '') {
10483:                 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])\/?$/) {
10484:                     push(@errors,$item);
10485:                 }
10486:             }
10487:         }
10488:         if (grep(/^\Q$item\E$/,@errors)) {
10489:             $newvalues{$item} = $domdefaults{$item};
10490:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
10491:             $changes{$item} = 1;
10492:         }
10493:         $domdefaults{$item} = $newvalues{$item};
10494:     }
10495:     my %defaults_hash = (
10496:                          defaults => \%newvalues,
10497:                         );
10498:     my $title = &defaults_titles();
10499: 
10500:     my $currinststatus;
10501:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
10502:         $currinststatus = $domconfig{'inststatus'};
10503:     } else {
10504:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
10505:         $currinststatus = {
10506:                              inststatustypes => $usertypes,
10507:                              inststatusorder => $types,
10508:                              inststatusguest => [],
10509:                           };
10510:     }
10511:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
10512:     my @allpos;
10513:     my %guests;
10514:     my %alltypes;
10515:     my ($currtitles,$currguests,$currorder);
10516:     if (ref($currinststatus) eq 'HASH') {
10517:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
10518:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
10519:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
10520:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
10521:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
10522:                     }
10523:                 }
10524:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
10525:                     my $position = $env{'form.inststatus_pos_'.$type};
10526:                     $position =~ s/\D+//g;
10527:                     $allpos[$position] = $type;
10528:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
10529:                     $alltypes{$type} =~ s/`//g;
10530:                     if ($env{'form.inststatus_guest_'.$type}) {
10531:                         $guests{$type} = 1;
10532:                     }
10533:                 }
10534:             }
10535:             if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
10536:                 $currguests = join(',',@{$currinststatus->{'inststatusguest'}});
10537:             }
10538:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
10539:             $currtitles =~ s/,$//;
10540:         }
10541:     }
10542:     if ($env{'form.addinststatus'}) {
10543:         my $newtype = $env{'form.addinststatus'};
10544:         $newtype =~ s/\W//g;
10545:         unless (exists($alltypes{$newtype})) {
10546:             if ($env{'form.addinststatus_guest'}) {
10547:                 $guests{$newtype} = 1;
10548:             }
10549:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
10550:             $alltypes{$newtype} =~ s/`//g; 
10551:             my $position = $env{'form.addinststatus_pos'};
10552:             $position =~ s/\D+//g;
10553:             if ($position ne '') {
10554:                 $allpos[$position] = $newtype;
10555:             }
10556:         }
10557:     }
10558:     my (@orderedstatus,@orderedguests);
10559:     foreach my $type (@allpos) {
10560:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
10561:             push(@orderedstatus,$type);
10562:             if ($guests{$type}) {
10563:                 push(@orderedguests,$type);
10564:             }
10565:         }
10566:     }
10567:     foreach my $type (keys(%alltypes)) {
10568:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
10569:             delete($alltypes{$type});
10570:         }
10571:     }
10572:     $defaults_hash{'inststatus'} = {
10573:                                      inststatustypes => \%alltypes,
10574:                                      inststatusorder => \@orderedstatus,
10575:                                      inststatusguest => \@orderedguests,
10576:                                    };
10577:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
10578:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
10579:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
10580:         }
10581:     }
10582:     if ($currorder ne join(',',@orderedstatus)) {
10583:         $changes{'inststatus'}{'inststatusorder'} = 1;
10584:     }
10585:     if ($currguests ne join(',',@orderedguests)) {
10586:         $changes{'inststatus'}{'inststatusguest'} = 1;
10587:     }
10588:     my $newtitles;
10589:     foreach my $item (@orderedstatus) {
10590:         $newtitles .= $alltypes{$item}.',';
10591:     }
10592:     $newtitles =~ s/,$//;
10593:     if ($currtitles ne $newtitles) {
10594:         $changes{'inststatus'}{'inststatustypes'} = 1;
10595:     }
10596:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
10597:                                              $dom);
10598:     if ($putresult eq 'ok') {
10599:         if (keys(%changes) > 0) {
10600:             $resulttext = &mt('Changes made:').'<ul>';
10601:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
10602:             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";
10603:             foreach my $item (sort(keys(%changes))) {
10604:                 if ($item eq 'inststatus') {
10605:                     if (ref($changes{'inststatus'}) eq 'HASH') {
10606:                         if (($changes{'inststatus'}{'inststatustypes'}) || $changes{'inststatus'}{'inststatusorder'}) {
10607:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
10608:                             foreach my $type (@orderedstatus) { 
10609:                                 $resulttext .= $alltypes{$type}.', ';
10610:                             }
10611:                             $resulttext =~ s/, $//;
10612:                             $resulttext .= '</li>';
10613:                         }
10614:                         if ($changes{'inststatus'}{'inststatusguest'}) {
10615:                             $resulttext .= '<li>'; 
10616:                             if (@orderedguests) {
10617:                                 $resulttext .= &mt('Types assignable to "non-institutional" usernames set to:').' ';
10618:                                 foreach my $type (@orderedguests) {
10619:                                     $resulttext .= $alltypes{$type}.', ';
10620:                                 }
10621:                                 $resulttext =~ s/, $//;
10622:                             } else {
10623:                                 $resulttext .= &mt('Types assignable to "non-institutional" usernames set to none.');
10624:                             }
10625:                             $resulttext .= '</li>';
10626:                         }
10627:                     }
10628:                 } else {
10629:                     my $value = $env{'form.'.$item};
10630:                     if ($value eq '') {
10631:                         $value = &mt('none');
10632:                     } elsif ($item eq 'auth_def') {
10633:                         my %authnames = &authtype_names();
10634:                         my %shortauth = (
10635:                                           internal   => 'int',
10636:                                           krb4       => 'krb4',
10637:                                           krb5       => 'krb5',
10638:                                           localauth  => 'loc',
10639:                         );
10640:                         $value = $authnames{$shortauth{$value}};
10641:                     }
10642:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
10643:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
10644:                 }
10645:             }
10646:             $resulttext .= '</ul>';
10647:             $mailmsgtext .= "\n";
10648:             my $cachetime = 24*60*60;
10649:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
10650:             if (ref($lastactref) eq 'HASH') {
10651:                 $lastactref->{'domdefaults'} = 1;
10652:             }
10653:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
10654:                 my $notify = 1;
10655:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
10656:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
10657:                         $notify = 0;
10658:                     }
10659:                 }
10660:                 if ($notify) {
10661:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
10662:                                                "LON-CAPA Domain Settings Change - $dom",
10663:                                                $mailmsgtext);
10664:                 }
10665:             }
10666:         } else {
10667:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
10668:         }
10669:     } else {
10670:         $resulttext = '<span class="LC_error">'.
10671:             &mt('An error occurred: [_1]',$putresult).'</span>';
10672:     }
10673:     if (@errors > 0) {
10674:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
10675:         foreach my $item (@errors) {
10676:             $resulttext .= ' "'.$title->{$item}.'",';
10677:         }
10678:         $resulttext =~ s/,$//;
10679:     }
10680:     return $resulttext;
10681: }
10682: 
10683: sub modify_scantron {
10684:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
10685:     my ($resulttext,%confhash,%changes,$errors);
10686:     my $custom = 'custom.tab';
10687:     my $default = 'default.tab';
10688:     my $servadm = $r->dir_config('lonAdmEMail');
10689:     my ($configuserok,$author_ok,$switchserver) = 
10690:         &config_check($dom,$confname,$servadm);
10691:     if ($env{'form.scantronformat.filename'} ne '') {
10692:         my $error;
10693:         if ($configuserok eq 'ok') {
10694:             if ($switchserver) {
10695:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
10696:             } else {
10697:                 if ($author_ok eq 'ok') {
10698:                     my ($result,$scantronurl) =
10699:                         &publishlogo($r,'upload','scantronformat',$dom,
10700:                                      $confname,'scantron','','',$custom);
10701:                     if ($result eq 'ok') {
10702:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
10703:                         $changes{'scantronformat'} = 1;
10704:                     } else {
10705:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
10706:                     }
10707:                 } else {
10708:                     $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);
10709:                 }
10710:             }
10711:         } else {
10712:             $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);
10713:         }
10714:         if ($error) {
10715:             &Apache::lonnet::logthis($error);
10716:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10717:         }
10718:     }
10719:     if (ref($domconfig{'scantron'}) eq 'HASH') {
10720:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
10721:             if ($env{'form.scantronformat_del'}) {
10722:                 $confhash{'scantron'}{'scantronformat'} = '';
10723:                 $changes{'scantronformat'} = 1;
10724:             }
10725:         }
10726:     }
10727:     if (keys(%confhash) > 0) {
10728:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
10729:                                                  $dom);
10730:         if ($putresult eq 'ok') {
10731:             if (keys(%changes) > 0) {
10732:                 if (ref($confhash{'scantron'}) eq 'HASH') {
10733:                     $resulttext = &mt('Changes made:').'<ul>';
10734:                     if ($confhash{'scantron'}{'scantronformat'} eq '') {
10735:                         $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
10736:                     } else {
10737:                         $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
10738:                     }
10739:                     $resulttext .= '</ul>';
10740:                 } else {
10741:                     $resulttext = &mt('Changes made to bubblesheet format file.');
10742:                 }
10743:                 $resulttext .= '</ul>';
10744:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
10745:                 if (ref($lastactref) eq 'HASH') {
10746:                     $lastactref->{'domainconfig'} = 1;
10747:                 }
10748:             } else {
10749:                 $resulttext = &mt('No changes made to bubblesheet format file');
10750:             }
10751:         } else {
10752:             $resulttext = '<span class="LC_error">'.
10753:                 &mt('An error occurred: [_1]',$putresult).'</span>';
10754:         }
10755:     } else {
10756:         $resulttext = &mt('No changes made to bubblesheet format file'); 
10757:     }
10758:     if ($errors) {
10759:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
10760:                        $errors.'</ul>';
10761:     }
10762:     return $resulttext;
10763: }
10764: 
10765: sub modify_coursecategories {
10766:     my ($dom,$lastactref,%domconfig) = @_;
10767:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
10768:         $cathash);
10769:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
10770:     my @catitems = ('unauth','auth');
10771:     my @cattypes = ('std','domonly','codesrch','none');
10772:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
10773:         $cathash = $domconfig{'coursecategories'}{'cats'};
10774:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
10775:             $changes{'togglecats'} = 1;
10776:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
10777:         }
10778:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
10779:             $changes{'categorize'} = 1;
10780:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
10781:         }
10782:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
10783:             $changes{'togglecatscomm'} = 1;
10784:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
10785:         }
10786:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
10787:             $changes{'categorizecomm'} = 1;
10788:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
10789:         }
10790:         foreach my $item (@catitems) {
10791:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
10792:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
10793:                     $changes{$item} = 1;
10794:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
10795:                 }
10796:             }
10797:         }
10798:     } else {
10799:         $changes{'togglecats'} = 1;
10800:         $changes{'categorize'} = 1;
10801:         $changes{'togglecatscomm'} = 1;
10802:         $changes{'categorizecomm'} = 1;
10803:         $domconfig{'coursecategories'} = {
10804:                                              togglecats => $env{'form.togglecats'},
10805:                                              categorize => $env{'form.categorize'},
10806:                                              togglecatscomm => $env{'form.togglecatscomm'},
10807:                                              categorizecomm => $env{'form.categorizecomm'},
10808:                                          };
10809:         foreach my $item (@catitems) {
10810:             if ($env{'form.coursecat_'.$item} ne 'std') {
10811:                 $changes{$item} = 1;
10812:             }
10813:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
10814:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
10815:             }
10816:         }
10817:     }
10818:     if (ref($cathash) eq 'HASH') {
10819:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
10820:             push (@deletecategory,'instcode::0');
10821:         }
10822:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
10823:             push(@deletecategory,'communities::0');
10824:         }
10825:     }
10826:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
10827:     if (ref($cathash) eq 'HASH') {
10828:         if (@deletecategory > 0) {
10829:             #FIXME Need to remove category from all courses using a deleted category 
10830:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
10831:             foreach my $item (@deletecategory) {
10832:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
10833:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
10834:                     $deletions{$item} = 1;
10835:                     &recurse_cat_deletes($item,$cathash,\%deletions);
10836:                 }
10837:             }
10838:         }
10839:         foreach my $item (keys(%{$cathash})) {
10840:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
10841:             if ($cathash->{$item} ne $env{'form.'.$item}) {
10842:                 $reorderings{$item} = 1;
10843:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
10844:             }
10845:             if ($env{'form.addcategory_name_'.$item} ne '') {
10846:                 my $newcat = $env{'form.addcategory_name_'.$item};
10847:                 my $newdepth = $depth+1;
10848:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
10849:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
10850:                 $adds{$newitem} = 1; 
10851:             }
10852:             if ($env{'form.subcat_'.$item} ne '') {
10853:                 my $newcat = $env{'form.subcat_'.$item};
10854:                 my $newdepth = $depth+1;
10855:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
10856:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
10857:                 $adds{$newitem} = 1;
10858:             }
10859:         }
10860:     }
10861:     if ($env{'form.instcode'} eq '1') {
10862:         if (ref($cathash) eq 'HASH') {
10863:             my $newitem = 'instcode::0';
10864:             if ($cathash->{$newitem} eq '') {  
10865:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
10866:                 $adds{$newitem} = 1;
10867:             }
10868:         } else {
10869:             my $newitem = 'instcode::0';
10870:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
10871:             $adds{$newitem} = 1;
10872:         }
10873:     }
10874:     if ($env{'form.communities'} eq '1') {
10875:         if (ref($cathash) eq 'HASH') {
10876:             my $newitem = 'communities::0';
10877:             if ($cathash->{$newitem} eq '') {
10878:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
10879:                 $adds{$newitem} = 1;
10880:             }
10881:         } else {
10882:             my $newitem = 'communities::0';
10883:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
10884:             $adds{$newitem} = 1;
10885:         }
10886:     }
10887:     if ($env{'form.addcategory_name'} ne '') {
10888:         if (($env{'form.addcategory_name'} ne 'instcode') &&
10889:             ($env{'form.addcategory_name'} ne 'communities')) {
10890:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
10891:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
10892:             $adds{$newitem} = 1;
10893:         }
10894:     }
10895:     my $putresult;
10896:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
10897:         if (keys(%deletions) > 0) {
10898:             foreach my $key (keys(%deletions)) {
10899:                 if ($predelallitems{$key} ne '') {
10900:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
10901:                 }
10902:             }
10903:         }
10904:         my (@chkcats,@chktrails,%chkallitems);
10905:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
10906:         if (ref($chkcats[0]) eq 'ARRAY') {
10907:             my $depth = 0;
10908:             my $chg = 0;
10909:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
10910:                 my $name = $chkcats[0][$i];
10911:                 my $item;
10912:                 if ($name eq '') {
10913:                     $chg ++;
10914:                 } else {
10915:                     $item = &escape($name).'::0';
10916:                     if ($chg) {
10917:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
10918:                     }
10919:                     $depth ++; 
10920:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
10921:                     $depth --;
10922:                 }
10923:             }
10924:         }
10925:     }
10926:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
10927:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
10928:         if ($putresult eq 'ok') {
10929:             my %title = (
10930:                          togglecats     => 'Show/Hide a course in catalog',
10931:                          categorize     => 'Assign a category to a course',
10932:                          togglecatscomm => 'Show/Hide a community in catalog',
10933:                          categorizecomm => 'Assign a category to a community',
10934:                         );
10935:             my %level = (
10936:                          dom  => 'set in Domain ("Modify Course/Community")',
10937:                          crs  => 'set in Course ("Course Configuration")',
10938:                          comm => 'set in Community ("Community Configuration")',
10939:                          none     => 'No catalog',
10940:                          std      => 'Standard catalog',
10941:                          domonly  => 'Domain-only catalog',
10942:                          codesrch => 'Code search form',
10943:                         );
10944:             $resulttext = &mt('Changes made:').'<ul>';
10945:             if ($changes{'togglecats'}) {
10946:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
10947:             }
10948:             if ($changes{'categorize'}) {
10949:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
10950:             }
10951:             if ($changes{'togglecatscomm'}) {
10952:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
10953:             }
10954:             if ($changes{'categorizecomm'}) {
10955:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
10956:             }
10957:             if ($changes{'unauth'}) {
10958:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
10959:             }
10960:             if ($changes{'auth'}) {
10961:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
10962:             }
10963:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
10964:                 my $cathash;
10965:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
10966:                     $cathash = $domconfig{'coursecategories'}{'cats'};
10967:                 } else {
10968:                     $cathash = {};
10969:                 } 
10970:                 my (@cats,@trails,%allitems);
10971:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
10972:                 if (keys(%deletions) > 0) {
10973:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
10974:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
10975:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
10976:                     }
10977:                     $resulttext .= '</ul></li>';
10978:                 }
10979:                 if (keys(%reorderings) > 0) {
10980:                     my %sort_by_trail;
10981:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
10982:                     foreach my $key (keys(%reorderings)) {
10983:                         if ($allitems{$key} ne '') {
10984:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
10985:                         }
10986:                     }
10987:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
10988:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
10989:                     }
10990:                     $resulttext .= '</ul></li>';
10991:                 }
10992:                 if (keys(%adds) > 0) {
10993:                     my %sort_by_trail;
10994:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
10995:                     foreach my $key (keys(%adds)) {
10996:                         if ($allitems{$key} ne '') {
10997:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
10998:                         }
10999:                     }
11000:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
11001:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
11002:                     }
11003:                     $resulttext .= '</ul></li>';
11004:                 }
11005:             }
11006:             $resulttext .= '</ul>';
11007:             if ($changes{'unauth'} || $changes{'auth'}) {
11008:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11009:                 if ($changes{'auth'}) {
11010:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
11011:                 }
11012:                 if ($changes{'unauth'}) {
11013:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
11014:                 }
11015:                 my $cachetime = 24*60*60;
11016:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
11017:                 if (ref($lastactref) eq 'HASH') {
11018:                     $lastactref->{'domdefaults'} = 1;
11019:                 }
11020:             }
11021:         } else {
11022:             $resulttext = '<span class="LC_error">'.
11023:                           &mt('An error occurred: [_1]',$putresult).'</span>';
11024:         }
11025:     } else {
11026:         $resulttext = &mt('No changes made to course and community categories');
11027:     }
11028:     return $resulttext;
11029: }
11030: 
11031: sub modify_serverstatuses {
11032:     my ($dom,%domconfig) = @_;
11033:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
11034:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
11035:         %currserverstatus = %{$domconfig{'serverstatuses'}};
11036:     }
11037:     my @pages = &serverstatus_pages();
11038:     foreach my $type (@pages) {
11039:         $newserverstatus{$type}{'namedusers'} = '';
11040:         $newserverstatus{$type}{'machines'} = '';
11041:         if (defined($env{'form.'.$type.'_namedusers'})) {
11042:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
11043:             my @okusers;
11044:             foreach my $user (@users) {
11045:                 my ($uname,$udom) = split(/:/,$user);
11046:                 if (($udom =~ /^$match_domain$/) &&   
11047:                     (&Apache::lonnet::domain($udom)) &&
11048:                     ($uname =~ /^$match_username$/)) {
11049:                     if (!grep(/^\Q$user\E/,@okusers)) {
11050:                         push(@okusers,$user);
11051:                     }
11052:                 }
11053:             }
11054:             if (@okusers > 0) {
11055:                  @okusers = sort(@okusers);
11056:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
11057:             }
11058:         }
11059:         if (defined($env{'form.'.$type.'_machines'})) {
11060:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
11061:             my @okmachines;
11062:             foreach my $ip (@machines) {
11063:                 my @parts = split(/\./,$ip);
11064:                 next if (@parts < 4);
11065:                 my $badip = 0;
11066:                 for (my $i=0; $i<4; $i++) {
11067:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
11068:                         $badip = 1;
11069:                         last;
11070:                     }
11071:                 }
11072:                 if (!$badip) {
11073:                     push(@okmachines,$ip);     
11074:                 }
11075:             }
11076:             @okmachines = sort(@okmachines);
11077:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
11078:         }
11079:     }
11080:     my %serverstatushash =  (
11081:                                 serverstatuses => \%newserverstatus,
11082:                             );
11083:     foreach my $type (@pages) {
11084:         foreach my $setting ('namedusers','machines') {
11085:             my (@current,@new);
11086:             if (ref($currserverstatus{$type}) eq 'HASH') {
11087:                 if ($currserverstatus{$type}{$setting} ne '') { 
11088:                     @current = split(/,/,$currserverstatus{$type}{$setting});
11089:                 }
11090:             }
11091:             if ($newserverstatus{$type}{$setting} ne '') {
11092:                 @new = split(/,/,$newserverstatus{$type}{$setting});
11093:             }
11094:             if (@current > 0) {
11095:                 if (@new > 0) {
11096:                     foreach my $item (@current) {
11097:                         if (!grep(/^\Q$item\E$/,@new)) {
11098:                             $changes{$type}{$setting} = 1;
11099:                             last;
11100:                         }
11101:                     }
11102:                     foreach my $item (@new) {
11103:                         if (!grep(/^\Q$item\E$/,@current)) {
11104:                             $changes{$type}{$setting} = 1;
11105:                             last;
11106:                         }
11107:                     }
11108:                 } else {
11109:                     $changes{$type}{$setting} = 1;
11110:                 }
11111:             } elsif (@new > 0) {
11112:                 $changes{$type}{$setting} = 1;
11113:             }
11114:         }
11115:     }
11116:     if (keys(%changes) > 0) {
11117:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
11118:         my $putresult = &Apache::lonnet::put_dom('configuration',
11119:                                                  \%serverstatushash,$dom);
11120:         if ($putresult eq 'ok') {
11121:             $resulttext .= &mt('Changes made:').'<ul>';
11122:             foreach my $type (@pages) {
11123:                 if (ref($changes{$type}) eq 'HASH') {
11124:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
11125:                     if ($changes{$type}{'namedusers'}) {
11126:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
11127:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
11128:                         } else {
11129:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
11130:                         }
11131:                     }
11132:                     if ($changes{$type}{'machines'}) {
11133:                         if ($newserverstatus{$type}{'machines'} eq '') {
11134:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
11135:                         } else {
11136:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
11137:                         }
11138: 
11139:                     }
11140:                     $resulttext .= '</ul></li>';
11141:                 }
11142:             }
11143:             $resulttext .= '</ul>';
11144:         } else {
11145:             $resulttext = '<span class="LC_error">'.
11146:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
11147: 
11148:         }
11149:     } else {
11150:         $resulttext = &mt('No changes made to access to server status pages');
11151:     }
11152:     return $resulttext;
11153: }
11154: 
11155: sub modify_helpsettings {
11156:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
11157:     my ($resulttext,$errors,%changes,%helphash);
11158:     my %defaultchecked = ('submitbugs' => 'on');
11159:     my @offon = ('off','on');
11160:     my @toggles = ('submitbugs');
11161:     my %current = ('submitbugs' => '',
11162:                    'adhoc'      => {},
11163:                   );
11164:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
11165:         %current = %{$domconfig{'helpsettings'}};
11166:     }
11167:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
11168:     foreach my $item (@toggles) {
11169:         if ($defaultchecked{$item} eq 'on') { 
11170:             if ($current{$item} eq '') {
11171:                 if ($env{'form.'.$item} eq '0') {
11172:                     $changes{$item} = 1;
11173:                 }
11174:             } elsif ($current{$item} ne $env{'form.'.$item}) {
11175:                 $changes{$item} = 1;
11176:             }
11177:         } elsif ($defaultchecked{$item} eq 'off') {
11178:             if ($current{$item} eq '') {
11179:                 if ($env{'form.'.$item} eq '1') {
11180:                     $changes{$item} = 1;
11181:                 }
11182:             } elsif ($current{$item} ne $env{'form.'.$item}) {
11183:                 $changes{$item} = 1;
11184:             }
11185:         }
11186:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
11187:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
11188:         }
11189:     }
11190:     my $maxnum = $env{'form.helproles_maxnum'};
11191:     my $confname = $dom.'-domainconfig';
11192:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
11193:     my (@allpos,%newsettings,%changedprivs,$newrole);
11194:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
11195:     my @accesstypes = ('all','none','status','inc','exc');
11196:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh']);
11197:     my %lt = &Apache::lonlocal::texthash(
11198:                     s      => 'system',
11199:                     d      => 'domain',
11200:                     order  => 'Display order',
11201:                     access => 'Role usage',
11202:                     all    => 'All',
11203:                     none   => 'None',
11204:                     status => 'Determined based on institutional status',
11205:                     inc    => 'Include all, but exclude specific personnel',
11206:                     exc    => 'Exclude all, but include specific personnel',
11207:     );
11208:     for (my $num=0; $num<=$maxnum; $num++) {
11209:         my ($prefix,$identifier,$rolename,%curr);
11210:         if ($num == $maxnum) {
11211:             next unless ($env{'form.newcusthelp'} == $maxnum);
11212:             $identifier = 'custhelp'.$num;
11213:             $prefix = 'helproles_'.$num;
11214:             $rolename = $env{'form.custhelpname'.$num};
11215:             $rolename=~s/[^A-Za-z0-9]//gs;
11216:             next if ($rolename eq '');
11217:             next if (exists($existing{'rolesdef_'.$rolename}));
11218:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
11219:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
11220:                                                      $newprivs{'c'},$confname,$dom);
11221:             if ($result ne 'ok') {
11222:                 $errors .= '<li><span class="LC_error">'.
11223:                            &mt('An error occurred storing the new custom role: [_1]',
11224:                            $result).'</span></li>';
11225:                 next;
11226:             } else {
11227:                 $changedprivs{$rolename} = \%newprivs;
11228:                 $newrole = $rolename;
11229:             }
11230:         } else {
11231:             $prefix = 'helproles_'.$num;
11232:             $rolename = $env{'form.'.$prefix};
11233:             next if ($rolename eq '');
11234:             next unless (exists($existing{'rolesdef_'.$rolename}));
11235:             $identifier = 'custhelp'.$num;
11236:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
11237:             my %currprivs;
11238:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
11239:                 split(/\_/,$existing{'rolesdef_'.$rolename});
11240:             foreach my $level ('c','d','s') {
11241:                 if ($newprivs{$level} ne $currprivs{$level}) {
11242:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
11243:                                                              $newprivs{'c'},$confname,$dom);
11244:                     if ($result ne 'ok') {
11245:                         $errors .= '<li><span class="LC_error">'.
11246:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
11247:                                        $rolename,$result).'</span></li>';
11248:                     } else {
11249:                         $changedprivs{$rolename} = \%newprivs;
11250:                     }
11251:                     last;
11252:                 }
11253:             }
11254:             if (ref($current{'adhoc'}) eq 'HASH') {
11255:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
11256:                     %curr = %{$current{'adhoc'}{$rolename}};
11257:                 }
11258:             }
11259:         }
11260:         my $newpos = $env{'form.'.$prefix.'_pos'};
11261:         $newpos =~ s/\D+//g;
11262:         $allpos[$newpos] = $rolename;
11263:         my $newdesc = $env{'form.'.$prefix.'_desc'};
11264:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
11265:         if ($curr{'desc'}) {
11266:             if ($curr{'desc'} ne $newdesc) {
11267:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
11268:                 $newsettings{$rolename}{'desc'} = $newdesc;
11269:             }
11270:         } elsif ($newdesc ne '') {
11271:             $changes{'customrole'}{$rolename}{'desc'} = 1;
11272:             $newsettings{$rolename}{'desc'} = $newdesc;
11273:         }
11274:         my $access = $env{'form.'.$prefix.'_access'};
11275:         if (grep(/^\Q$access\E$/,@accesstypes)) {
11276:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
11277:             if ($access eq 'status') {
11278:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
11279:                 if (scalar(@statuses) == 0) {
11280:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
11281:                 } else {
11282:                     my (@shownstatus,$numtypes);
11283:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
11284:                     if (ref($types) eq 'ARRAY') {
11285:                         $numtypes = scalar(@{$types});
11286:                         foreach my $type (sort(@statuses)) {
11287:                             if ($type eq 'default') {
11288:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
11289:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
11290:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
11291:                                 push(@shownstatus,$usertypes->{$type});
11292:                             }
11293:                         }
11294:                     }
11295:                     if (grep(/^default$/,@statuses)) {
11296:                         push(@shownstatus,$othertitle);
11297:                     }
11298:                     if (scalar(@shownstatus) == 1+$numtypes) {
11299:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
11300:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
11301:                     } else {
11302:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
11303:                         if (ref($curr{'status'}) eq 'ARRAY') {
11304:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
11305:                             if (@diffs) {
11306:                                 $changes{'customrole'}{$rolename}{$access} = 1;
11307:                             }
11308:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
11309:                             $changes{'customrole'}{$rolename}{$access} = 1;
11310:                         }
11311:                     }
11312:                 }
11313:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
11314:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
11315:                 my @newspecstaff;
11316:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
11317:                 foreach my $person (sort(@personnel)) {
11318:                     if ($domhelpdesk{$person}) {
11319:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
11320:                     }
11321:                 }
11322:                 if (ref($curr{$access}) eq 'ARRAY') {
11323:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
11324:                     if (@diffs) {
11325:                         $changes{'customrole'}{$rolename}{$access} = 1;
11326:                     }
11327:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
11328:                     $changes{'customrole'}{$rolename}{$access} = 1;
11329:                 }
11330:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
11331:                     my ($uname,$udom) = split(/:/,$person);
11332:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
11333:                 }
11334:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
11335:             }
11336:         } else {
11337:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
11338:         }
11339:         unless ($curr{'access'} eq $access) {
11340:             $changes{'customrole'}{$rolename}{'access'} = 1;
11341:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
11342:         }
11343:     }
11344:     if (@allpos > 0) {
11345:         my $idx = 0;
11346:         foreach my $rolename (@allpos) {
11347:             if ($rolename ne '') {
11348:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
11349:                 if (ref($current{'adhoc'}) eq 'HASH') {
11350:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
11351:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
11352:                             $changes{'customrole'}{$rolename}{'order'} = 1;
11353:                             $newsettings{$rolename}{'order'} = $idx+1;
11354:                         }
11355:                     }
11356:                 }
11357:                 $idx ++;
11358:             }
11359:         }
11360:     }
11361:     my $putresult;
11362:     if (keys(%changes) > 0) {
11363:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
11364:         if ($putresult eq 'ok') {
11365:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
11366:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
11367:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
11368:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
11369:                 }
11370:             }
11371:             my $cachetime = 24*60*60;
11372:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
11373:             if (ref($lastactref) eq 'HASH') {
11374:                 $lastactref->{'domdefaults'} = 1;
11375:             }
11376:         } else {
11377:             $errors .= '<li><span class="LC_error">'.
11378:                        &mt('An error occurred storing the settings: [_1]',
11379:                            $putresult).'</span></li>';
11380:         }
11381:     }
11382:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
11383:         $resulttext = &mt('Changes made:').'<ul>';
11384:         my (%shownprivs,@levelorder);
11385:         @levelorder = ('c','d','s');
11386:         if ((keys(%changes)) && ($putresult eq 'ok')) {
11387:             foreach my $item (sort(keys(%changes))) {
11388:                 if ($item eq 'submitbugs') {
11389:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
11390:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
11391:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
11392:                 } elsif ($item eq 'customrole') {
11393:                     if (ref($changes{'customrole'}) eq 'HASH') {
11394:                         my @keyorder = ('order','desc','access','status','exc','inc');
11395:                         my %keytext = &Apache::lonlocal::texthash(
11396:                                                                    order  => 'Order',
11397:                                                                    desc   => 'Role description',
11398:                                                                    access => 'Role usage',
11399:                                                                    status => 'Allowed instituional types',
11400:                                                                    exc    => 'Allowed personnel',
11401:                                                                    inc    => 'Disallowed personnel',
11402:                         );
11403:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
11404:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
11405:                                 if ($role eq $newrole) {
11406:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
11407:                                                               $role).'<ul>';
11408:                                 } else {
11409:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
11410:                                                               $role).'<ul>';
11411:                                 }
11412:                                 foreach my $key (@keyorder) {
11413:                                     if ($changes{'customrole'}{$role}{$key}) {
11414:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
11415:                                                                   $keytext{$key},$newsettings{$role}{$key}).
11416:                                                        '</li>';
11417:                                     }
11418:                                 }
11419:                                 if (ref($changedprivs{$role}) eq 'HASH') {
11420:                                     $shownprivs{$role} = 1;
11421:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
11422:                                     foreach my $level (@levelorder) {
11423:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
11424:                                             next if ($item eq '');
11425:                                             my ($priv) = split(/\&/,$item,2);
11426:                                             if (&Apache::lonnet::plaintext($priv)) {
11427:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
11428:                                                 unless ($level eq 'c') {
11429:                                                     $resulttext .= ' ('.$lt{$level}.')';
11430:                                                 }
11431:                                                 $resulttext .= '</li>';
11432:                                             }
11433:                                         }
11434:                                     }
11435:                                     $resulttext .= '</ul>';
11436:                                 }
11437:                                 $resulttext .= '</ul></li>';
11438:                             }
11439:                         }
11440:                     }
11441:                 }
11442:             }
11443:         }
11444:         if (keys(%changedprivs)) {
11445:             foreach my $role (sort(keys(%changedprivs))) {
11446:                 unless ($shownprivs{$role}) {
11447:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
11448:                                               $role).'<ul>'.
11449:                                    '<li>'.&mt('Privileges set to :').'<ul>';
11450:                     foreach my $level (@levelorder) {
11451:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
11452:                             next if ($item eq '');
11453:                             my ($priv) = split(/\&/,$item,2);
11454:                             if (&Apache::lonnet::plaintext($priv)) {
11455:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
11456:                                 unless ($level eq 'c') {
11457:                                     $resulttext .= ' ('.$lt{$level}.')';
11458:                                 }
11459:                                 $resulttext .= '</li>';
11460:                             }
11461:                         }
11462:                     }
11463:                     $resulttext .= '</ul></li></ul></li>';
11464:                 }
11465:             }
11466:         }
11467:         $resulttext .= '</ul>';
11468:     } else {
11469:         $resulttext = &mt('No changes made to help settings');
11470:     }
11471:     if ($errors) {
11472:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
11473:                                     $errors.'</ul>';
11474:     }
11475:     return $resulttext;
11476: }
11477: 
11478: sub modify_coursedefaults {
11479:     my ($dom,$lastactref,%domconfig) = @_;
11480:     my ($resulttext,$errors,%changes,%defaultshash);
11481:     my %defaultchecked = (
11482:                            'uselcmath'       => 'on',
11483:                            'usejsme'         => 'on'
11484:                          );
11485:     my @toggles = ('uselcmath','usejsme');
11486:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
11487:                    'uploadquota_community','uploadquota_textbook','mysqltables_official',
11488:                    'mysqltables_unofficial','mysqltables_community','mysqltables_textbook');
11489:     my @types = ('official','unofficial','community','textbook');
11490:     my %staticdefaults = (
11491:                            anonsurvey_threshold => 10,
11492:                            uploadquota          => 500,
11493:                            postsubmit           => 60,
11494:                            mysqltables          => 172800,
11495:                          );
11496: 
11497:     $defaultshash{'coursedefaults'} = {};
11498: 
11499:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
11500:         if ($domconfig{'coursedefaults'} eq '') {
11501:             $domconfig{'coursedefaults'} = {};
11502:         }
11503:     }
11504: 
11505:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
11506:         foreach my $item (@toggles) {
11507:             if ($defaultchecked{$item} eq 'on') {
11508:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
11509:                     ($env{'form.'.$item} eq '0')) {
11510:                     $changes{$item} = 1;
11511:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
11512:                     $changes{$item} = 1;
11513:                 }
11514:             } elsif ($defaultchecked{$item} eq 'off') {
11515:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
11516:                     ($env{'form.'.$item} eq '1')) {
11517:                     $changes{$item} = 1;
11518:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
11519:                     $changes{$item} = 1;
11520:                 }
11521:             }
11522:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
11523:         }
11524:         foreach my $item (@numbers) {
11525:             my ($currdef,$newdef);
11526:             $newdef = $env{'form.'.$item};
11527:             if ($item eq 'anonsurvey_threshold') {
11528:                 $currdef = $domconfig{'coursedefaults'}{$item};
11529:                 $newdef =~ s/\D//g;
11530:                 if ($newdef eq '' || $newdef < 1) {
11531:                     $newdef = 1;
11532:                 }
11533:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
11534:             } else {
11535:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
11536:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
11537:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
11538:                 }
11539:                 $newdef =~ s/[^\w.\-]//g;
11540:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
11541:             }
11542:             if ($currdef ne $newdef) {
11543:                 my $staticdef;
11544:                 if ($item eq 'anonsurvey_threshold') {
11545:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
11546:                         $changes{$item} = 1;
11547:                     }
11548:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
11549:                     my $setting = $1;
11550:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
11551:                         $changes{$setting} = 1;
11552:                     }
11553:                 }
11554:             }
11555:         }
11556:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
11557:         my @currclonecode;
11558:         if (ref($currclone) eq 'HASH') {
11559:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
11560:                 @currclonecode = @{$currclone->{'instcode'}};
11561:             }
11562:         }
11563:         my $newclone;
11564:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
11565:             $newclone = $env{'form.canclone'};
11566:         }
11567:         if ($newclone eq 'instcode') {
11568:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
11569:             my (%codedefaults,@code_order,@clonecode);
11570:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
11571:                                                     \@code_order);
11572:             foreach my $item (@code_order) {
11573:                 if (grep(/^\Q$item\E$/,@newcodes)) {
11574:                     push(@clonecode,$item);
11575:                 }
11576:             }
11577:             if (@clonecode) {
11578:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
11579:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
11580:                 if (@diffs) {
11581:                     $changes{'canclone'} = 1;
11582:                 }
11583:             } else {
11584:                 $newclone eq '';
11585:             }
11586:         } elsif ($newclone ne '') {
11587:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
11588:         }
11589:         if ($newclone ne $currclone) {
11590:             $changes{'canclone'} = 1;
11591:         }
11592:         my %credits;
11593:         foreach my $type (@types) {
11594:             unless ($type eq 'community') {
11595:                 $credits{$type} = $env{'form.'.$type.'_credits'};
11596:                 $credits{$type} =~ s/[^\d.]+//g;
11597:             }
11598:         }
11599:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
11600:             ($env{'form.coursecredits'} eq '1')) {
11601:             $changes{'coursecredits'} = 1;
11602:             foreach my $type (keys(%credits)) {
11603:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
11604:             }
11605:         } else {
11606:             if ($env{'form.coursecredits'} eq '1') {
11607:                 foreach my $type (@types) {
11608:                     unless ($type eq 'community') {
11609:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
11610:                             $changes{'coursecredits'} = 1;
11611:                         }
11612:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
11613:                     }
11614:                 }
11615:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
11616:                 foreach my $type (@types) {
11617:                     unless ($type eq 'community') {
11618:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
11619:                             $changes{'coursecredits'} = 1;
11620:                             last;
11621:                         }
11622:                     }
11623:                 }
11624:             }
11625:         }
11626:         if ($env{'form.postsubmit'} eq '1') {
11627:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
11628:             my %currtimeout;
11629:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
11630:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
11631:                     $changes{'postsubmit'} = 1;
11632:                 }
11633:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
11634:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
11635:                 }
11636:             } else {
11637:                 $changes{'postsubmit'} = 1;
11638:             }
11639:             foreach my $type (@types) {
11640:                 my $timeout = $env{'form.'.$type.'_timeout'};
11641:                 $timeout =~ s/\D//g;
11642:                 if ($timeout == $staticdefaults{'postsubmit'}) {
11643:                     $timeout = '';
11644:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
11645:                     $timeout = '0';
11646:                 }
11647:                 unless ($timeout eq '') {
11648:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
11649:                 }
11650:                 if (exists($currtimeout{$type})) {
11651:                     if ($timeout ne $currtimeout{$type}) {
11652:                         $changes{'postsubmit'} = 1;
11653:                     }
11654:                 } elsif ($timeout ne '') {
11655:                     $changes{'postsubmit'} = 1;
11656:                 }
11657:             }
11658:         } else {
11659:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
11660:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
11661:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
11662:                     $changes{'postsubmit'} = 1;
11663:                 }
11664:             } else {
11665:                 $changes{'postsubmit'} = 1;
11666:             }
11667:         }
11668:     }
11669:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
11670:                                              $dom);
11671:     if ($putresult eq 'ok') {
11672:         if (keys(%changes) > 0) {
11673:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
11674:             if (($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
11675:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
11676:                 ($changes{'canclone'}) || ($changes{'mysqltables'})) {
11677:                 foreach my $item ('uselcmath','usejsme') {
11678:                     if ($changes{$item}) {
11679:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
11680:                     }
11681:                 }
11682:                 if ($changes{'coursecredits'}) {
11683:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
11684:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
11685:                             $domdefaults{$type.'credits'} =
11686:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
11687:                         }
11688:                     }
11689:                 }
11690:                 if ($changes{'postsubmit'}) {
11691:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
11692:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
11693:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
11694:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
11695:                                 $domdefaults{$type.'postsubtimeout'} =
11696:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
11697:                             }
11698:                         }
11699:                     }
11700:                 }
11701:                 if ($changes{'uploadquota'}) {
11702:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
11703:                         foreach my $type (@types) {
11704:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
11705:                         }
11706:                     }
11707:                 }
11708:                 if ($changes{'canclone'}) {
11709:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
11710:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
11711:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
11712:                             if (@clonecodes) {
11713:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
11714:                             }
11715:                         }
11716:                     } else {
11717:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
11718:                     }
11719:                 }
11720:                 my $cachetime = 24*60*60;
11721:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
11722:                 if (ref($lastactref) eq 'HASH') {
11723:                     $lastactref->{'domdefaults'} = 1;
11724:                 }
11725:             }
11726:             $resulttext = &mt('Changes made:').'<ul>';
11727:             foreach my $item (sort(keys(%changes))) {
11728:                 if ($item eq 'uselcmath') {
11729:                     if ($env{'form.'.$item} eq '1') {
11730:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
11731:                     } else {
11732:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
11733:                     }
11734:                 } elsif ($item eq 'usejsme') {
11735:                     if ($env{'form.'.$item} eq '1') {
11736:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
11737:                     } else {
11738:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
11739:                     }
11740:                 } elsif ($item eq 'anonsurvey_threshold') {
11741:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
11742:                 } elsif ($item eq 'uploadquota') {
11743:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
11744:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
11745:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
11746:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
11747:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
11748: 
11749:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
11750:                                        '</ul>'.
11751:                                        '</li>';
11752:                     } else {
11753:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
11754:                     }
11755:                 } elsif ($item eq 'mysqltables') {
11756:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
11757:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
11758:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
11759:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
11760:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
11761:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
11762:                                        '</ul>'.
11763:                                        '</li>';
11764:                     } else {
11765:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
11766:                     }
11767:                 } elsif ($item eq 'postsubmit') {
11768:                     if ($domdefaults{'postsubmit'} eq 'off') {
11769:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
11770:                     } else {
11771:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
11772:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
11773:                             $resulttext .= &mt('durations:').'<ul>';
11774:                             foreach my $type (@types) {
11775:                                 $resulttext .= '<li>';
11776:                                 my $timeout;
11777:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
11778:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
11779:                                 }
11780:                                 my $display;
11781:                                 if ($timeout eq '0') {
11782:                                     $display = &mt('unlimited');
11783:                                 } elsif ($timeout eq '') {
11784:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
11785:                                 } else {
11786:                                     $display = &mt('[quant,_1,second]',$timeout);
11787:                                 }
11788:                                 if ($type eq 'community') {
11789:                                     $resulttext .= &mt('Communities');
11790:                                 } elsif ($type eq 'official') {
11791:                                     $resulttext .= &mt('Official courses');
11792:                                 } elsif ($type eq 'unofficial') {
11793:                                     $resulttext .= &mt('Unofficial courses');
11794:                                 } elsif ($type eq 'textbook') {
11795:                                     $resulttext .= &mt('Textbook courses');
11796:                                 }
11797:                                 $resulttext .= ' -- '.$display.'</li>';
11798:                             }
11799:                             $resulttext .= '</ul>';
11800:                         }
11801:                         $resulttext .= '</li>';
11802:                     }
11803:                 } elsif ($item eq 'coursecredits') {
11804:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
11805:                         if (($domdefaults{'officialcredits'} eq '') &&
11806:                             ($domdefaults{'unofficialcredits'} eq '') &&
11807:                             ($domdefaults{'textbookcredits'} eq '')) {
11808:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
11809:                         } else {
11810:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
11811:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
11812:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
11813:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
11814:                                            '</ul>'.
11815:                                            '</li>';
11816:                         }
11817:                     } else {
11818:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
11819:                     }
11820:                 } elsif ($item eq 'canclone') {
11821:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
11822:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
11823:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
11824:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
11825:                         }
11826:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
11827:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
11828:                     } else {
11829:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
11830:                     }
11831:                 }
11832:             }
11833:             $resulttext .= '</ul>';
11834:         } else {
11835:             $resulttext = &mt('No changes made to course defaults');
11836:         }
11837:     } else {
11838:         $resulttext = '<span class="LC_error">'.
11839:             &mt('An error occurred: [_1]',$putresult).'</span>';
11840:     }
11841:     return $resulttext;
11842: }
11843: 
11844: sub modify_selfenrollment {
11845:     my ($dom,$lastactref,%domconfig) = @_;
11846:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
11847:     my @types = ('official','unofficial','community','textbook');
11848:     my %titles = &tool_titles();
11849:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
11850:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
11851:     $ordered{'default'} = ['types','registered','approval','limit'];
11852: 
11853:     my (%roles,%shown,%toplevel);
11854:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
11855: 
11856:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
11857:         if ($domconfig{'selfenrollment'} eq '') {
11858:             $domconfig{'selfenrollment'} = {};
11859:         }
11860:     }
11861:     %toplevel = (
11862:                   admin      => 'Configuration Rights',
11863:                   default    => 'Default settings',
11864:                   validation => 'Validation of self-enrollment requests',
11865:                 );
11866:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
11867: 
11868:     if (ref($ordered{'admin'}) eq 'ARRAY') {
11869:         foreach my $item (@{$ordered{'admin'}}) {
11870:             foreach my $type (@types) {
11871:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
11872:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
11873:                 } else {
11874:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
11875:                 }
11876:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
11877:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
11878:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
11879:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
11880:                             push(@{$changes{'admin'}{$type}},$item);
11881:                         }
11882:                     } else {
11883:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
11884:                             push(@{$changes{'admin'}{$type}},$item);
11885:                         }
11886:                     }
11887:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
11888:                     push(@{$changes{'admin'}{$type}},$item);
11889:                 }
11890:             }
11891:         }
11892:     }
11893: 
11894:     foreach my $item (@{$ordered{'default'}}) {
11895:         foreach my $type (@types) {
11896:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
11897:             if ($item eq 'types') {
11898:                 unless (($value eq 'all') || ($value eq 'dom')) {
11899:                     $value = '';
11900:                 }
11901:             } elsif ($item eq 'registered') {
11902:                 unless ($value eq '1') {
11903:                     $value = 0;
11904:                 }
11905:             } elsif ($item eq 'approval') {
11906:                 unless ($value =~ /^[012]$/) {
11907:                     $value = 0;
11908:                 }
11909:             } else {
11910:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
11911:                     $value = 'none';
11912:                 }
11913:             }
11914:             $selfenrollhash{'default'}{$type}{$item} = $value;
11915:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
11916:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
11917:                     if ($selfenrollhash{'default'}{$type}{$item} ne
11918:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
11919:                          push(@{$changes{'default'}{$type}},$item);
11920:                     }
11921:                 } else {
11922:                     push(@{$changes{'default'}{$type}},$item);
11923:                 }
11924:             } else {
11925:                 push(@{$changes{'default'}{$type}},$item);
11926:             }
11927:             if ($item eq 'limit') {
11928:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
11929:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
11930:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
11931:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
11932:                     }
11933:                 } else {
11934:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
11935:                 }
11936:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
11937:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
11938:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
11939:                          push(@{$changes{'default'}{$type}},'cap');
11940:                     }
11941:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
11942:                     push(@{$changes{'default'}{$type}},'cap');
11943:                 }
11944:             }
11945:         }
11946:     }
11947: 
11948:     foreach my $item (@{$itemsref}) {
11949:         if ($item eq 'fields') {
11950:             my @changed;
11951:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
11952:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
11953:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
11954:             }
11955:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
11956:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
11957:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
11958:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
11959:                 } else {
11960:                     @changed = @{$selfenrollhash{'validation'}{$item}};
11961:                 }
11962:             } else {
11963:                 @changed = @{$selfenrollhash{'validation'}{$item}};
11964:             }
11965:             if (@changed) {
11966:                 if ($selfenrollhash{'validation'}{$item}) { 
11967:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
11968:                 } else {
11969:                     $changes{'validation'}{$item} = &mt('None');
11970:                 }
11971:             }
11972:         } else {
11973:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
11974:             if ($item eq 'markup') {
11975:                if ($env{'form.selfenroll_validation_'.$item}) {
11976:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
11977:                }
11978:             }
11979:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
11980:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
11981:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
11982:                 }
11983:             }
11984:         }
11985:     }
11986: 
11987:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
11988:                                              $dom);
11989:     if ($putresult eq 'ok') {
11990:         if (keys(%changes) > 0) {
11991:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
11992:             $resulttext = &mt('Changes made:').'<ul>';
11993:             foreach my $key ('admin','default','validation') {
11994:                 if (ref($changes{$key}) eq 'HASH') {
11995:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
11996:                     if ($key eq 'validation') {
11997:                         foreach my $item (@{$itemsref}) {
11998:                             if (exists($changes{$key}{$item})) {
11999:                                 if ($item eq 'markup') {
12000:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
12001:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
12002:                                 } else {  
12003:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
12004:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
12005:                                 }
12006:                             }
12007:                         }
12008:                     } else {
12009:                         foreach my $type (@types) {
12010:                             if ($type eq 'community') {
12011:                                 $roles{'1'} = &mt('Community personnel');
12012:                             } else {
12013:                                 $roles{'1'} = &mt('Course personnel');
12014:                             }
12015:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
12016:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
12017:                                     if ($key eq 'admin') {
12018:                                         my @mgrdc = ();
12019:                                         if (ref($ordered{$key}) eq 'ARRAY') {
12020:                                             foreach my $item (@{$ordered{'admin'}}) {
12021:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
12022:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
12023:                                                         push(@mgrdc,$item);
12024:                                                     }
12025:                                                 }
12026:                                             }
12027:                                             if (@mgrdc) {
12028:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
12029:                                             } else {
12030:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
12031:                                             }
12032:                                         }
12033:                                     } else {
12034:                                         if (ref($ordered{$key}) eq 'ARRAY') {
12035:                                             foreach my $item (@{$ordered{$key}}) {
12036:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
12037:                                                     $domdefaults{$type.'selfenroll'.$item} =
12038:                                                         $selfenrollhash{$key}{$type}{$item};
12039:                                                 }
12040:                                             }
12041:                                         }
12042:                                     }
12043:                                 }
12044:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
12045:                                 foreach my $item (@{$ordered{$key}}) {
12046:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
12047:                                         $resulttext .= '<li>';
12048:                                         if ($key eq 'admin') {
12049:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
12050:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
12051:                                         } else {
12052:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
12053:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
12054:                                         }
12055:                                         $resulttext .= '</li>';
12056:                                     }
12057:                                 }
12058:                                 $resulttext .= '</ul></li>';
12059:                             }
12060:                         }
12061:                         $resulttext .= '</ul></li>'; 
12062:                     }
12063:                 }
12064:                 if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
12065:                     my $cachetime = 24*60*60;
12066:                     &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
12067:                     if (ref($lastactref) eq 'HASH') {
12068:                         $lastactref->{'domdefaults'} = 1;
12069:                     }
12070:                 }
12071:             }
12072:             $resulttext .= '</ul>';
12073:         } else {
12074:             $resulttext = &mt('No changes made to self-enrollment settings');
12075:         }
12076:     } else {
12077:         $resulttext = '<span class="LC_error">'.
12078:             &mt('An error occurred: [_1]',$putresult).'</span>';
12079:     }
12080:     return $resulttext;
12081: }
12082: 
12083: sub modify_usersessions {
12084:     my ($dom,$lastactref,%domconfig) = @_;
12085:     my @hostingtypes = ('version','excludedomain','includedomain');
12086:     my @offloadtypes = ('primary','default');
12087:     my %types = (
12088:                   remote => \@hostingtypes,
12089:                   hosted => \@hostingtypes,
12090:                   spares => \@offloadtypes,
12091:                 );
12092:     my @prefixes = ('remote','hosted','spares');
12093:     my @lcversions = &Apache::lonnet::all_loncaparevs();
12094:     my (%by_ip,%by_location,@intdoms);
12095:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
12096:     my @locations = sort(keys(%by_location));
12097:     my (%defaultshash,%changes);
12098:     foreach my $prefix (@prefixes) {
12099:         $defaultshash{'usersessions'}{$prefix} = {};
12100:     }
12101:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12102:     my $resulttext;
12103:     my %iphost = &Apache::lonnet::get_iphost();
12104:     foreach my $prefix (@prefixes) {
12105:         next if ($prefix eq 'spares');
12106:         foreach my $type (@{$types{$prefix}}) {
12107:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
12108:             if ($type eq 'version') {
12109:                 my $value = $env{'form.'.$prefix.'_'.$type};
12110:                 my $okvalue;
12111:                 if ($value ne '') {
12112:                     if (grep(/^\Q$value\E$/,@lcversions)) {
12113:                         $okvalue = $value;
12114:                     }
12115:                 }
12116:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
12117:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
12118:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
12119:                             if ($inuse == 0) {
12120:                                 $changes{$prefix}{$type} = 1;
12121:                             } else {
12122:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
12123:                                     $changes{$prefix}{$type} = 1;
12124:                                 }
12125:                                 if ($okvalue ne '') {
12126:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
12127:                                 } 
12128:                             }
12129:                         } else {
12130:                             if (($inuse == 1) && ($okvalue ne '')) {
12131:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
12132:                                 $changes{$prefix}{$type} = 1;
12133:                             }
12134:                         }
12135:                     } else {
12136:                         if (($inuse == 1) && ($okvalue ne '')) {
12137:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
12138:                             $changes{$prefix}{$type} = 1;
12139:                         }
12140:                     }
12141:                 } else {
12142:                     if (($inuse == 1) && ($okvalue ne '')) {
12143:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
12144:                         $changes{$prefix}{$type} = 1;
12145:                     }
12146:                 }
12147:             } else {
12148:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
12149:                 my @okvals;
12150:                 foreach my $val (@vals) {
12151:                     if ($val =~ /:/) {
12152:                         my @items = split(/:/,$val);
12153:                         foreach my $item (@items) {
12154:                             if (ref($by_location{$item}) eq 'ARRAY') {
12155:                                 push(@okvals,$item);
12156:                             }
12157:                         }
12158:                     } else {
12159:                         if (ref($by_location{$val}) eq 'ARRAY') {
12160:                             push(@okvals,$val);
12161:                         }
12162:                     }
12163:                 }
12164:                 @okvals = sort(@okvals);
12165:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
12166:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
12167:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
12168:                             if ($inuse == 0) {
12169:                                 $changes{$prefix}{$type} = 1; 
12170:                             } else {
12171:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
12172:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
12173:                                 if (@changed > 0) {
12174:                                     $changes{$prefix}{$type} = 1;
12175:                                 }
12176:                             }
12177:                         } else {
12178:                             if ($inuse == 1) {
12179:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
12180:                                 $changes{$prefix}{$type} = 1;
12181:                             }
12182:                         } 
12183:                     } else {
12184:                         if ($inuse == 1) {
12185:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
12186:                             $changes{$prefix}{$type} = 1;
12187:                         }
12188:                     }
12189:                 } else {
12190:                     if ($inuse == 1) {
12191:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
12192:                         $changes{$prefix}{$type} = 1;
12193:                     }
12194:                 }
12195:             }
12196:         }
12197:     }
12198: 
12199:     my @alldoms = &Apache::lonnet::all_domains();
12200:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
12201:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
12202:     my $savespares;
12203: 
12204:     foreach my $lonhost (sort(keys(%servers))) {
12205:         my $serverhomeID =
12206:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
12207:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
12208:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
12209:         my %spareschg;
12210:         foreach my $type (@{$types{'spares'}}) {
12211:             my @okspares;
12212:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
12213:             foreach my $server (@checked) {
12214:                 if (&Apache::lonnet::hostname($server) ne '') {
12215:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
12216:                         unless (grep(/^\Q$server\E$/,@okspares)) {
12217:                             push(@okspares,$server);
12218:                         }
12219:                     }
12220:                 }
12221:             }
12222:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
12223:             my $newspare;
12224:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
12225:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
12226:                     $newspare = $new;
12227:                 }
12228:             }
12229:             my @spares;
12230:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
12231:                 @spares = sort(@okspares,$newspare);
12232:             } else {
12233:                 @spares = sort(@okspares);
12234:             }
12235:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
12236:             if (ref($spareid{$lonhost}) eq 'HASH') {
12237:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
12238:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
12239:                     if (@diffs > 0) {
12240:                         $spareschg{$type} = 1;
12241:                     }
12242:                 }
12243:             }
12244:         }
12245:         if (keys(%spareschg) > 0) {
12246:             $changes{'spares'}{$lonhost} = \%spareschg;
12247:         }
12248:     }
12249:     $defaultshash{'usersessions'}{'offloadnow'} = {};
12250:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
12251:     my @okoffload;
12252:     if (@offloadnow) {
12253:         foreach my $server (@offloadnow) {
12254:             if (&Apache::lonnet::hostname($server) ne '') {
12255:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
12256:                     push(@okoffload,$server);
12257:                 }
12258:             }
12259:         }
12260:         if (@okoffload) {
12261:             foreach my $lonhost (@okoffload) {
12262:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
12263:             }
12264:         }
12265:     }
12266:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
12267:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
12268:             if (ref($changes{'spares'}) eq 'HASH') {
12269:                 if (keys(%{$changes{'spares'}}) > 0) {
12270:                     $savespares = 1;
12271:                 }
12272:             }
12273:         } else {
12274:             $savespares = 1;
12275:         }
12276:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
12277:             foreach my $lonhost (keys(%{$domconfig{'usersessions'}{'offloadnow'}})) {
12278:                 unless ($defaultshash{'usersessions'}{'offloadnow'}{$lonhost}) {
12279:                     $changes{'offloadnow'} = 1;
12280:                     last;
12281:                 }
12282:             }
12283:             unless ($changes{'offloadnow'}) {
12284:                 foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{'offloadnow'}})) {
12285:                     unless ($domconfig{'usersessions'}{'offloadnow'}{$lonhost}) {
12286:                         $changes{'offloadnow'} = 1;
12287:                         last;
12288:                     }
12289:                 }
12290:             }
12291:         } elsif (@okoffload) {
12292:             $changes{'offloadnow'} = 1;
12293:         }
12294:     } elsif (@okoffload) {
12295:         $changes{'offloadnow'} = 1;
12296:     }
12297:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
12298:     if ((keys(%changes) > 0) || ($savespares)) {
12299:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
12300:                                                  $dom);
12301:         if ($putresult eq 'ok') {
12302:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
12303:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
12304:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
12305:                 }
12306:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
12307:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
12308:                 }
12309:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
12310:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
12311:                 }
12312:             }
12313:             my $cachetime = 24*60*60;
12314:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
12315:             if (ref($lastactref) eq 'HASH') {
12316:                 $lastactref->{'domdefaults'} = 1;
12317:             }
12318:             if (keys(%changes) > 0) {
12319:                 my %lt = &usersession_titles();
12320:                 $resulttext = &mt('Changes made:').'<ul>';
12321:                 foreach my $prefix (@prefixes) {
12322:                     if (ref($changes{$prefix}) eq 'HASH') {
12323:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
12324:                         if ($prefix eq 'spares') {
12325:                             if (ref($changes{$prefix}) eq 'HASH') {
12326:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
12327:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
12328:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
12329:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
12330:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
12331:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
12332:                                         foreach my $type (@{$types{$prefix}}) {
12333:                                             if ($changes{$prefix}{$lonhost}{$type}) {
12334:                                                 my $offloadto = &mt('None');
12335:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
12336:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
12337:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
12338:                                                     }
12339:                                                 }
12340:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
12341:                                             }
12342:                                         }
12343:                                     }
12344:                                     $resulttext .= '</li>';
12345:                                 }
12346:                             }
12347:                         } else {
12348:                             foreach my $type (@{$types{$prefix}}) {
12349:                                 if (defined($changes{$prefix}{$type})) {
12350:                                     my $newvalue;
12351:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
12352:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
12353:                                             if ($type eq 'version') {
12354:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
12355:                                             } elsif (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
12356:                                                 if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
12357:                                                     $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
12358:                                                 }
12359:                                             }
12360:                                         }
12361:                                     }
12362:                                     if ($newvalue eq '') {
12363:                                         if ($type eq 'version') {
12364:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
12365:                                         } else {
12366:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
12367:                                         }
12368:                                     } else {
12369:                                         if ($type eq 'version') {
12370:                                             $newvalue .= ' '.&mt('(or later)'); 
12371:                                         }
12372:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
12373:                                     }
12374:                                 }
12375:                             }
12376:                         }
12377:                         $resulttext .= '</ul>';
12378:                     }
12379:                 }
12380:                 if ($changes{'offloadnow'}) {
12381:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
12382:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
12383:                             $resulttext .= '<li>'.&mt('Switch active users on next access, for server(s):').'<ul>';
12384:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
12385:                                 $resulttext .= '<li>'.$lonhost.'</li>';
12386:                             }
12387:                             $resulttext .= '</ul>';
12388:                         } else {
12389:                             $resulttext .= '<li>'.&mt('No servers now set to switch active users on next access.');
12390:                         }
12391:                     } else {
12392:                         $resulttext .= '<li>'.&mt('No servers now set to switch active users on next access.').'</li>';
12393:                     }
12394:                 }
12395:                 $resulttext .= '</ul>';
12396:             } else {
12397:                 $resulttext = $nochgmsg;
12398:             }
12399:         } else {
12400:             $resulttext = '<span class="LC_error">'.
12401:                           &mt('An error occurred: [_1]',$putresult).'</span>';
12402:         }
12403:     } else {
12404:         $resulttext = $nochgmsg;
12405:     }
12406:     return $resulttext;
12407: }
12408: 
12409: sub modify_loadbalancing {
12410:     my ($dom,%domconfig) = @_;
12411:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
12412:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
12413:     my ($othertitle,$usertypes,$types) =
12414:         &Apache::loncommon::sorted_inst_types($dom);
12415:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
12416:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
12417:     my @sparestypes = ('primary','default');
12418:     my %typetitles = &sparestype_titles();
12419:     my $resulttext;
12420:     my (%currbalancer,%currtargets,%currrules,%existing);
12421:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
12422:         %existing = %{$domconfig{'loadbalancing'}};
12423:     }
12424:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
12425:                               \%currtargets,\%currrules);
12426:     my ($saveloadbalancing,%defaultshash,%changes);
12427:     my ($alltypes,$othertypes,$titles) =
12428:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
12429:     my %ruletitles = &offloadtype_text();
12430:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
12431:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
12432:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
12433:         if ($balancer eq '') {
12434:             next;
12435:         }
12436:         if (!exists($servers{$balancer})) {
12437:             if (exists($currbalancer{$balancer})) {
12438:                 push(@{$changes{'delete'}},$balancer);
12439:             }
12440:             next;
12441:         }
12442:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
12443:             push(@{$changes{'delete'}},$balancer);
12444:             next;
12445:         }
12446:         if (!exists($currbalancer{$balancer})) {
12447:             push(@{$changes{'add'}},$balancer);
12448:         }
12449:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
12450:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
12451:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
12452:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
12453:             $saveloadbalancing = 1;
12454:         }
12455:         foreach my $sparetype (@sparestypes) {
12456:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
12457:             my @offloadto;
12458:             foreach my $target (@targets) {
12459:                 if (($servers{$target}) && ($target ne $balancer)) {
12460:                     if ($sparetype eq 'default') {
12461:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
12462:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
12463:                         }
12464:                     }
12465:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
12466:                         push(@offloadto,$target);
12467:                     }
12468:                 }
12469:             }
12470:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
12471:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
12472:                     push(@offloadto,$balancer);
12473:                 }
12474:             }
12475:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
12476:         }
12477:         if (ref($currtargets{$balancer}) eq 'HASH') {
12478:             foreach my $sparetype (@sparestypes) {
12479:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
12480:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
12481:                     if (@targetdiffs > 0) {
12482:                         $changes{'curr'}{$balancer}{'targets'} = 1;
12483:                     }
12484:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
12485:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
12486:                         $changes{'curr'}{$balancer}{'targets'} = 1;
12487:                     }
12488:                 }
12489:             }
12490:         } else {
12491:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
12492:                 foreach my $sparetype (@sparestypes) {
12493:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
12494:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
12495:                             $changes{'curr'}{$balancer}{'targets'} = 1;
12496:                         }
12497:                     }
12498:                 }
12499:             }
12500:         }
12501:         my $ishomedom;
12502:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
12503:             $ishomedom = 1;
12504:         }
12505:         if (ref($alltypes) eq 'ARRAY') {
12506:             foreach my $type (@{$alltypes}) {
12507:                 my $rule;
12508:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
12509:                          (!$ishomedom)) {
12510:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
12511:                 }
12512:                 if ($rule eq 'specific') {
12513:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
12514:                     if (exists($servers{$specifiedhost})) {
12515:                         $rule = $specifiedhost;
12516:                     }
12517:                 }
12518:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
12519:                 if (ref($currrules{$balancer}) eq 'HASH') {
12520:                     if ($rule ne $currrules{$balancer}{$type}) {
12521:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
12522:                     }
12523:                 } elsif ($rule ne '') {
12524:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
12525:                 }
12526:             }
12527:         }
12528:     }
12529:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
12530:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
12531:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
12532:             $defaultshash{'loadbalancing'} = {};
12533:         }
12534:         my $putresult = &Apache::lonnet::put_dom('configuration',
12535:                                                  \%defaultshash,$dom);
12536:         if ($putresult eq 'ok') {
12537:             if (keys(%changes) > 0) {
12538:                 my %toupdate;
12539:                 if (ref($changes{'delete'}) eq 'ARRAY') {
12540:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
12541:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
12542:                         $toupdate{$balancer} = 1;
12543:                     }
12544:                 }
12545:                 if (ref($changes{'add'}) eq 'ARRAY') {
12546:                     foreach my $balancer (sort(@{$changes{'add'}})) {
12547:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
12548:                         $toupdate{$balancer} = 1;
12549:                     }
12550:                 }
12551:                 if (ref($changes{'curr'}) eq 'HASH') {
12552:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
12553:                         $toupdate{$balancer} = 1;
12554:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
12555:                             if ($changes{'curr'}{$balancer}{'targets'}) {
12556:                                 my %offloadstr;
12557:                                 foreach my $sparetype (@sparestypes) {
12558:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
12559:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
12560:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
12561:                                         }
12562:                                     }
12563:                                 }
12564:                                 if (keys(%offloadstr) == 0) {
12565:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
12566:                                 } else {
12567:                                     my $showoffload;
12568:                                     foreach my $sparetype (@sparestypes) {
12569:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
12570:                                         if (defined($offloadstr{$sparetype})) {
12571:                                             $showoffload .= $offloadstr{$sparetype};
12572:                                         } else {
12573:                                             $showoffload .= &mt('None');
12574:                                         }
12575:                                         $showoffload .= ('&nbsp;'x3);
12576:                                     }
12577:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
12578:                                 }
12579:                             }
12580:                         }
12581:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
12582:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
12583:                                 foreach my $type (@{$alltypes}) {
12584:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
12585:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
12586:                                         my $balancetext;
12587:                                         if ($rule eq '') {
12588:                                             $balancetext =  $ruletitles{'default'};
12589:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
12590:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
12591:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
12592:                                                 foreach my $sparetype (@sparestypes) {
12593:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
12594:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
12595:                                                     }
12596:                                                 }
12597:                                                 foreach my $item (@{$alltypes}) {
12598:                                                     next if ($item =~  /^_LC_ipchange/);
12599:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
12600:                                                     if ($hasrule eq 'homeserver') {
12601:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
12602:                                                     } else {
12603:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
12604:                                                             if ($servers{$hasrule}) {
12605:                                                                 $toupdate{$hasrule} = 1;
12606:                                                             }
12607:                                                         }
12608:                                                     }
12609:                                                 }
12610:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
12611:                                                     $balancetext =  $ruletitles{$rule};
12612:                                                 } else {
12613:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
12614:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
12615:                                                     if ($receiver) {
12616:                                                         $toupdate{$receiver};
12617:                                                     }
12618:                                                 }
12619:                                             } else {
12620:                                                 $balancetext =  $ruletitles{$rule};
12621:                                             }
12622:                                         } else {
12623:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
12624:                                         }
12625:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
12626:                                     }
12627:                                 }
12628:                             }
12629:                         }
12630:                         if (keys(%toupdate)) {
12631:                             my %thismachine;
12632:                             my $updatedhere;
12633:                             my $cachetime = 60*60*24;
12634:                             map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
12635:                             foreach my $lonhost (keys(%toupdate)) {
12636:                                 if ($thismachine{$lonhost}) {
12637:                                     unless ($updatedhere) {
12638:                                         &Apache::lonnet::do_cache_new('loadbalancing',$dom,
12639:                                                                       $defaultshash{'loadbalancing'},
12640:                                                                       $cachetime);
12641:                                         $updatedhere = 1;
12642:                                     }
12643:                                 } else {
12644:                                     my $cachekey = &escape('loadbalancing').':'.&escape($dom);
12645:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
12646:                                 }
12647:                             }
12648:                         }
12649:                     }
12650:                 }
12651:                 if ($resulttext ne '') {
12652:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
12653:                 } else {
12654:                     $resulttext = $nochgmsg;
12655:                 }
12656:             } else {
12657:                 $resulttext = $nochgmsg;
12658:             }
12659:         } else {
12660:             $resulttext = '<span class="LC_error">'.
12661:                           &mt('An error occurred: [_1]',$putresult).'</span>';
12662:         }
12663:     } else {
12664:         $resulttext = $nochgmsg;
12665:     }
12666:     return $resulttext;
12667: }
12668: 
12669: sub recurse_check {
12670:     my ($chkcats,$categories,$depth,$name) = @_;
12671:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
12672:         my $chg = 0;
12673:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
12674:             my $category = $chkcats->[$depth]{$name}[$j];
12675:             my $item;
12676:             if ($category eq '') {
12677:                 $chg ++;
12678:             } else {
12679:                 my $deeper = $depth + 1;
12680:                 $item = &escape($category).':'.&escape($name).':'.$depth;
12681:                 if ($chg) {
12682:                     $categories->{$item} -= $chg;
12683:                 }
12684:                 &recurse_check($chkcats,$categories,$deeper,$category);
12685:                 $deeper --;
12686:             }
12687:         }
12688:     }
12689:     return;
12690: }
12691: 
12692: sub recurse_cat_deletes {
12693:     my ($item,$coursecategories,$deletions) = @_;
12694:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
12695:     my $subdepth = $depth + 1;
12696:     if (ref($coursecategories) eq 'HASH') {
12697:         foreach my $subitem (keys(%{$coursecategories})) {
12698:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
12699:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
12700:                 delete($coursecategories->{$subitem});
12701:                 $deletions->{$subitem} = 1;
12702:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
12703:             }
12704:         }
12705:     }
12706:     return;
12707: }
12708: 
12709: sub active_dc_picker {
12710:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
12711:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
12712:     my @domcoord = keys(%domcoords);
12713:     if (keys(%currhash)) {
12714:         foreach my $dc (keys(%currhash)) {
12715:             unless (exists($domcoords{$dc})) {
12716:                 push(@domcoord,$dc);
12717:             }
12718:         }
12719:     }
12720:     @domcoord = sort(@domcoord);
12721:     my $numdcs = scalar(@domcoord);
12722:     my $rows = 0;
12723:     my $table;
12724:     if ($numdcs > 1) {
12725:         $table = '<table>';
12726:         for (my $i=0; $i<@domcoord; $i++) {
12727:             my $rem = $i%($numinrow);
12728:             if ($rem == 0) {
12729:                 if ($i > 0) {
12730:                     $table .= '</tr>';
12731:                 }
12732:                 $table .= '<tr>';
12733:                 $rows ++;
12734:             }
12735:             my $check = '';
12736:             if ($inputtype eq 'radio') {
12737:                 if (keys(%currhash) == 0) {
12738:                     if (!$i) {
12739:                         $check = ' checked="checked"';
12740:                     }
12741:                 } elsif (exists($currhash{$domcoord[$i]})) {
12742:                     $check = ' checked="checked"';
12743:                 }
12744:             } else {
12745:                 if (exists($currhash{$domcoord[$i]})) {
12746:                     $check = ' checked="checked"';
12747:                 }
12748:             }
12749:             if ($i == @domcoord - 1) {
12750:                 my $colsleft = $numinrow - $rem;
12751:                 if ($colsleft > 1) {
12752:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
12753:                 } else {
12754:                     $table .= '<td class="LC_left_item">';
12755:                 }
12756:             } else {
12757:                 $table .= '<td class="LC_left_item">';
12758:             }
12759:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
12760:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
12761:             $table .= '<span class="LC_nobreak"><label>'.
12762:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
12763:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
12764:             if ($user ne $dcname.':'.$dcdom) {
12765:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
12766:             }
12767:             $table .= '</label></span></td>';
12768:         }
12769:         $table .= '</tr></table>';
12770:     } elsif ($numdcs == 1) {
12771:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
12772:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
12773:         if ($inputtype eq 'radio') {
12774:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
12775:             if ($user ne $dcname.':'.$dcdom) {
12776:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
12777:             }
12778:         } else {
12779:             my $check;
12780:             if (exists($currhash{$domcoord[0]})) {
12781:                 $check = ' checked="checked"';
12782:             }
12783:             $table = '<span class="LC_nobreak"><label>'.
12784:                      '<input type="checkbox" name="'.$name.'" '.
12785:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
12786:             if ($user ne $dcname.':'.$dcdom) {
12787:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
12788:             }
12789:             $table .= '</label></span>';
12790:             $rows ++;
12791:         }
12792:     }
12793:     return ($numdcs,$table,$rows);
12794: }
12795: 
12796: sub usersession_titles {
12797:     return &Apache::lonlocal::texthash(
12798:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
12799:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
12800:                spares => 'Servers offloaded to, when busy',
12801:                version => 'LON-CAPA version requirement',
12802:                excludedomain => 'Allow all, but exclude specific domains',
12803:                includedomain => 'Deny all, but include specific domains',
12804:                primary => 'Primary (checked first)',
12805:                default => 'Default',
12806:            );
12807: }
12808: 
12809: sub id_for_thisdom {
12810:     my (%servers) = @_;
12811:     my %altids;
12812:     foreach my $server (keys(%servers)) {
12813:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
12814:         if ($serverhome ne $server) {
12815:             $altids{$serverhome} = $server;
12816:         }
12817:     }
12818:     return %altids;
12819: }
12820: 
12821: sub count_servers {
12822:     my ($currbalancer,%servers) = @_;
12823:     my (@spares,$numspares);
12824:     foreach my $lonhost (sort(keys(%servers))) {
12825:         next if ($currbalancer eq $lonhost);
12826:         push(@spares,$lonhost);
12827:     }
12828:     if ($currbalancer) {
12829:         $numspares = scalar(@spares);
12830:     } else {
12831:         $numspares = scalar(@spares) - 1;
12832:     }
12833:     return ($numspares,@spares);
12834: }
12835: 
12836: sub lonbalance_targets_js {
12837:     my ($dom,$types,$servers,$settings) = @_;
12838:     my $select = &mt('Select');
12839:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
12840:     if (ref($servers) eq 'HASH') {
12841:         $alltargets = join("','",sort(keys(%{$servers})));
12842:         my @homedoms;
12843:         foreach my $server (sort(keys(%{$servers}))) {
12844:             if (&Apache::lonnet::host_domain($server) eq $dom) {
12845:                 push(@homedoms,'1');
12846:             } else {
12847:                 push(@homedoms,'0');
12848:             }
12849:         }
12850:         $allishome = join("','",@homedoms);
12851:     }
12852:     if (ref($types) eq 'ARRAY') {
12853:         if (@{$types} > 0) {
12854:             @alltypes = @{$types};
12855:         }
12856:     }
12857:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
12858:     $allinsttypes = join("','",@alltypes);
12859:     my (%currbalancer,%currtargets,%currrules,%existing);
12860:     if (ref($settings) eq 'HASH') {
12861:         %existing = %{$settings};
12862:     }
12863:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
12864:                               \%currtargets,\%currrules);
12865:     my $balancers = join("','",sort(keys(%currbalancer)));
12866:     return <<"END";
12867: 
12868: <script type="text/javascript">
12869: // <![CDATA[
12870: 
12871: currBalancers = new Array('$balancers');
12872: 
12873: function toggleTargets(balnum) {
12874:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
12875:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
12876:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
12877:     var prevbalancer = prevhostitem.value;
12878:     var baltotal = document.getElementById('loadbalancing_total').value;
12879:     prevhostitem.value = balancer;
12880:     if (prevbalancer != '') {
12881:         var prevIdx = currBalancers.indexOf(prevbalancer);
12882:         if (prevIdx != -1) {
12883:             currBalancers.splice(prevIdx,1);
12884:         }
12885:     }
12886:     if (balancer == '') {
12887:         hideSpares(balnum);
12888:     } else {
12889:         var currIdx = currBalancers.indexOf(balancer);
12890:         if (currIdx == -1) {
12891:             currBalancers.push(balancer);
12892:         }
12893:         var homedoms = new Array('$allishome');
12894:         var ishomedom = homedoms[lonhostitem.selectedIndex];
12895:         showSpares(balancer,ishomedom,balnum);
12896:     }
12897:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
12898:     return;
12899: }
12900: 
12901: function showSpares(balancer,ishomedom,balnum) {
12902:     var alltargets = new Array('$alltargets');
12903:     var insttypes = new Array('$allinsttypes');
12904:     var offloadtypes = new Array('primary','default');
12905: 
12906:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
12907:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
12908:  
12909:     for (var i=0; i<offloadtypes.length; i++) {
12910:         var count = 0;
12911:         for (var j=0; j<alltargets.length; j++) {
12912:             if (alltargets[j] != balancer) {
12913:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
12914:                 item.value = alltargets[j];
12915:                 item.style.textAlign='left';
12916:                 item.style.textFace='normal';
12917:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
12918:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
12919:                     item.disabled = '';
12920:                 } else {
12921:                     item.disabled = 'disabled';
12922:                     item.checked = false;
12923:                 }
12924:                 count ++;
12925:             }
12926:         }
12927:     }
12928:     for (var k=0; k<insttypes.length; k++) {
12929:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
12930:             if (ishomedom == 1) {
12931:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
12932:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
12933:             } else {
12934:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
12935:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
12936:             }
12937:         } else {
12938:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
12939:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
12940:         }
12941:         if ((insttypes[k] != '_LC_external') && 
12942:             ((insttypes[k] != '_LC_internetdom') ||
12943:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
12944:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
12945:             item.options.length = 0;
12946:             item.options[0] = new Option("","",true,true);
12947:             var idx = 0;
12948:             for (var m=0; m<alltargets.length; m++) {
12949:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
12950:                     idx ++;
12951:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
12952:                 }
12953:             }
12954:         }
12955:     }
12956:     return;
12957: }
12958: 
12959: function hideSpares(balnum) {
12960:     var alltargets = new Array('$alltargets');
12961:     var insttypes = new Array('$allinsttypes');
12962:     var offloadtypes = new Array('primary','default');
12963: 
12964:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
12965:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
12966: 
12967:     var total = alltargets.length - 1;
12968:     for (var i=0; i<offloadtypes; i++) {
12969:         for (var j=0; j<total; j++) {
12970:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
12971:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
12972:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
12973:         }
12974:     }
12975:     for (var k=0; k<insttypes.length; k++) {
12976:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
12977:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
12978:         if (insttypes[k] != '_LC_external') {
12979:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
12980:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
12981:         }
12982:     }
12983:     return;
12984: }
12985: 
12986: function checkOffloads(item,balnum,type) {
12987:     var alltargets = new Array('$alltargets');
12988:     var offloadtypes = new Array('primary','default');
12989:     if (item.checked) {
12990:         var total = alltargets.length - 1;
12991:         var other;
12992:         if (type == offloadtypes[0]) {
12993:             other = offloadtypes[1];
12994:         } else {
12995:             other = offloadtypes[0];
12996:         }
12997:         for (var i=0; i<total; i++) {
12998:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
12999:             if (server == item.value) {
13000:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
13001:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
13002:                 }
13003:             }
13004:         }
13005:     }
13006:     return;
13007: }
13008: 
13009: function singleServerToggle(balnum,type) {
13010:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
13011:     if (offloadtoSelIdx == 0) {
13012:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
13013:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
13014: 
13015:     } else {
13016:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
13017:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
13018:     }
13019:     return;
13020: }
13021: 
13022: function balanceruleChange(formname,balnum,type) {
13023:     if (type == '_LC_external') {
13024:         return;
13025:     }
13026:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
13027:     for (var i=0; i<typesRules.length; i++) {
13028:         if (formname.elements[typesRules[i]].checked) {
13029:             if (formname.elements[typesRules[i]].value != 'specific') {
13030:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
13031:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
13032:             } else {
13033:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
13034:             }
13035:         }
13036:     }
13037:     return;
13038: }
13039: 
13040: function balancerDeleteChange(balnum) {
13041:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
13042:     var baltotal = document.getElementById('loadbalancing_total').value;
13043:     var addtarget;
13044:     var removetarget;
13045:     var action = 'delete';
13046:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
13047:         var lonhost = hostitem.value;
13048:         var currIdx = currBalancers.indexOf(lonhost);
13049:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
13050:             if (currIdx != -1) {
13051:                 currBalancers.splice(currIdx,1);
13052:             }
13053:             addtarget = lonhost;
13054:         } else {
13055:             if (currIdx == -1) {
13056:                 currBalancers.push(lonhost);
13057:             }
13058:             removetarget = lonhost;
13059:             action = 'undelete';
13060:         }
13061:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
13062:     }
13063:     return;
13064: }
13065: 
13066: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
13067:     if (baltotal > 1) {
13068:         var offloadtypes = new Array('primary','default');
13069:         var alltargets = new Array('$alltargets');
13070:         var insttypes = new Array('$allinsttypes');
13071:         for (var i=0; i<baltotal; i++) {
13072:             if (i != balnum) {
13073:                 for (var j=0; j<offloadtypes.length; j++) {
13074:                     var total = alltargets.length - 1;
13075:                     for (var k=0; k<total; k++) {
13076:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
13077:                         var server = serveritem.value;
13078:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
13079:                             if (server == addtarget) {
13080:                                 serveritem.disabled = '';
13081:                             }
13082:                         }
13083:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
13084:                             if (server == removetarget) {
13085:                                 serveritem.disabled = 'disabled';
13086:                                 serveritem.checked = false;
13087:                             }
13088:                         }
13089:                     }
13090:                 }
13091:                 for (var j=0; j<insttypes.length; j++) {
13092:                     if (insttypes[j] != '_LC_external') {
13093:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
13094:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
13095:                             var currSel = singleserver.selectedIndex;
13096:                             var currVal = singleserver.options[currSel].value;
13097:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
13098:                                 var numoptions = singleserver.options.length;
13099:                                 var needsnew = 1;
13100:                                 for (var k=0; k<numoptions; k++) {
13101:                                     if (singleserver.options[k] == addtarget) {
13102:                                         needsnew = 0;
13103:                                         break;
13104:                                     }
13105:                                 }
13106:                                 if (needsnew == 1) {
13107:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
13108:                                 }
13109:                             }
13110:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
13111:                                 singleserver.options.length = 0;
13112:                                 if ((currVal) && (currVal != removetarget)) {
13113:                                     singleserver.options[0] = new Option("","",false,false);
13114:                                 } else {
13115:                                     singleserver.options[0] = new Option("","",true,true);
13116:                                 }
13117:                                 var idx = 0;
13118:                                 for (var m=0; m<alltargets.length; m++) {
13119:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
13120:                                         idx ++;
13121:                                         if (currVal == alltargets[m]) {
13122:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
13123:                                         } else {
13124:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
13125:                                         }
13126:                                     }
13127:                                 }
13128:                             }
13129:                         }
13130:                     }
13131:                 }
13132:             }
13133:         }
13134:     }
13135:     return;
13136: }
13137: 
13138: // ]]>
13139: </script>
13140: 
13141: END
13142: }
13143: 
13144: sub new_spares_js {
13145:     my @sparestypes = ('primary','default');
13146:     my $types = join("','",@sparestypes);
13147:     my $select = &mt('Select');
13148:     return <<"END";
13149: 
13150: <script type="text/javascript">
13151: // <![CDATA[
13152: 
13153: function updateNewSpares(formname,lonhost) {
13154:     var types = new Array('$types');
13155:     var include = new Array();
13156:     var exclude = new Array();
13157:     for (var i=0; i<types.length; i++) {
13158:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
13159:         for (var j=0; j<spareboxes.length; j++) {
13160:             if (formname.elements[spareboxes[j]].checked) {
13161:                 exclude.push(formname.elements[spareboxes[j]].value);
13162:             } else {
13163:                 include.push(formname.elements[spareboxes[j]].value);
13164:             }
13165:         }
13166:     }
13167:     for (var i=0; i<types.length; i++) {
13168:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
13169:         var selIdx = newSpare.selectedIndex;
13170:         var currnew = newSpare.options[selIdx].value;
13171:         var okSpares = new Array();
13172:         for (var j=0; j<newSpare.options.length; j++) {
13173:             var possible = newSpare.options[j].value;
13174:             if (possible != '') {
13175:                 if (exclude.indexOf(possible) == -1) {
13176:                     okSpares.push(possible);
13177:                 } else {
13178:                     if (currnew == possible) {
13179:                         selIdx = 0;
13180:                     }
13181:                 }
13182:             }
13183:         }
13184:         for (var k=0; k<include.length; k++) {
13185:             if (okSpares.indexOf(include[k]) == -1) {
13186:                 okSpares.push(include[k]);
13187:             }
13188:         }
13189:         okSpares.sort();
13190:         newSpare.options.length = 0;
13191:         if (selIdx == 0) {
13192:             newSpare.options[0] = new Option("$select","",true,true);
13193:         } else {
13194:             newSpare.options[0] = new Option("$select","",false,false);
13195:         }
13196:         for (var m=0; m<okSpares.length; m++) {
13197:             var idx = m+1;
13198:             var selThis = 0;
13199:             if (selIdx != 0) {
13200:                 if (okSpares[m] == currnew) {
13201:                     selThis = 1;
13202:                 }
13203:             }
13204:             if (selThis == 1) {
13205:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
13206:             } else {
13207:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
13208:             }
13209:         }
13210:     }
13211:     return;
13212: }
13213: 
13214: function checkNewSpares(lonhost,type) {
13215:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
13216:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
13217:     if (chosen != '') { 
13218:         var othertype;
13219:         var othernewSpare;
13220:         if (type == 'primary') {
13221:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
13222:         }
13223:         if (type == 'default') {
13224:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
13225:         }
13226:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
13227:             othernewSpare.selectedIndex = 0;
13228:         }
13229:     }
13230:     return;
13231: }
13232: 
13233: // ]]>
13234: </script>
13235: 
13236: END
13237: 
13238: }
13239: 
13240: sub common_domprefs_js {
13241:     return <<"END";
13242: 
13243: <script type="text/javascript">
13244: // <![CDATA[
13245: 
13246: function getIndicesByName(formname,item) {
13247:     var group = new Array();
13248:     for (var i=0;i<formname.elements.length;i++) {
13249:         if (formname.elements[i].name == item) {
13250:             group.push(formname.elements[i].id);
13251:         }
13252:     }
13253:     return group;
13254: }
13255: 
13256: // ]]>
13257: </script>
13258: 
13259: END
13260: 
13261: }
13262: 
13263: sub recaptcha_js {
13264:     my %lt = &captcha_phrases();
13265:     return <<"END";
13266: 
13267: <script type="text/javascript">
13268: // <![CDATA[
13269: 
13270: function updateCaptcha(caller,context) {
13271:     var privitem;
13272:     var pubitem;
13273:     var privtext;
13274:     var pubtext;
13275:     var versionitem;
13276:     var versiontext;
13277:     if (document.getElementById(context+'_recaptchapub')) {
13278:         pubitem = document.getElementById(context+'_recaptchapub');
13279:     } else {
13280:         return;
13281:     }
13282:     if (document.getElementById(context+'_recaptchapriv')) {
13283:         privitem = document.getElementById(context+'_recaptchapriv');
13284:     } else {
13285:         return;
13286:     }
13287:     if (document.getElementById(context+'_recaptchapubtxt')) {
13288:         pubtext = document.getElementById(context+'_recaptchapubtxt');
13289:     } else {
13290:         return;
13291:     }
13292:     if (document.getElementById(context+'_recaptchaprivtxt')) {
13293:         privtext = document.getElementById(context+'_recaptchaprivtxt');
13294:     } else {
13295:         return;
13296:     }
13297:     if (document.getElementById(context+'_recaptchaversion')) {
13298:         versionitem = document.getElementById(context+'_recaptchaversion');
13299:     } else {
13300:         return;
13301:     }
13302:     if (document.getElementById(context+'_recaptchavertxt')) {
13303:         versiontext = document.getElementById(context+'_recaptchavertxt');
13304:     } else {
13305:         return;
13306:     }
13307:     if (caller.checked) {
13308:         if (caller.value == 'recaptcha') {
13309:             pubitem.type = 'text';
13310:             privitem.type = 'text';
13311:             pubitem.size = '40';
13312:             privitem.size = '40';
13313:             pubtext.innerHTML = "$lt{'pub'}";
13314:             privtext.innerHTML = "$lt{'priv'}";
13315:             versionitem.type = 'text';
13316:             versionitem.size = '3';
13317:             versiontext.innerHTML = "$lt{'ver'}";
13318:         } else {
13319:             pubitem.type = 'hidden';
13320:             privitem.type = 'hidden';
13321:             versionitem.type = 'hidden';
13322:             pubtext.innerHTML = '';
13323:             privtext.innerHTML = '';
13324:             versiontext.innerHTML = '';
13325:         }
13326:     }
13327:     return;
13328: }
13329: 
13330: // ]]>
13331: </script>
13332: 
13333: END
13334: 
13335: }
13336: 
13337: sub toggle_display_js {
13338:     return <<"END";
13339: 
13340: <script type="text/javascript">
13341: // <![CDATA[
13342: 
13343: function toggleDisplay(domForm,caller) {
13344:     if (document.getElementById(caller)) {
13345:         var divitem = document.getElementById(caller);
13346:         var optionsElement = domForm.coursecredits;
13347:         var checkval = 1;
13348:         var dispval = 'block';
13349:         if (caller == 'emailoptions') {
13350:             optionsElement = domForm.cancreate_email; 
13351:         }
13352:         if (caller == 'studentsubmission') {
13353:             optionsElement = domForm.postsubmit;
13354:         }
13355:         if (caller == 'cloneinstcode') {
13356:             optionsElement = domForm.canclone;
13357:             checkval = 'instcode';
13358:         }
13359:         if (optionsElement.length) {
13360:             var currval;
13361:             for (var i=0; i<optionsElement.length; i++) {
13362:                 if (optionsElement[i].checked) {
13363:                    currval = optionsElement[i].value;
13364:                 }
13365:             }
13366:             if (currval == checkval) {
13367:                 divitem.style.display = dispval;
13368:             } else {
13369:                 divitem.style.display = 'none';
13370:             }
13371:         }
13372:     }
13373:     return;
13374: }
13375: 
13376: // ]]>
13377: </script>
13378: 
13379: END
13380: 
13381: }
13382: 
13383: sub captcha_phrases {
13384:     return &Apache::lonlocal::texthash (
13385:                  priv => 'Private key',
13386:                  pub  => 'Public key',
13387:                  original  => 'original (CAPTCHA)',
13388:                  recaptcha => 'successor (ReCAPTCHA)',
13389:                  notused   => 'unused',
13390:                  ver => 'ReCAPTCHA version (1 or 2)',
13391:     );
13392: }
13393: 
13394: sub devalidate_remote_domconfs {
13395:     my ($dom,$cachekeys) = @_;
13396:     return unless (ref($cachekeys) eq 'HASH');
13397:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
13398:     my %thismachine;
13399:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
13400:     my @posscached = ('domainconfig','domdefaults');
13401:     if (keys(%servers)) {
13402:         foreach my $server (keys(%servers)) {
13403:             next if ($thismachine{$server});
13404:             my @cached;
13405:             foreach my $name (@posscached) {
13406:                 if ($cachekeys->{$name}) {
13407:                     push(@cached,&escape($name).':'.&escape($dom));
13408:                 }
13409:             }
13410:             if (@cached) {
13411:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
13412:             }
13413:         }
13414:     }
13415:     return;
13416: }
13417: 
13418: 1;

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