File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.160.6.93: download - view: text, annotated - select for diffs
Tue Jul 30 11:14:53 2019 UTC (4 years, 11 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.160: preferred, unified
- For 2.11
  Backport 1.303, 1.304, 1.305

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.160.6.93 2019/07/30 11:14:53 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 => 'Internal Authentication',
  266:                                   col2 => 'Value'},
  267:                                  {col1 => 'Institutional user types',
  268:                                   col2 => 'Name displayed'}],
  269:                       print => \&print_defaults,
  270:                       modify => \&modify_defaults,
  271:                     },
  272:         'quotas' => 
  273:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  274:                       help => 'Domain_Configuration_Quotas',
  275:                       header => [{col1 => 'User affiliation',
  276:                                   col2 => 'Available tools',
  277:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  278:                       print => \&print_quotas,
  279:                       modify => \&modify_quotas,
  280:                     },
  281:         'autoenroll' =>
  282:                    { text => 'Auto-enrollment settings',
  283:                      help => 'Domain_Configuration_Auto_Enrollment',
  284:                      header => [{col1 => 'Configuration setting',
  285:                                  col2 => 'Value(s)'}],
  286:                      print => \&print_autoenroll,
  287:                      modify => \&modify_autoenroll,
  288:                    },
  289:         'autoupdate' => 
  290:                    { text => 'Auto-update settings',
  291:                      help => 'Domain_Configuration_Auto_Updates',
  292:                      header => [{col1 => 'Setting',
  293:                                  col2 => 'Value',},
  294:                                 {col1 => 'Setting',
  295:                                  col2 => 'Affiliation'},
  296:                                 {col1 => 'User population',
  297:                                  col2 => 'Updatable user data'}],
  298:                      print => \&print_autoupdate,
  299:                      modify => \&modify_autoupdate,
  300:                   },
  301:         'autocreate' => 
  302:                   { text => 'Auto-course creation settings',
  303:                      help => 'Domain_Configuration_Auto_Creation',
  304:                      header => [{col1 => 'Configuration Setting',
  305:                                  col2 => 'Value',}],
  306:                      print => \&print_autocreate,
  307:                      modify => \&modify_autocreate,
  308:                   },
  309:         'directorysrch' => 
  310:                   { text => 'Directory searches',
  311:                     help => 'Domain_Configuration_InstDirectory_Search',
  312:                     header => [{col1 => 'Institutional Directory Setting',
  313:                                 col2 => 'Value',},
  314:                                {col1 => 'LON-CAPA Directory Setting',
  315:                                 col2 => 'Value',}],
  316:                     print => \&print_directorysrch,
  317:                     modify => \&modify_directorysrch,
  318:                   },
  319:         'contacts' =>
  320:                   { text => 'E-mail addresses and helpform',
  321:                     help => 'Domain_Configuration_Contact_Info',
  322:                     header => [{col1 => 'Default e-mail addresses',
  323:                                 col2 => 'Value',},
  324:                                {col1 => 'Recipient(s) for notifications',
  325:                                 col2 => 'Value',},
  326:                                {col1 => 'Ask helpdesk form settings',
  327:                                 col2 => 'Value',},],
  328:                     print => \&print_contacts,
  329:                     modify => \&modify_contacts,
  330:                   },
  331:         'usercreation' => 
  332:                   { text => 'User creation',
  333:                     help => 'Domain_Configuration_User_Creation',
  334:                     header => [{col1 => 'Format rule type',
  335:                                 col2 => 'Format rules in force'},
  336:                                {col1 => 'User account creation',
  337:                                 col2 => 'Usernames which may be created',},
  338:                                {col1 => 'Context',
  339:                                 col2 => 'Assignable authentication types'}],
  340:                     print => \&print_usercreation,
  341:                     modify => \&modify_usercreation,
  342:                   },
  343:         'selfcreation' => 
  344:                   { text => 'Users self-creating accounts',
  345:                     help => 'Domain_Configuration_Self_Creation', 
  346:                     header => [{col1 => 'Self-creation with institutional username',
  347:                                 col2 => 'Enabled?'},
  348:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  349:                                 col2 => 'Information user can enter'},
  350:                                {col1 => 'Self-creation with e-mail verification',
  351:                                 col2 => 'Settings'}],
  352:                     print => \&print_selfcreation,
  353:                     modify => \&modify_selfcreation,
  354:                   },
  355:         'usermodification' =>
  356:                   { text => 'User modification',
  357:                     help => 'Domain_Configuration_User_Modification',
  358:                     header => [{col1 => 'Target user has role',
  359:                                 col2 => 'User information updatable in author context'},
  360:                                {col1 => 'Target user has role',
  361:                                 col2 => 'User information updatable in course context'}],
  362:                     print => \&print_usermodification,
  363:                     modify => \&modify_usermodification,
  364:                   },
  365:         'scantron' =>
  366:                   { text => 'Bubblesheet format file',
  367:                     help => 'Domain_Configuration_Scantron_Format',
  368:                     header => [ {col1 => 'Item',
  369:                                  col2 => '',
  370:                               }],
  371:                     print => \&print_scantron,
  372:                     modify => \&modify_scantron,
  373:                   },
  374:         'requestcourses' => 
  375:                  {text => 'Request creation of courses',
  376:                   help => 'Domain_Configuration_Request_Courses',
  377:                   header => [{col1 => 'User affiliation',
  378:                               col2 => 'Availability/Processing of requests',},
  379:                              {col1 => 'Setting',
  380:                               col2 => 'Value'},
  381:                              {col1 => 'Available textbooks',
  382:                               col2 => ''},
  383:                              {col1 => 'Available templates',
  384:                               col2 => ''},
  385:                              {col1 => 'Validation (not official courses)',
  386:                               col2 => 'Value'},],
  387:                   print => \&print_quotas,
  388:                   modify => \&modify_quotas,
  389:                  },
  390:         'requestauthor' =>
  391:                  {text => 'Request Authoring Space',
  392:                   help => 'Domain_Configuration_Request_Author',
  393:                   header => [{col1 => 'User affiliation',
  394:                               col2 => 'Availability/Processing of requests',},
  395:                              {col1 => 'Setting',
  396:                               col2 => 'Value'}],
  397:                   print => \&print_quotas,
  398:                   modify => \&modify_quotas,
  399:                  },
  400:         'coursecategories' =>
  401:                   { text => 'Cataloging of courses/communities',
  402:                     help => 'Domain_Configuration_Cataloging_Courses',
  403:                     header => [{col1 => 'Catalog type/availability',
  404:                                 col2 => '',},
  405:                                {col1 => 'Category settings for standard catalog',
  406:                                 col2 => '',},
  407:                                {col1 => 'Categories',
  408:                                 col2 => '',
  409:                                }],
  410:                     print => \&print_coursecategories,
  411:                     modify => \&modify_coursecategories,
  412:                   },
  413:         'serverstatuses' =>
  414:                  {text   => 'Access to server status pages',
  415:                   help   => 'Domain_Configuration_Server_Status',
  416:                   header => [{col1 => 'Status Page',
  417:                               col2 => 'Other named users',
  418:                               col3 => 'Specific IPs',
  419:                             }],
  420:                   print => \&print_serverstatuses,
  421:                   modify => \&modify_serverstatuses,
  422:                  },
  423:         'helpsettings' =>
  424:                  {text   => 'Support settings',
  425:                   help   => 'Domain_Configuration_Help_Settings',
  426:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  427:                               col2 => 'Value'},
  428:                              {col1 => 'Helpdesk Roles',
  429:                               col2 => 'Settings'},],
  430:                   print  => \&print_helpsettings,
  431:                   modify => \&modify_helpsettings,
  432:                  },
  433:         'coursedefaults' => 
  434:                  {text => 'Course/Community defaults',
  435:                   help => 'Domain_Configuration_Course_Defaults',
  436:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  437:                               col2 => 'Value',},
  438:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  439:                               col2 => 'Value',},],
  440:                   print => \&print_coursedefaults,
  441:                   modify => \&modify_coursedefaults,
  442:                  },
  443:         'selfenrollment' => 
  444:                  {text   => 'Self-enrollment in Course/Community',
  445:                   help   => 'Domain_Configuration_Selfenrollment',
  446:                   header => [{col1 => 'Configuration Rights',
  447:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  448:                              {col1 => 'Defaults',
  449:                               col2 => 'Value'},
  450:                              {col1 => 'Self-enrollment validation (optional)',
  451:                               col2 => 'Value'},],
  452:                   print => \&print_selfenrollment,
  453:                   modify => \&modify_selfenrollment,
  454:                  },
  455:         'usersessions' =>
  456:                  {text  => 'User session hosting/offloading',
  457:                   help  => 'Domain_Configuration_User_Sessions',
  458:                   header => [{col1 => 'Domain server',
  459:                               col2 => 'Servers to offload sessions to when busy'},
  460:                              {col1 => 'Hosting of users from other domains',
  461:                               col2 => 'Rules'},
  462:                              {col1 => "Hosting domain's own users elsewhere",
  463:                               col2 => 'Rules'}],
  464:                   print => \&print_usersessions,
  465:                   modify => \&modify_usersessions,
  466:                  },
  467:         'loadbalancing' =>
  468:                  {text  => 'Dedicated Load Balancer(s)',
  469:                   help  => 'Domain_Configuration_Load_Balancing',
  470:                   header => [{col1 => 'Balancers',
  471:                               col2 => 'Default destinations',
  472:                               col3 => 'User affiliation',
  473:                               col4 => 'Overrides'},
  474:                             ],
  475:                   print => \&print_loadbalancing,
  476:                   modify => \&modify_loadbalancing,
  477:                  },
  478:     );
  479:     if (keys(%servers) > 1) {
  480:         $prefs{'login'}  = { text   => 'Log-in page options',
  481:                              help   => 'Domain_Configuration_Login_Page',
  482:                             header => [{col1 => 'Log-in Service',
  483:                                         col2 => 'Server Setting',},
  484:                                        {col1 => 'Log-in Page Items',
  485:                                         col2 => ''},
  486:                                        {col1 => 'Log-in Help',
  487:                                         col2 => 'Value'},
  488:                                        {col1 => 'Custom HTML in document head',
  489:                                         col2 => 'Value'}],
  490:                             print => \&print_login,
  491:                             modify => \&modify_login,
  492:                            };
  493:     }
  494: 
  495:     my @roles = ('student','coordinator','author','admin');
  496:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  497:     &Apache::lonhtmlcommon::add_breadcrumb
  498:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  499:       text=>"Settings to display/modify"});
  500:     my $confname = $dom.'-domainconfig';
  501: 
  502:     if ($phase eq 'process') {
  503:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  504:                                                               \%prefs,\%domconfig,$confname,\@roles);
  505:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  506:             $r->rflush();
  507:             &devalidate_remote_domconfs($dom,$result);
  508:         }
  509:     } elsif ($phase eq 'display') {
  510:         my $js = &recaptcha_js().
  511:                  &toggle_display_js();
  512:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  513:             my ($othertitle,$usertypes,$types) =
  514:                 &Apache::loncommon::sorted_inst_types($dom);
  515:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  516:                                           $domconfig{'loadbalancing'}).
  517:                    &new_spares_js().
  518:                    &common_domprefs_js().
  519:                    &Apache::loncommon::javascript_array_indexof();
  520:         }
  521:         if (grep(/^requestcourses$/,@actions)) {
  522:             my $javascript_validations;
  523:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  524:             $js .= <<END;
  525: <script type="text/javascript">
  526: $javascript_validations
  527: </script>
  528: $coursebrowserjs
  529: END
  530:         }
  531:         if (grep(/^selfcreation$/,@actions)) {
  532:             $js .= &selfcreate_javascript();
  533:         }
  534:         if (grep(/^contacts$/,@actions)) {
  535:             $js .= &contacts_javascript();
  536:         }
  537:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  538:     } else {
  539: # check if domconfig user exists for the domain.
  540:         my $servadm = $r->dir_config('lonAdmEMail');
  541:         my ($configuserok,$author_ok,$switchserver) =
  542:             &config_check($dom,$confname,$servadm);
  543:         unless ($configuserok eq 'ok') {
  544:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  545:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  546:                           $confname).
  547:                       '<br />'
  548:             );
  549:             if ($switchserver) {
  550:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  551:                           '<br />'.
  552:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  553:                           '<br />'.
  554:                           &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).
  555:                           '<br />'.
  556:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  557:                 );
  558:             } else {
  559:                 $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.').
  560:                           '<br />'.
  561:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  562:                 );
  563:             }
  564:             $r->print(&Apache::loncommon::end_page());
  565:             return OK;
  566:         }
  567:         if (keys(%domconfig) == 0) {
  568:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  569:             my @ids=&Apache::lonnet::current_machine_ids();
  570:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  571:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  572:                 my @loginimages = ('img','logo','domlogo','login');
  573:                 my $custom_img_count = 0;
  574:                 foreach my $img (@loginimages) {
  575:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  576:                         $custom_img_count ++;
  577:                     }
  578:                 }
  579:                 foreach my $role (@roles) {
  580:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  581:                         $custom_img_count ++;
  582:                     }
  583:                 }
  584:                 if ($custom_img_count > 0) {
  585:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  586:                     my $switch_server = &check_switchserver($dom,$confname);
  587:                     $r->print(
  588:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  589:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  590:     &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 />'.
  591:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  592:                     if ($switch_server) {
  593:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  594:                     }
  595:                     $r->print(&Apache::loncommon::end_page());
  596:                     return OK;
  597:                 }
  598:             }
  599:         }
  600:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  601:     }
  602:     return OK;
  603: }
  604: 
  605: sub process_changes {
  606:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  607:     my %domconfig;
  608:     if (ref($values) eq 'HASH') {
  609:         %domconfig = %{$values};
  610:     }
  611:     my $output;
  612:     if ($action eq 'login') {
  613:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  614:     } elsif ($action eq 'rolecolors') {
  615:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  616:                                      $lastactref,%domconfig);
  617:     } elsif ($action eq 'quotas') {
  618:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  619:     } elsif ($action eq 'autoenroll') {
  620:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  621:     } elsif ($action eq 'autoupdate') {
  622:         $output = &modify_autoupdate($dom,%domconfig);
  623:     } elsif ($action eq 'autocreate') {
  624:         $output = &modify_autocreate($dom,%domconfig);
  625:     } elsif ($action eq 'directorysrch') {
  626:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  627:     } elsif ($action eq 'usercreation') {
  628:         $output = &modify_usercreation($dom,%domconfig);
  629:     } elsif ($action eq 'selfcreation') {
  630:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  631:     } elsif ($action eq 'usermodification') {
  632:         $output = &modify_usermodification($dom,%domconfig);
  633:     } elsif ($action eq 'contacts') {
  634:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  635:     } elsif ($action eq 'defaults') {
  636:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  637:     } elsif ($action eq 'scantron') {
  638:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  639:     } elsif ($action eq 'coursecategories') {
  640:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  641:     } elsif ($action eq 'serverstatuses') {
  642:         $output = &modify_serverstatuses($dom,%domconfig);
  643:     } elsif ($action eq 'requestcourses') {
  644:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  645:     } elsif ($action eq 'requestauthor') {
  646:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  647:     } elsif ($action eq 'helpsettings') {
  648:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  649:     } elsif ($action eq 'coursedefaults') {
  650:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  651:     } elsif ($action eq 'selfenrollment') {
  652:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  653:     } elsif ($action eq 'usersessions') {
  654:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  655:     } elsif ($action eq 'loadbalancing') {
  656:         $output = &modify_loadbalancing($dom,%domconfig);
  657:     }
  658:     return $output;
  659: }
  660: 
  661: sub print_config_box {
  662:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  663:     my $rowtotal = 0;
  664:     my $output;
  665:     if ($action eq 'coursecategories') {
  666:         $output = &coursecategories_javascript($settings);
  667:     } elsif ($action eq 'defaults') {
  668:         $output = &defaults_javascript($settings); 
  669:     } elsif ($action eq 'helpsettings') {
  670:         my (%privs,%levelscurrent);
  671:         my %full=();
  672:         my %levels=(
  673:                      course => {},
  674:                      domain => {},
  675:                      system => {},
  676:                    );
  677:         my $context = 'domain';
  678:         my $crstype = 'Course';
  679:         my $formname = 'display';
  680:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  681:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  682:         $output =
  683:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full,
  684:                                                       \@templateroles);
  685:     }
  686:     $output .=
  687:          '<table class="LC_nested_outer">
  688:           <tr>
  689:            <th align="left" valign="middle"><span class="LC_nobreak">'.
  690:            &mt($item->{text}).'&nbsp;'.
  691:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  692:           '</tr>';
  693:     $rowtotal ++;
  694:     my $numheaders = 1;
  695:     if (ref($item->{'header'}) eq 'ARRAY') {
  696:         $numheaders = scalar(@{$item->{'header'}});
  697:     }
  698:     if ($numheaders > 1) {
  699:         my $colspan = '';
  700:         my $rightcolspan = '';
  701:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  702:             ($action eq 'directorysrch') ||
  703:             (($action eq 'login') && ($numheaders < 4))) {
  704:             $colspan = ' colspan="2"';
  705:         }
  706:         if ($action eq 'usersessions') {
  707:             $rightcolspan = ' colspan="3"'; 
  708:         }
  709:         $output .= '
  710:           <tr>
  711:            <td>
  712:             <table class="LC_nested">
  713:              <tr class="LC_info_row">
  714:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  715:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  716:              </tr>';
  717:         $rowtotal ++;
  718:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  719:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  720:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'directorysrch') ||
  721:             ($action eq 'helpsettings') || ($action eq 'contacts')) {
  722:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  723:         } elsif ($action eq 'coursecategories') {
  724:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  725:         } elsif ($action eq 'login') {
  726:             if ($numheaders == 4) {
  727:                 $colspan = ' colspan="2"';
  728:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  729:             } else {
  730:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  731:             }
  732:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  733:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  734:         } elsif ($action eq 'rolecolors') {
  735:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  736:         }
  737:         $output .= '
  738:            </table>
  739:           </td>
  740:          </tr>
  741:          <tr>
  742:            <td>
  743:             <table class="LC_nested">
  744:              <tr class="LC_info_row">
  745:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  746:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  747:              </tr>';
  748:             $rowtotal ++;
  749:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  750:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  751:             ($action eq 'usersessions') || ($action eq 'coursecategories') ||
  752:             ($action eq 'contacts') || ($action eq 'defaults')) {
  753:             if ($action eq 'coursecategories') {
  754:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  755:                 $colspan = ' colspan="2"';
  756:             } else {
  757:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  758:             }
  759:             $output .= '
  760:            </table>
  761:           </td>
  762:          </tr>
  763:          <tr>
  764:            <td>
  765:             <table class="LC_nested">
  766:              <tr class="LC_info_row">
  767:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  768:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  769:              </tr>'."\n";
  770:             if ($action eq 'coursecategories') {
  771:                 $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
  772:             } else {
  773:                 $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  774:             }
  775:             $rowtotal ++;
  776:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
  777:                  ($action eq 'defaults') || ($action eq 'directorysrch') ||
  778:                  ($action eq 'helpsettings')) {
  779:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  780:         } elsif ($action eq 'login') {
  781:             if ($numheaders == 4) {
  782:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
  783:            </table>
  784:           </td>
  785:          </tr>
  786:          <tr>
  787:            <td>
  788:             <table class="LC_nested">
  789:              <tr class="LC_info_row">
  790:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  791:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
  792:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  793:                 $rowtotal ++;
  794:             } else {
  795:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  796:             }
  797:             $output .= '
  798:            </table>
  799:           </td>
  800:          </tr>
  801:          <tr>
  802:            <td>
  803:             <table class="LC_nested">
  804:              <tr class="LC_info_row">';
  805:             if ($numheaders == 4) {
  806:                 $output .= '
  807:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  808:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  809:              </tr>';
  810:             } else {
  811:                 $output .= '
  812:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  813:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  814:              </tr>';
  815:             }
  816:             $rowtotal ++;
  817:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal);
  818:         } elsif ($action eq 'requestcourses') {
  819:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
  820:             $rowtotal ++;
  821:             $output .= &print_studentcode($settings,\$rowtotal).'
  822:            </table>
  823:           </td>
  824:          </tr>
  825:          <tr>
  826:            <td>
  827:             <table class="LC_nested">
  828:              <tr class="LC_info_row">
  829:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  830:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
  831:                        &textbookcourses_javascript($settings).
  832:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
  833:             </table>
  834:            </td>
  835:           </tr>
  836:          <tr>
  837:            <td>
  838:             <table class="LC_nested">
  839:              <tr class="LC_info_row">
  840:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  841:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
  842:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
  843:             </table>
  844:            </td>
  845:           </tr>
  846:           <tr>
  847:            <td>
  848:             <table class="LC_nested">
  849:              <tr class="LC_info_row">
  850:               <td class="LC_left_item"'.$colspan.' valign="top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
  851:               <td class="LC_right_item" valign="top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
  852:              </tr>'.
  853:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
  854:         } elsif ($action eq 'requestauthor') {
  855:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
  856:             $rowtotal ++;
  857:         } elsif ($action eq 'rolecolors') {
  858:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
  859:            </table>
  860:           </td>
  861:          </tr>
  862:          <tr>
  863:            <td>
  864:             <table class="LC_nested">
  865:              <tr class="LC_info_row">
  866:               <td class="LC_left_item"'.$colspan.' valign="top">'.
  867:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
  868:               <td class="LC_right_item" valign="top">'.
  869:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
  870:              </tr>'.
  871:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
  872:            </table>
  873:           </td>
  874:          </tr>
  875:          <tr>
  876:            <td>
  877:             <table class="LC_nested">
  878:              <tr class="LC_info_row">
  879:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  880:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  881:              </tr>'.
  882:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
  883:             $rowtotal += 2;
  884:         }
  885:     } else {
  886:         $output .= '
  887:           <tr>
  888:            <td>
  889:             <table class="LC_nested">
  890:              <tr class="LC_info_row">';
  891:         if ($action eq 'login') {
  892:             $output .= '  
  893:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
  894:         } elsif ($action eq 'serverstatuses') {
  895:             $output .= '
  896:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).
  897:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
  898: 
  899:         } else {
  900:             $output .= '
  901:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
  902:         }
  903:         if (defined($item->{'header'}->[0]->{'col3'})) {
  904:             $output .= '<td class="LC_left_item" valign="top">'.
  905:                        &mt($item->{'header'}->[0]->{'col2'});
  906:             if ($action eq 'serverstatuses') {
  907:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
  908:             } 
  909:         } else {
  910:             $output .= '<td class="LC_right_item" valign="top">'.
  911:                        &mt($item->{'header'}->[0]->{'col2'});
  912:         }
  913:         $output .= '</td>';
  914:         if ($item->{'header'}->[0]->{'col3'}) {
  915:             if (defined($item->{'header'}->[0]->{'col4'})) {
  916:                 $output .= '<td class="LC_left_item" valign="top">'.
  917:                             &mt($item->{'header'}->[0]->{'col3'});
  918:             } else {
  919:                 $output .= '<td class="LC_right_item" valign="top">'.
  920:                            &mt($item->{'header'}->[0]->{'col3'});
  921:             }
  922:             if ($action eq 'serverstatuses') {
  923:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
  924:             }
  925:             $output .= '</td>';
  926:         }
  927:         if ($item->{'header'}->[0]->{'col4'}) {
  928:             $output .= '<td class="LC_right_item" valign="top">'.
  929:                        &mt($item->{'header'}->[0]->{'col4'});
  930:         }
  931:         $output .= '</tr>';
  932:         $rowtotal ++;
  933:         if ($action eq 'quotas') {
  934:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  935:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
  936:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing')) {
  937:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
  938:         } elsif ($action eq 'scantron') {
  939:             $output .= &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
  940:         }
  941:     }
  942:     $output .= '
  943:    </table>
  944:   </td>
  945:  </tr>
  946: </table><br />';
  947:     return ($output,$rowtotal);
  948: }
  949: 
  950: sub print_login {
  951:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
  952:     my ($css_class,$datatable);
  953:     my %choices = &login_choices();
  954: 
  955:     if ($caller eq 'service') {
  956:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
  957:         my $choice = $choices{'disallowlogin'};
  958:         $css_class = ' class="LC_odd_row"';
  959:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
  960:                       '<td align="right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
  961:                       '<th>'.$choices{'server'}.'</th>'.
  962:                       '<th>'.$choices{'serverpath'}.'</th>'.
  963:                       '<th>'.$choices{'custompath'}.'</th>'.
  964:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
  965:         my %disallowed;
  966:         if (ref($settings) eq 'HASH') {
  967:             if (ref($settings->{'loginvia'}) eq 'HASH') {
  968:                %disallowed = %{$settings->{'loginvia'}};
  969:             }
  970:         }
  971:         foreach my $lonhost (sort(keys(%servers))) {
  972:             my $direct = 'selected="selected"';
  973:             if (ref($disallowed{$lonhost}) eq 'HASH') {
  974:                 if ($disallowed{$lonhost}{'server'} ne '') {
  975:                     $direct = '';
  976:                 }
  977:             }
  978:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
  979:                           '<td><select name="'.$lonhost.'_server">'.
  980:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
  981:                           '</option>';
  982:             foreach my $hostid (sort(keys(%servers))) {
  983:                 next if ($servers{$hostid} eq $servers{$lonhost});
  984:                 my $selected = '';
  985:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
  986:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
  987:                         $selected = 'selected="selected"';
  988:                     }
  989:                 }
  990:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
  991:                               $servers{$hostid}.'</option>';
  992:             }
  993:             $datatable .= '</select></td>'.
  994:                           '<td><select name="'.$lonhost.'_serverpath">';
  995:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
  996:                 my $pathname = $path;
  997:                 if ($path eq 'custom') {
  998:                     $pathname = &mt('Custom Path').' ->';
  999:                 }
 1000:                 my $selected = '';
 1001:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1002:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1003:                         $selected = 'selected="selected"';
 1004:                     }
 1005:                 } elsif ($path eq '') {
 1006:                     $selected = 'selected="selected"';
 1007:                 }
 1008:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1009:             }
 1010:             $datatable .= '</select></td>';
 1011:             my ($custom,$exempt);
 1012:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1013:                 $custom = $disallowed{$lonhost}{'custompath'};
 1014:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1015:             }
 1016:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1017:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1018:                           '</tr>';
 1019:         }
 1020:         $datatable .= '</table></td></tr>';
 1021:         return $datatable;
 1022:     } elsif ($caller eq 'page') {
 1023:         my %defaultchecked = ( 
 1024:                                'coursecatalog' => 'on',
 1025:                                'helpdesk'      => 'on',
 1026:                                'adminmail'     => 'off',
 1027:                                'newuser'       => 'off',
 1028:                              );
 1029:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1030:         my (%checkedon,%checkedoff);
 1031:         foreach my $item (@toggles) {
 1032:             if ($defaultchecked{$item} eq 'on') { 
 1033:                 $checkedon{$item} = ' checked="checked" ';
 1034:                 $checkedoff{$item} = ' ';
 1035:             } elsif ($defaultchecked{$item} eq 'off') {
 1036:                 $checkedoff{$item} = ' checked="checked" ';
 1037:                 $checkedon{$item} = ' ';
 1038:             }
 1039:         }
 1040:         my @images = ('img','logo','domlogo','login');
 1041:         my @logintext = ('textcol','bgcol');
 1042:         my @bgs = ('pgbg','mainbg','sidebg');
 1043:         my @links = ('link','alink','vlink');
 1044:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1045:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1046:         my (%is_custom,%designs);
 1047:         my %defaults = (
 1048:                        font => $defaultdesign{'login.font'},
 1049:                        );
 1050:         foreach my $item (@images) {
 1051:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1052:             $defaults{'showlogo'}{$item} = 1;
 1053:         }
 1054:         foreach my $item (@bgs) {
 1055:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1056:         }
 1057:         foreach my $item (@logintext) {
 1058:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1059:         }
 1060:         foreach my $item (@links) {
 1061:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1062:         }
 1063:         if (ref($settings) eq 'HASH') {
 1064:             foreach my $item (@toggles) {
 1065:                 if ($settings->{$item} eq '1') {
 1066:                     $checkedon{$item} =  ' checked="checked" ';
 1067:                     $checkedoff{$item} = ' ';
 1068:                 } elsif ($settings->{$item} eq '0') {
 1069:                     $checkedoff{$item} =  ' checked="checked" ';
 1070:                     $checkedon{$item} = ' ';
 1071:                 }
 1072:             }
 1073:             foreach my $item (@images) {
 1074:                 if (defined($settings->{$item})) {
 1075:                     $designs{$item} = $settings->{$item};
 1076:                     $is_custom{$item} = 1;
 1077:                 }
 1078:                 if (defined($settings->{'showlogo'}{$item})) {
 1079:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1080:                 }
 1081:             }
 1082:             foreach my $item (@logintext) {
 1083:                 if ($settings->{$item} ne '') {
 1084:                     $designs{'logintext'}{$item} = $settings->{$item};
 1085:                     $is_custom{$item} = 1;
 1086:                 }
 1087:             }
 1088:             if ($settings->{'font'} ne '') {
 1089:                 $designs{'font'} = $settings->{'font'};
 1090:                 $is_custom{'font'} = 1;
 1091:             }
 1092:             foreach my $item (@bgs) {
 1093:                 if ($settings->{$item} ne '') {
 1094:                     $designs{'bgs'}{$item} = $settings->{$item};
 1095:                     $is_custom{$item} = 1;
 1096:                 }
 1097:             }
 1098:             foreach my $item (@links) {
 1099:                 if ($settings->{$item} ne '') {
 1100:                     $designs{'links'}{$item} = $settings->{$item};
 1101:                     $is_custom{$item} = 1;
 1102:                 }
 1103:             }
 1104:         } else {
 1105:             if ($designhash{$dom.'.login.font'} ne '') {
 1106:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1107:                 $is_custom{'font'} = 1;
 1108:             }
 1109:             foreach my $item (@images) {
 1110:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1111:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1112:                     $is_custom{$item} = 1;
 1113:                 }
 1114:             }
 1115:             foreach my $item (@bgs) {
 1116:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1117:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1118:                     $is_custom{$item} = 1;
 1119:                 }
 1120:             }
 1121:             foreach my $item (@links) {
 1122:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1123:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1124:                     $is_custom{$item} = 1;
 1125:                 }
 1126:             }
 1127:         }
 1128:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1129:                                                       logo => 'Institution Logo',
 1130:                                                       domlogo => 'Domain Logo',
 1131:                                                       login => 'Login box');
 1132:         my $itemcount = 1;
 1133:         foreach my $item (@toggles) {
 1134:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1135:             $datatable .=  
 1136:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1137:                 '</td><td>'.
 1138:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1139:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1140:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1141:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1142:                 '</tr>';
 1143:             $itemcount ++;
 1144:         }
 1145:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1146:         $datatable .= '</tr></table></td></tr>';
 1147:     } elsif ($caller eq 'help') {
 1148:         my ($defaulturl,$defaulttype,%url,%type,%lt,%langchoices);
 1149:         my $switchserver = &check_switchserver($dom,$confname);
 1150:         my $itemcount = 1;
 1151:         $defaulturl = '/adm/loginproblems.html';
 1152:         $defaulttype = 'default';
 1153:         %lt = &Apache::lonlocal::texthash (
 1154:                      del     => 'Delete?',
 1155:                      rep     => 'Replace:',
 1156:                      upl     => 'Upload:',
 1157:                      default => 'Default',
 1158:                      custom  => 'Custom',
 1159:                                              );
 1160:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1161:         my @currlangs;
 1162:         if (ref($settings) eq 'HASH') {
 1163:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1164:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1165:                     next if ($settings->{'helpurl'}{$key} eq '');
 1166:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1167:                     $type{$key} = 'custom';
 1168:                     unless ($key eq 'nolang') {
 1169:                         push(@currlangs,$key);
 1170:                     }
 1171:                 }
 1172:             } elsif ($settings->{'helpurl'} ne '') {
 1173:                 $type{'nolang'} = 'custom';
 1174:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1175:             }
 1176:         }
 1177:         foreach my $lang ('nolang',sort(@currlangs)) {
 1178:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1179:             $datatable .= '<tr'.$css_class.'>';
 1180:             if ($url{$lang} eq '') {
 1181:                 $url{$lang} = $defaulturl;
 1182:             }
 1183:             if ($type{$lang} eq '') {
 1184:                 $type{$lang} = $defaulttype;
 1185:             }
 1186:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1187:             if ($lang eq 'nolang') {
 1188:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1189:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1190:             } else {
 1191:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1192:                                   $langchoices{$lang},
 1193:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1194:             }
 1195:             $datatable .= '</span></td>'."\n".
 1196:                           '<td class="LC_left_item">';
 1197:             if ($type{$lang} eq 'custom') {
 1198:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1199:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1200:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1201:             } else {
 1202:                 $datatable .= $lt{'upl'};
 1203:             }
 1204:             $datatable .='<br />';
 1205:             if ($switchserver) {
 1206:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1207:             } else {
 1208:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1209:             }
 1210:             $datatable .= '</td></tr>';
 1211:             $itemcount ++;
 1212:         }
 1213:         my @addlangs;
 1214:         foreach my $lang (sort(keys(%langchoices))) {
 1215:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1216:             push(@addlangs,$lang);
 1217:         }
 1218:         if (@addlangs > 0) {
 1219:             my %toadd;
 1220:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1221:             $toadd{''} = &mt('Select');
 1222:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1223:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1224:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1225:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1226:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1227:             if ($switchserver) {
 1228:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1229:             } else {
 1230:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1231:             }
 1232:             $datatable .= '</td></tr>';
 1233:             $itemcount ++;
 1234:         }
 1235:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1236:     } elsif ($caller eq 'headtag') {
 1237:         my %domservers = &Apache::lonnet::get_servers($dom);
 1238:         my $choice = $choices{'headtag'};
 1239:         $css_class = ' class="LC_odd_row"';
 1240:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1241:                       '<td align="left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1242:                       '<th>'.$choices{'current'}.'</th>'.
 1243:                       '<th>'.$choices{'action'}.'</th>'.
 1244:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1245:         my (%currurls,%currexempt);
 1246:         if (ref($settings) eq 'HASH') {
 1247:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1248:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1249:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1250:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1251:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1252:                     }
 1253:                 }
 1254:             }
 1255:         }
 1256:         my %lt = &Apache::lonlocal::texthash(
 1257:                                                del  => 'Delete?',
 1258:                                                rep  => 'Replace:',
 1259:                                                upl  => 'Upload:',
 1260:                                                curr => 'View contents',
 1261:                                                none => 'None',
 1262:         );
 1263:         my $switchserver = &check_switchserver($dom,$confname);
 1264:         foreach my $lonhost (sort(keys(%domservers))) {
 1265:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1266:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1267:             if ($currurls{$lonhost}) {
 1268:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1269:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1270:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1271:                               '">'.$lt{'curr'}.'</a></td>'.
 1272:                               '<td><span class="LC_nobreak"><label>'.
 1273:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1274:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1275:             } else {
 1276:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1277:             }
 1278:             $datatable .='<br />';
 1279:             if ($switchserver) {
 1280:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1281:             } else {
 1282:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1283:             }
 1284:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1285:         }
 1286:         $datatable .= '</table></td></tr>';
 1287:     }
 1288:     return $datatable;
 1289: }
 1290: 
 1291: sub login_choices {
 1292:     my %choices =
 1293:         &Apache::lonlocal::texthash (
 1294:             coursecatalog => 'Display Course/Community Catalog link?',
 1295:             adminmail     => "Display Administrator's E-mail Address?",
 1296:             helpdesk      => 'Display "Contact Helpdesk" link',
 1297:             disallowlogin => "Login page requests redirected",
 1298:             hostid        => "Server",
 1299:             server        => "Redirect to:",
 1300:             serverpath    => "Path",
 1301:             custompath    => "Custom", 
 1302:             exempt        => "Exempt IP(s)",
 1303:             directlogin   => "No redirect",
 1304:             newuser       => "Link to create a user account",
 1305:             img           => "Header",
 1306:             logo          => "Main Logo",
 1307:             domlogo       => "Domain Logo",
 1308:             login         => "Log-in Header", 
 1309:             textcol       => "Text color",
 1310:             bgcol         => "Box color",
 1311:             bgs           => "Background colors",
 1312:             links         => "Link colors",
 1313:             font          => "Font color",
 1314:             pgbg          => "Header",
 1315:             mainbg        => "Page",
 1316:             sidebg        => "Login box",
 1317:             link          => "Link",
 1318:             alink         => "Active link",
 1319:             vlink         => "Visited link",
 1320:             headtag       => "Custom markup",
 1321:             action        => "Action",
 1322:             current       => "Current",
 1323:         );
 1324:     return %choices;
 1325: }
 1326: 
 1327: sub print_rolecolors {
 1328:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1329:     my %choices = &color_font_choices();
 1330:     my @bgs = ('pgbg','tabbg','sidebg');
 1331:     my @links = ('link','alink','vlink');
 1332:     my @images = ('img');
 1333:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1334:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1335:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1336:     my (%is_custom,%designs);
 1337:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1338:     if (ref($settings) eq 'HASH') {
 1339:         if (ref($settings->{$role}) eq 'HASH') {
 1340:             if ($settings->{$role}->{'img'} ne '') {
 1341:                 $designs{'img'} = $settings->{$role}->{'img'};
 1342:                 $is_custom{'img'} = 1;
 1343:             }
 1344:             if ($settings->{$role}->{'font'} ne '') {
 1345:                 $designs{'font'} = $settings->{$role}->{'font'};
 1346:                 $is_custom{'font'} = 1;
 1347:             }
 1348:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1349:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1350:                 $is_custom{'fontmenu'} = 1;
 1351:             }
 1352:             foreach my $item (@bgs) {
 1353:                 if ($settings->{$role}->{$item} ne '') {
 1354:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1355:                     $is_custom{$item} = 1;
 1356:                 }
 1357:             }
 1358:             foreach my $item (@links) {
 1359:                 if ($settings->{$role}->{$item} ne '') {
 1360:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1361:                     $is_custom{$item} = 1;
 1362:                 }
 1363:             }
 1364:         }
 1365:     } else {
 1366:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1367:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1368:             $is_custom{'img'} = 1;
 1369:         }
 1370:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1371:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1372:             $is_custom{'fontmenu'} = 1; 
 1373:         }
 1374:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1375:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1376:             $is_custom{'font'} = 1;
 1377:         }
 1378:         foreach my $item (@bgs) {
 1379:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1380:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1381:                 $is_custom{$item} = 1;
 1382:             
 1383:             }
 1384:         }
 1385:         foreach my $item (@links) {
 1386:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1387:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1388:                 $is_custom{$item} = 1;
 1389:             }
 1390:         }
 1391:     }
 1392:     my $itemcount = 1;
 1393:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 1394:     $datatable .= '</tr></table></td></tr>';
 1395:     return $datatable;
 1396: }
 1397: 
 1398: sub role_defaults {
 1399:     my ($role,$bgs,$links,$images,$logintext) = @_;
 1400:     my %defaults;
 1401:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 1402:         return %defaults;
 1403:     }
 1404:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1405:     if ($role eq 'login') {
 1406:         %defaults = (
 1407:                        font => $defaultdesign{$role.'.font'},
 1408:                     );
 1409:         if (ref($logintext) eq 'ARRAY') {
 1410:             foreach my $item (@{$logintext}) {
 1411:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 1412:             }
 1413:         }
 1414:         foreach my $item (@{$images}) {
 1415:             $defaults{'showlogo'}{$item} = 1;
 1416:         }
 1417:     } else {
 1418:         %defaults = (
 1419:                        img => $defaultdesign{$role.'.img'},
 1420:                        font => $defaultdesign{$role.'.font'},
 1421:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 1422:                     );
 1423:     }
 1424:     foreach my $item (@{$bgs}) {
 1425:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 1426:     }
 1427:     foreach my $item (@{$links}) {
 1428:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 1429:     }
 1430:     foreach my $item (@{$images}) {
 1431:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 1432:     }
 1433:     return %defaults;
 1434: }
 1435: 
 1436: sub display_color_options {
 1437:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 1438:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 1439:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1440:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1441:     my $datatable = '<tr'.$css_class.'>'.
 1442:         '<td>'.$choices->{'font'}.'</td>';
 1443:     if (!$is_custom->{'font'}) {
 1444:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 1445:     } else {
 1446:         $datatable .= '<td>&nbsp;</td>';
 1447:     }
 1448:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 1449: 
 1450:     $datatable .= '<td><span class="LC_nobreak">'.
 1451:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 1452:                   ' value="'.$current_color.'" />&nbsp;'.
 1453:                   '&nbsp;</span></td></tr>';
 1454:     unless ($role eq 'login') { 
 1455:         $datatable .= '<tr'.$css_class.'>'.
 1456:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 1457:         if (!$is_custom->{'fontmenu'}) {
 1458:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 1459:         } else {
 1460:             $datatable .= '<td>&nbsp;</td>';
 1461:         }
 1462: 	$current_color = $designs->{'fontmenu'} ?
 1463: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 1464:         $datatable .= '<td><span class="LC_nobreak">'.
 1465:                       '<input class="colorchooser" type="text" size="10" name="'
 1466: 		      .$role.'_fontmenu"'.
 1467:                       ' value="'.$current_color.'" />&nbsp;'.
 1468:                       '&nbsp;</span></td></tr>';
 1469:     }
 1470:     my $switchserver = &check_switchserver($dom,$confname);
 1471:     foreach my $img (@{$images}) {
 1472: 	$itemcount ++;
 1473:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1474:         $datatable .= '<tr'.$css_class.'>'.
 1475:                       '<td>'.$choices->{$img};
 1476:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors);
 1477:         if ($role eq 'login') {
 1478:             if ($img eq 'login') {
 1479:                 $login_hdr_pick =
 1480:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 1481:                 $logincolors =
 1482:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 1483:                                        $designs,$defaults);
 1484:             } elsif ($img ne 'domlogo') {
 1485:                 $datatable.= &logo_display_options($img,$defaults,$designs);
 1486:             }
 1487:         }
 1488:         $datatable .= '</td>';
 1489:         if ($designs->{$img} ne '') {
 1490:             $imgfile = $designs->{$img};
 1491: 	    $img_import = ($imgfile =~ m{^/adm/});
 1492:         } else {
 1493:             $imgfile = $defaults->{$img};
 1494:         }
 1495:         if ($imgfile) {
 1496:             my ($showfile,$fullsize);
 1497:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 1498:                 my $urldir = $1;
 1499:                 my $filename = $2;
 1500:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 1501:                 if (@info) {
 1502:                     my $thumbfile = 'tn-'.$filename;
 1503:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 1504:                     if (@thumb) {
 1505:                         $showfile = $urldir.'/'.$thumbfile;
 1506:                     } else {
 1507:                         $showfile = $imgfile;
 1508:                     }
 1509:                 } else {
 1510:                     $showfile = '';
 1511:                 }
 1512:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 1513:                 $showfile = $imgfile;
 1514:                 my $imgdir = $1;
 1515:                 my $filename = $2;
 1516:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 1517:                     $showfile = "/$imgdir/tn-".$filename;
 1518:                 } else {
 1519:                     my $input = $londocroot.$imgfile;
 1520:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 1521:                     if (!-e $output) {
 1522:                         my ($width,$height) = &thumb_dimensions();
 1523:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 1524:                         if ($fullwidth ne '' && $fullheight ne '') {
 1525:                             if ($fullwidth > $width && $fullheight > $height) { 
 1526:                                 my $size = $width.'x'.$height;
 1527:                                 my @args = ('convert','-sample',$size,$input,$output);
 1528:                                 system({$args[0]} @args);
 1529:                                 $showfile = "/$imgdir/tn-".$filename;
 1530:                             }
 1531:                         }
 1532:                     }
 1533:                 }
 1534:             }
 1535:             if ($showfile) {
 1536:                 if ($showfile =~ m{^/(adm|res)/}) {
 1537:                     if ($showfile =~ m{^/res/}) {
 1538:                         my $local_showfile =
 1539:                             &Apache::lonnet::filelocation('',$showfile);
 1540:                         &Apache::lonnet::repcopy($local_showfile);
 1541:                     }
 1542:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 1543:                 }
 1544:                 if ($imgfile) {
 1545:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 1546:                         if ($imgfile =~ m{^/res/}) {
 1547:                             my $local_imgfile =
 1548:                                 &Apache::lonnet::filelocation('',$imgfile);
 1549:                             &Apache::lonnet::repcopy($local_imgfile);
 1550:                         }
 1551:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 1552:                     } else {
 1553:                         $fullsize = $imgfile;
 1554:                     }
 1555:                 }
 1556:                 $datatable .= '<td>';
 1557:                 if ($img eq 'login') {
 1558:                     $datatable .= $login_hdr_pick;
 1559:                 } 
 1560:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 1561:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 1562:             } else {
 1563:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1564:                               &mt('Upload:').'<br />';
 1565:             }
 1566:         } else {
 1567:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1568:                           &mt('Upload:').'<br />';
 1569:         }
 1570:         if ($switchserver) {
 1571:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1572:         } else {
 1573:             if ($img ne 'login') { # suppress file selection for Log-in header
 1574:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 1575:             }
 1576:         }
 1577:         $datatable .= '</td></tr>';
 1578:     }
 1579:     $itemcount ++;
 1580:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1581:     $datatable .= '<tr'.$css_class.'>'.
 1582:                   '<td>'.$choices->{'bgs'}.'</td>';
 1583:     my $bgs_def;
 1584:     foreach my $item (@{$bgs}) {
 1585:         if (!$is_custom->{$item}) {
 1586:             $bgs_def .= '<td><span class="LC_nobreak">'.$choices->{$item}.'</span>&nbsp;<span class="css_default_'.$role.'_'.$item.'" style="background-color: '.$defaults->{'bgs'}{$item}.';">&nbsp;&nbsp;&nbsp;</span><br />'.$defaults->{'bgs'}{$item}.'</td>';
 1587:         }
 1588:     }
 1589:     if ($bgs_def) {
 1590:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 1591:     } else {
 1592:         $datatable .= '<td>&nbsp;</td>';
 1593:     }
 1594:     $datatable .= '<td class="LC_right_item">'.
 1595:                   '<table border="0"><tr>';
 1596: 
 1597:     foreach my $item (@{$bgs}) {
 1598:         $datatable .= '<td align="center">'.$choices->{$item};
 1599: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 1600:         if ($designs->{'bgs'}{$item}) {
 1601:             $datatable .= '&nbsp;';
 1602:         }
 1603:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 1604:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 1605:     }
 1606:     $datatable .= '</tr></table></td></tr>';
 1607:     $itemcount ++;
 1608:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1609:     $datatable .= '<tr'.$css_class.'>'.
 1610:                   '<td>'.$choices->{'links'}.'</td>';
 1611:     my $links_def;
 1612:     foreach my $item (@{$links}) {
 1613:         if (!$is_custom->{$item}) {
 1614:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 1615:         }
 1616:     }
 1617:     if ($links_def) {
 1618:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 1619:     } else {
 1620:         $datatable .= '<td>&nbsp;</td>';
 1621:     }
 1622:     $datatable .= '<td class="LC_right_item">'.
 1623:                   '<table border="0"><tr>';
 1624:     foreach my $item (@{$links}) {
 1625: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 1626:         $datatable .= '<td align="center">'.$choices->{$item}."\n";
 1627:         if ($designs->{'links'}{$item}) {
 1628:             $datatable.='&nbsp;';
 1629:         }
 1630:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 1631:                       '" /></td>';
 1632:     }
 1633:     $$rowtotal += $itemcount;
 1634:     return $datatable;
 1635: }
 1636: 
 1637: sub logo_display_options {
 1638:     my ($img,$defaults,$designs) = @_;
 1639:     my $checkedon;
 1640:     if (ref($defaults) eq 'HASH') {
 1641:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 1642:             if ($defaults->{'showlogo'}{$img}) {
 1643:                 $checkedon = 'checked="checked" ';     
 1644:             }
 1645:         } 
 1646:     }
 1647:     if (ref($designs) eq 'HASH') {
 1648:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 1649:             if (defined($designs->{'showlogo'}{$img})) {
 1650:                 if ($designs->{'showlogo'}{$img} == 0) {
 1651:                     $checkedon = '';
 1652:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 1653:                     $checkedon = 'checked="checked" ';
 1654:                 }
 1655:             }
 1656:         }
 1657:     }
 1658:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 1659:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 1660:            &mt('show').'</label>'."\n";
 1661: }
 1662: 
 1663: sub login_header_options  {
 1664:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 1665:     my $output = '';
 1666:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 1667:         $output .= &mt('Text default(s):').'<br />';
 1668:         if (!$is_custom->{'textcol'}) {
 1669:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 1670:                        '&nbsp;&nbsp;&nbsp;';
 1671:         }
 1672:         if (!$is_custom->{'bgcol'}) {
 1673:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 1674:                        '<span id="css_'.$role.'_font" style="background-color: '.
 1675:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 1676:         }
 1677:         $output .= '<br />';
 1678:     }
 1679:     $output .='<br />';
 1680:     return $output;
 1681: }
 1682: 
 1683: sub login_text_colors {
 1684:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 1685:     my $color_menu = '<table border="0"><tr>';
 1686:     foreach my $item (@{$logintext}) {
 1687:         $color_menu .= '<td align="center">'.$choices->{$item};
 1688:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 1689:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 1690:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 1691:     }
 1692:     $color_menu .= '</tr></table><br />';
 1693:     return $color_menu;
 1694: }
 1695: 
 1696: sub image_changes {
 1697:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 1698:     my $output;
 1699:     if ($img eq 'login') {
 1700:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 1701:     } elsif (!$is_custom) {
 1702:         if ($img ne 'domlogo') {
 1703:             $output = &mt('Default image:').'<br />';
 1704:         } else {
 1705:             $output = &mt('Default in use:').'<br />';
 1706:         }
 1707:     }
 1708:     if ($img ne 'login') {
 1709:         if ($img_import) {
 1710:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 1711:         }
 1712:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 1713:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 1714:         if ($is_custom) {
 1715:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 1716:                        '<input type="checkbox" name="'.
 1717:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 1718:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 1719:         } else {
 1720:             $output .= '<td valign="middle">'.$logincolors.&mt('Upload:').'<br />';
 1721:         }
 1722:     }
 1723:     return $output;
 1724: }
 1725: 
 1726: sub print_quotas {
 1727:     my ($dom,$settings,$rowtotal,$action) = @_;
 1728:     my $context;
 1729:     if ($action eq 'quotas') {
 1730:         $context = 'tools';
 1731:     } else {
 1732:         $context = $action;
 1733:     }
 1734:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 1735:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 1736:     my $typecount = 0;
 1737:     my ($css_class,%titles);
 1738:     if ($context eq 'requestcourses') {
 1739:         @usertools = ('official','unofficial','community','textbook');
 1740:         @options =('norequest','approval','validate','autolimit');
 1741:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 1742:         %titles = &courserequest_titles();
 1743:     } elsif ($context eq 'requestauthor') {
 1744:         @usertools = ('author');
 1745:         @options = ('norequest','approval','automatic');
 1746:         %titles = &authorrequest_titles();
 1747:     } else {
 1748:         @usertools = ('aboutme','blog','webdav','portfolio');
 1749:         %titles = &tool_titles();
 1750:     }
 1751:     if (ref($types) eq 'ARRAY') {
 1752:         foreach my $type (@{$types}) {
 1753:             my ($currdefquota,$currauthorquota);
 1754:             unless (($context eq 'requestcourses') ||
 1755:                     ($context eq 'requestauthor')) {
 1756:                 if (ref($settings) eq 'HASH') {
 1757:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 1758:                         $currdefquota = $settings->{defaultquota}->{$type};
 1759:                     } else {
 1760:                         $currdefquota = $settings->{$type};
 1761:                     }
 1762:                     if (ref($settings->{authorquota}) eq 'HASH') {
 1763:                         $currauthorquota = $settings->{authorquota}->{$type};
 1764:                     }
 1765:                 }
 1766:             }
 1767:             if (defined($usertypes->{$type})) {
 1768:                 $typecount ++;
 1769:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 1770:                 $datatable .= '<tr'.$css_class.'>'.
 1771:                               '<td>'.$usertypes->{$type}.'</td>'.
 1772:                               '<td class="LC_left_item">';
 1773:                 if ($context eq 'requestcourses') {
 1774:                     $datatable .= '<table><tr>';
 1775:                 }
 1776:                 my %cell;  
 1777:                 foreach my $item (@usertools) {
 1778:                     if ($context eq 'requestcourses') {
 1779:                         my ($curroption,$currlimit);
 1780:                         if (ref($settings) eq 'HASH') {
 1781:                             if (ref($settings->{$item}) eq 'HASH') {
 1782:                                 $curroption = $settings->{$item}->{$type};
 1783:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 1784:                                     $currlimit = $1; 
 1785:                                 }
 1786:                             }
 1787:                         }
 1788:                         if (!$curroption) {
 1789:                             $curroption = 'norequest';
 1790:                         }
 1791:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 1792:                         foreach my $option (@options) {
 1793:                             my $val = $option;
 1794:                             if ($option eq 'norequest') {
 1795:                                 $val = 0;  
 1796:                             }
 1797:                             if ($option eq 'validate') {
 1798:                                 my $canvalidate = 0;
 1799:                                 if (ref($validations{$item}) eq 'HASH') { 
 1800:                                     if ($validations{$item}{$type}) {
 1801:                                         $canvalidate = 1;
 1802:                                     }
 1803:                                 }
 1804:                                 next if (!$canvalidate);
 1805:                             }
 1806:                             my $checked = '';
 1807:                             if ($option eq $curroption) {
 1808:                                 $checked = ' checked="checked"';
 1809:                             } elsif ($option eq 'autolimit') {
 1810:                                 if ($curroption =~ /^autolimit/) {
 1811:                                     $checked = ' checked="checked"';
 1812:                                 }                       
 1813:                             } 
 1814:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 1815:                                   '<input type="radio" name="crsreq_'.$item.
 1816:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 1817:                                   $titles{$option}.'</label>';
 1818:                             if ($option eq 'autolimit') {
 1819:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 1820:                                                 $item.'_limit_'.$type.'" size="1" '.
 1821:                                                 'value="'.$currlimit.'" />';
 1822:                             }
 1823:                             $cell{$item} .= '</span> ';
 1824:                             if ($option eq 'autolimit') {
 1825:                                 $cell{$item} .= $titles{'unlimited'};
 1826:                             }
 1827:                         }
 1828:                     } elsif ($context eq 'requestauthor') {
 1829:                         my $curroption;
 1830:                         if (ref($settings) eq 'HASH') {
 1831:                             $curroption = $settings->{$type};
 1832:                         }
 1833:                         if (!$curroption) {
 1834:                             $curroption = 'norequest';
 1835:                         }
 1836:                         foreach my $option (@options) {
 1837:                             my $val = $option;
 1838:                             if ($option eq 'norequest') {
 1839:                                 $val = 0;
 1840:                             }
 1841:                             my $checked = '';
 1842:                             if ($option eq $curroption) {
 1843:                                 $checked = ' checked="checked"';
 1844:                             }
 1845:                             $datatable .= '<span class="LC_nobreak"><label>'.
 1846:                                   '<input type="radio" name="authorreq_'.$type.
 1847:                                   '" value="'.$val.'"'.$checked.' />'.
 1848:                                   $titles{$option}.'</label></span>&nbsp; ';
 1849:                         }
 1850:                     } else {
 1851:                         my $checked = 'checked="checked" ';
 1852:                         if (ref($settings) eq 'HASH') {
 1853:                             if (ref($settings->{$item}) eq 'HASH') {
 1854:                                 if ($settings->{$item}->{$type} == 0) {
 1855:                                     $checked = '';
 1856:                                 } elsif ($settings->{$item}->{$type} == 1) {
 1857:                                     $checked =  'checked="checked" ';
 1858:                                 }
 1859:                             }
 1860:                         }
 1861:                         $datatable .= '<span class="LC_nobreak"><label>'.
 1862:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 1863:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 1864:                                       '</label></span>&nbsp; ';
 1865:                     }
 1866:                 }
 1867:                 if ($context eq 'requestcourses') {
 1868:                     $datatable .= '</tr><tr>';
 1869:                     foreach my $item (@usertools) {
 1870:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 1871:                     }
 1872:                     $datatable .= '</tr></table>';
 1873:                 }
 1874:                 $datatable .= '</td>';
 1875:                 unless (($context eq 'requestcourses') ||
 1876:                         ($context eq 'requestauthor')) {
 1877:                     $datatable .= 
 1878:                               '<td class="LC_right_item">'.
 1879:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 1880:                               '<input type="text" name="quota_'.$type.
 1881:                               '" value="'.$currdefquota.
 1882:                               '" size="5" /></span>'.('&nbsp;' x 2).
 1883:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 1884:                               '<input type="text" name="authorquota_'.$type.
 1885:                               '" value="'.$currauthorquota.
 1886:                               '" size="5" /></span></td>';
 1887:                 }
 1888:                 $datatable .= '</tr>';
 1889:             }
 1890:         }
 1891:     }
 1892:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 1893:         $defaultquota = '20';
 1894:         $authorquota = '500';
 1895:         if (ref($settings) eq 'HASH') {
 1896:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 1897:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 1898:             } elsif (defined($settings->{'default'})) {
 1899:                 $defaultquota = $settings->{'default'};
 1900:             }
 1901:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 1902:                 $authorquota = $settings->{'authorquota'}->{'default'};
 1903:             }
 1904:         }
 1905:     }
 1906:     $typecount ++;
 1907:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 1908:     $datatable .= '<tr'.$css_class.'>'.
 1909:                   '<td>'.$othertitle.'</td>'.
 1910:                   '<td class="LC_left_item">';
 1911:     if ($context eq 'requestcourses') {
 1912:         $datatable .= '<table><tr>';
 1913:     }
 1914:     my %defcell;
 1915:     foreach my $item (@usertools) {
 1916:         if ($context eq 'requestcourses') {
 1917:             my ($curroption,$currlimit);
 1918:             if (ref($settings) eq 'HASH') {
 1919:                 if (ref($settings->{$item}) eq 'HASH') {
 1920:                     $curroption = $settings->{$item}->{'default'};
 1921:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 1922:                         $currlimit = $1;
 1923:                     }
 1924:                 }
 1925:             }
 1926:             if (!$curroption) {
 1927:                 $curroption = 'norequest';
 1928:             }
 1929:             $datatable .= '<th>'.$titles{$item}.'</th>';
 1930:             foreach my $option (@options) {
 1931:                 my $val = $option;
 1932:                 if ($option eq 'norequest') {
 1933:                     $val = 0;
 1934:                 }
 1935:                 if ($option eq 'validate') {
 1936:                     my $canvalidate = 0;
 1937:                     if (ref($validations{$item}) eq 'HASH') {
 1938:                         if ($validations{$item}{'default'}) {
 1939:                             $canvalidate = 1;
 1940:                         }
 1941:                     }
 1942:                     next if (!$canvalidate);
 1943:                 }
 1944:                 my $checked = '';
 1945:                 if ($option eq $curroption) {
 1946:                     $checked = ' checked="checked"';
 1947:                 } elsif ($option eq 'autolimit') {
 1948:                     if ($curroption =~ /^autolimit/) {
 1949:                         $checked = ' checked="checked"';
 1950:                     }
 1951:                 }
 1952:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 1953:                                   '<input type="radio" name="crsreq_'.$item.
 1954:                                   '_default" value="'.$val.'"'.$checked.' />'.
 1955:                                   $titles{$option}.'</label>';
 1956:                 if ($option eq 'autolimit') {
 1957:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 1958:                                        $item.'_limit_default" size="1" '.
 1959:                                        'value="'.$currlimit.'" />';
 1960:                 }
 1961:                 $defcell{$item} .= '</span> ';
 1962:                 if ($option eq 'autolimit') {
 1963:                     $defcell{$item} .= $titles{'unlimited'};
 1964:                 }
 1965:             }
 1966:         } elsif ($context eq 'requestauthor') {
 1967:             my $curroption;
 1968:             if (ref($settings) eq 'HASH') {
 1969:                 $curroption = $settings->{'default'};
 1970:             }
 1971:             if (!$curroption) {
 1972:                 $curroption = 'norequest';
 1973:             }
 1974:             foreach my $option (@options) {
 1975:                 my $val = $option;
 1976:                 if ($option eq 'norequest') {
 1977:                     $val = 0;
 1978:                 }
 1979:                 my $checked = '';
 1980:                 if ($option eq $curroption) {
 1981:                     $checked = ' checked="checked"';
 1982:                 }
 1983:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1984:                               '<input type="radio" name="authorreq_default"'.
 1985:                               ' value="'.$val.'"'.$checked.' />'.
 1986:                               $titles{$option}.'</label></span>&nbsp; ';
 1987:             }
 1988:         } else {
 1989:             my $checked = 'checked="checked" ';
 1990:             if (ref($settings) eq 'HASH') {
 1991:                 if (ref($settings->{$item}) eq 'HASH') {
 1992:                     if ($settings->{$item}->{'default'} == 0) {
 1993:                         $checked = '';
 1994:                     } elsif ($settings->{$item}->{'default'} == 1) {
 1995:                         $checked = 'checked="checked" ';
 1996:                     }
 1997:                 }
 1998:             }
 1999:             $datatable .= '<span class="LC_nobreak"><label>'.
 2000:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2001:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2002:                           '</label></span>&nbsp; ';
 2003:         }
 2004:     }
 2005:     if ($context eq 'requestcourses') {
 2006:         $datatable .= '</tr><tr>';
 2007:         foreach my $item (@usertools) {
 2008:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2009:         }
 2010:         $datatable .= '</tr></table>';
 2011:     }
 2012:     $datatable .= '</td>';
 2013:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2014:         $datatable .= '<td class="LC_right_item">'.
 2015:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2016:                       '<input type="text" name="defaultquota" value="'.
 2017:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2018:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2019:                       '<input type="text" name="authorquota" value="'.
 2020:                       $authorquota.'" size="5" /></span></td>';
 2021:     }
 2022:     $datatable .= '</tr>';
 2023:     $typecount ++;
 2024:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2025:     $datatable .= '<tr'.$css_class.'>'.
 2026:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2027:     if ($context eq 'requestcourses') {
 2028:         $datatable .= &mt('(overrides affiliation, if set)').
 2029:                       '</td>'.
 2030:                       '<td class="LC_left_item">'.
 2031:                       '<table><tr>';
 2032:     } else {
 2033:         $datatable .= &mt('(overrides affiliation, if checked)').
 2034:                       '</td>'.
 2035:                       '<td class="LC_left_item" colspan="2">'.
 2036:                       '<br />';
 2037:     }
 2038:     my %advcell;
 2039:     foreach my $item (@usertools) {
 2040:         if ($context eq 'requestcourses') {
 2041:             my ($curroption,$currlimit);
 2042:             if (ref($settings) eq 'HASH') {
 2043:                 if (ref($settings->{$item}) eq 'HASH') {
 2044:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2045:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2046:                         $currlimit = $1;
 2047:                     }
 2048:                 }
 2049:             }
 2050:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2051:             my $checked = '';
 2052:             if ($curroption eq '') {
 2053:                 $checked = ' checked="checked"';
 2054:             }
 2055:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2056:                                '<input type="radio" name="crsreq_'.$item.
 2057:                                '__LC_adv" value=""'.$checked.' />'.
 2058:                                &mt('No override set').'</label></span>&nbsp; ';
 2059:             foreach my $option (@options) {
 2060:                 my $val = $option;
 2061:                 if ($option eq 'norequest') {
 2062:                     $val = 0;
 2063:                 }
 2064:                 if ($option eq 'validate') {
 2065:                     my $canvalidate = 0;
 2066:                     if (ref($validations{$item}) eq 'HASH') {
 2067:                         if ($validations{$item}{'_LC_adv'}) {
 2068:                             $canvalidate = 1;
 2069:                         }
 2070:                     }
 2071:                     next if (!$canvalidate);
 2072:                 }
 2073:                 my $checked = '';
 2074:                 if ($val eq $curroption) {
 2075:                     $checked = ' checked="checked"';
 2076:                 } elsif ($option eq 'autolimit') {
 2077:                     if ($curroption =~ /^autolimit/) {
 2078:                         $checked = ' checked="checked"';
 2079:                     }
 2080:                 }
 2081:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2082:                                   '<input type="radio" name="crsreq_'.$item.
 2083:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2084:                                   $titles{$option}.'</label>';
 2085:                 if ($option eq 'autolimit') {
 2086:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2087:                                        $item.'_limit__LC_adv" size="1" '.
 2088:                                        'value="'.$currlimit.'" />';
 2089:                 }
 2090:                 $advcell{$item} .= '</span> ';
 2091:                 if ($option eq 'autolimit') {
 2092:                     $advcell{$item} .= $titles{'unlimited'};
 2093:                 }
 2094:             }
 2095:         } elsif ($context eq 'requestauthor') {
 2096:             my $curroption;
 2097:             if (ref($settings) eq 'HASH') {
 2098:                 $curroption = $settings->{'_LC_adv'};
 2099:             }
 2100:             my $checked = '';
 2101:             if ($curroption eq '') {
 2102:                 $checked = ' checked="checked"';
 2103:             }
 2104:             $datatable .= '<span class="LC_nobreak"><label>'.
 2105:                           '<input type="radio" name="authorreq__LC_adv"'.
 2106:                           ' value=""'.$checked.' />'.
 2107:                           &mt('No override set').'</label></span>&nbsp; ';
 2108:             foreach my $option (@options) {
 2109:                 my $val = $option;
 2110:                 if ($option eq 'norequest') {
 2111:                     $val = 0;
 2112:                 }
 2113:                 my $checked = '';
 2114:                 if ($val eq $curroption) {
 2115:                     $checked = ' checked="checked"';
 2116:                 }
 2117:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2118:                               '<input type="radio" name="authorreq__LC_adv"'.
 2119:                               ' value="'.$val.'"'.$checked.' />'.
 2120:                               $titles{$option}.'</label></span>&nbsp; ';
 2121:             }
 2122:         } else {
 2123:             my $checked = 'checked="checked" ';
 2124:             if (ref($settings) eq 'HASH') {
 2125:                 if (ref($settings->{$item}) eq 'HASH') {
 2126:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2127:                         $checked = '';
 2128:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2129:                         $checked = 'checked="checked" ';
 2130:                     }
 2131:                 }
 2132:             }
 2133:             $datatable .= '<span class="LC_nobreak"><label>'.
 2134:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2135:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2136:                           '</label></span>&nbsp; ';
 2137:         }
 2138:     }
 2139:     if ($context eq 'requestcourses') {
 2140:         $datatable .= '</tr><tr>';
 2141:         foreach my $item (@usertools) {
 2142:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2143:         }
 2144:         $datatable .= '</tr></table>';
 2145:     }
 2146:     $datatable .= '</td></tr>';
 2147:     $$rowtotal += $typecount;
 2148:     return $datatable;
 2149: }
 2150: 
 2151: sub print_requestmail {
 2152:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2153:     my ($now,$datatable,%currapp);
 2154:     $now = time;
 2155:     if (ref($settings) eq 'HASH') {
 2156:         if (ref($settings->{'notify'}) eq 'HASH') {
 2157:             if ($settings->{'notify'}{'approval'} ne '') {
 2158:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2159:             }
 2160:         }
 2161:     }
 2162:     my $numinrow = 2;
 2163:     my $css_class;
 2164:     if ($$rowtotal%2) {
 2165:         $css_class = 'LC_odd_row';
 2166:     }
 2167:     if ($customcss) {
 2168:         $css_class .= " $customcss";
 2169:     }
 2170:     $css_class =~ s/^\s+//;
 2171:     if ($css_class) {
 2172:         $css_class = ' class="'.$css_class.'"';
 2173:     }
 2174:     if ($rowstyle) {
 2175:         $css_class .= ' style="'.$rowstyle.'"';
 2176:     }
 2177:     my $text;
 2178:     if ($action eq 'requestcourses') {
 2179:         $text = &mt('Receive notification of course requests requiring approval');
 2180:     } elsif ($action eq 'requestauthor') {
 2181:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2182:     } else {
 2183:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2184:     }
 2185:     $datatable = '<tr'.$css_class.'>'.
 2186:                  ' <td>'.$text.'</td>'.
 2187:                  ' <td class="LC_left_item">';
 2188:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2189:                                                  $action.'notifyapproval',%currapp);
 2190:     if ($numdc > 0) {
 2191:         $datatable .= $table;
 2192:     } else {
 2193:         $datatable .= &mt('There are no active Domain Coordinators');
 2194:     }
 2195:     $datatable .='</td></tr>';
 2196:     return $datatable;
 2197: }
 2198: 
 2199: sub print_studentcode {
 2200:     my ($settings,$rowtotal) = @_;
 2201:     my $rownum = 0; 
 2202:     my ($output,%current);
 2203:     my @crstypes = ('official','unofficial','community','textbook');
 2204:     if (ref($settings) eq 'HASH') {
 2205:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2206:             foreach my $type (@crstypes) {
 2207:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2208:             }
 2209:         }
 2210:     }
 2211:     $output .= '<tr>'.
 2212:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2213:                '<td class="LC_left_item">';
 2214:     foreach my $type (@crstypes) {
 2215:         my $check = ' ';
 2216:         if ($current{$type}) {
 2217:             $check = ' checked="checked" ';
 2218:         }
 2219:         $output .= '<span class="LC_nobreak"><label>'.
 2220:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2221:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2222:     }
 2223:     $output .= '</td></tr>';
 2224:     $$rowtotal ++;
 2225:     return $output;
 2226: }
 2227: 
 2228: sub print_textbookcourses {
 2229:     my ($dom,$type,$settings,$rowtotal) = @_;
 2230:     my $rownum = 0;
 2231:     my $css_class;
 2232:     my $itemcount = 1;
 2233:     my $maxnum = 0;
 2234:     my $bookshash;
 2235:     if (ref($settings) eq 'HASH') {
 2236:         $bookshash = $settings->{$type};
 2237:     }
 2238:     my %ordered;
 2239:     if (ref($bookshash) eq 'HASH') {
 2240:         foreach my $item (keys(%{$bookshash})) {
 2241:             if (ref($bookshash->{$item}) eq 'HASH') {
 2242:                 my $num = $bookshash->{$item}{'order'};
 2243:                 $ordered{$num} = $item;
 2244:             }
 2245:         }
 2246:     }
 2247:     my $confname = $dom.'-domainconfig';
 2248:     my $switchserver = &check_switchserver($dom,$confname);
 2249:     my $maxnum = scalar(keys(%ordered));
 2250:     my $datatable;
 2251:     if (keys(%ordered)) {
 2252:         my @items = sort { $a <=> $b } keys(%ordered);
 2253:         for (my $i=0; $i<@items; $i++) {
 2254:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2255:             my $key = $ordered{$items[$i]};
 2256:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2257:             my $coursetitle = $coursehash{'description'};
 2258:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2259:             if (ref($bookshash->{$key}) eq 'HASH') {
 2260:                 $subject = $bookshash->{$key}->{'subject'};
 2261:                 $title = $bookshash->{$key}->{'title'};
 2262:                 if ($type eq 'textbooks') {
 2263:                     $publisher = $bookshash->{$key}->{'publisher'};
 2264:                     $author = $bookshash->{$key}->{'author'};
 2265:                     $image = $bookshash->{$key}->{'image'};
 2266:                     if ($image ne '') {
 2267:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2268:                         my $imagethumb = "$path/tn-".$imagefile;
 2269:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2270:                     }
 2271:                 }
 2272:             }
 2273:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2274:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2275:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2276:             for (my $k=0; $k<=$maxnum; $k++) {
 2277:                 my $vpos = $k+1;
 2278:                 my $selstr;
 2279:                 if ($k == $i) {
 2280:                     $selstr = ' selected="selected" ';
 2281:                 }
 2282:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2283:             }
 2284:             $datatable .= '</select>'.('&nbsp;'x2).
 2285:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2286:                 &mt('Delete?').'</label></span></td>'.
 2287:                 '<td colspan="2">'.
 2288:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2289:                 ('&nbsp;'x2).
 2290:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2291:             if ($type eq 'textbooks') {
 2292:                 $datatable .= ('&nbsp;'x2).
 2293:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2294:                               ('&nbsp;'x2).
 2295:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2296:                               ('&nbsp;'x2).
 2297:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2298:                 if ($image) {
 2299:                     $datatable .= '<span class="LC_nobreak">'.
 2300:                                   $imgsrc.
 2301:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2302:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2303:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2304:                 }
 2305:                 if ($switchserver) {
 2306:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2307:                 } else {
 2308:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2309:                 }
 2310:             }
 2311:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2312:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2313:                           $coursetitle.'</span></td></tr>'."\n";
 2314:             $itemcount ++;
 2315:         }
 2316:     }
 2317:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2318:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2319:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2320:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2321:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2322:     for (my $k=0; $k<$maxnum+1; $k++) {
 2323:         my $vpos = $k+1;
 2324:         my $selstr;
 2325:         if ($k == $maxnum) {
 2326:             $selstr = ' selected="selected" ';
 2327:         }
 2328:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2329:     }
 2330:     $datatable .= '</select>&nbsp;'."\n".
 2331:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2332:                   '<td colspan="2">'.
 2333:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2334:                   ('&nbsp;'x2).
 2335:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2336:                   ('&nbsp;'x2);
 2337:     if ($type eq 'textbooks') {
 2338:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2339:                       ('&nbsp;'x2).
 2340:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2341:                       ('&nbsp;'x2).
 2342:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2343:         if ($switchserver) {
 2344:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2345:         } else {
 2346:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2347:         }
 2348:         $datatable .= '</span>'."\n";
 2349:     }
 2350:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2351:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2352:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2353:                   &Apache::loncommon::selectcourse_link
 2354:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2355:                   '</span></td>'."\n".
 2356:                   '</tr>'."\n";
 2357:     $itemcount ++;
 2358:     return $datatable;
 2359: }
 2360: 
 2361: sub textbookcourses_javascript {
 2362:     my ($settings) = @_;
 2363:     return unless(ref($settings) eq 'HASH');
 2364:     my (%ordered,%total,%jstext);
 2365:     foreach my $type ('textbooks','templates') {
 2366:         $total{$type} = 0;
 2367:         if (ref($settings->{$type}) eq 'HASH') {
 2368:             foreach my $item (keys(%{$settings->{$type}})) {
 2369:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2370:                     my $num = $settings->{$type}->{$item}{'order'};
 2371:                     $ordered{$type}{$num} = $item;
 2372:                 }
 2373:             }
 2374:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2375:         }
 2376:         my @jsarray = ();
 2377:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 2378:             push(@jsarray,$ordered{$type}{$item});
 2379:         }
 2380:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 2381:     }
 2382:     return <<"ENDSCRIPT";
 2383: <script type="text/javascript">
 2384: // <![CDATA[
 2385: function reorderBooks(form,item,caller) {
 2386:     var changedVal;
 2387: $jstext{'textbooks'};
 2388: $jstext{'templates'};
 2389:     var newpos;
 2390:     var maxh;
 2391:     if (caller == 'textbooks') {  
 2392:         newpos = 'textbooks_addbook_pos';
 2393:         maxh = 1 + $total{'textbooks'};
 2394:     } else {
 2395:         newpos = 'templates_addbook_pos';
 2396:         maxh = 1 + $total{'templates'};
 2397:     }
 2398:     var current = new Array;
 2399:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2400:     if (item == newpos) {
 2401:         changedVal = newitemVal;
 2402:     } else {
 2403:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2404:         current[newitemVal] = newpos;
 2405:     }
 2406:     if (caller == 'textbooks') {
 2407:         for (var i=0; i<textbooks.length; i++) {
 2408:             var elementName = 'textbooks_'+textbooks[i];
 2409:             if (elementName != item) {
 2410:                 if (form.elements[elementName]) {
 2411:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2412:                     current[currVal] = elementName;
 2413:                 }
 2414:             }
 2415:         }
 2416:     }
 2417:     if (caller == 'templates') {
 2418:         for (var i=0; i<templates.length; i++) {
 2419:             var elementName = 'templates_'+templates[i];
 2420:             if (elementName != item) {
 2421:                 if (form.elements[elementName]) {
 2422:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2423:                     current[currVal] = elementName;
 2424:                 }
 2425:             }
 2426:         }
 2427:     }
 2428:     var oldVal;
 2429:     for (var j=0; j<maxh; j++) {
 2430:         if (current[j] == undefined) {
 2431:             oldVal = j;
 2432:         }
 2433:     }
 2434:     if (oldVal < changedVal) {
 2435:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2436:            var elementName = current[k];
 2437:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2438:         }
 2439:     } else {
 2440:         for (var k=changedVal; k<oldVal; k++) {
 2441:             var elementName = current[k];
 2442:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2443:         }
 2444:     }
 2445:     return;
 2446: }
 2447: 
 2448: // ]]>
 2449: </script>
 2450: 
 2451: ENDSCRIPT
 2452: }
 2453: 
 2454: sub print_autoenroll {
 2455:     my ($dom,$settings,$rowtotal) = @_;
 2456:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 2457:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,$failsafe);
 2458:     if (ref($settings) eq 'HASH') {
 2459:         if (exists($settings->{'run'})) {
 2460:             if ($settings->{'run'} eq '0') {
 2461:                 $runoff = ' checked="checked" ';
 2462:                 $runon = ' ';
 2463:             } else {
 2464:                 $runon = ' checked="checked" ';
 2465:                 $runoff = ' ';
 2466:             }
 2467:         } else {
 2468:             if ($autorun) {
 2469:                 $runon = ' checked="checked" ';
 2470:                 $runoff = ' ';
 2471:             } else {
 2472:                 $runoff = ' checked="checked" ';
 2473:                 $runon = ' ';
 2474:             }
 2475:         }
 2476:         if (exists($settings->{'co-owners'})) {
 2477:             if ($settings->{'co-owners'} eq '0') {
 2478:                 $coownersoff = ' checked="checked" ';
 2479:                 $coownerson = ' ';
 2480:             } else {
 2481:                 $coownerson = ' checked="checked" ';
 2482:                 $coownersoff = ' ';
 2483:             }
 2484:         } else {
 2485:             $coownersoff = ' checked="checked" ';
 2486:             $coownerson = ' ';
 2487:         }
 2488:         if (exists($settings->{'sender_domain'})) {
 2489:             $defdom = $settings->{'sender_domain'};
 2490:         }
 2491:         if (exists($settings->{'autofailsafe'})) {
 2492:             $failsafe = $settings->{'autofailsafe'};
 2493:         }
 2494:     } else {
 2495:         if ($autorun) {
 2496:             $runon = ' checked="checked" ';
 2497:             $runoff = ' ';
 2498:         } else {
 2499:             $runoff = ' checked="checked" ';
 2500:             $runon = ' ';
 2501:         }
 2502:     }
 2503:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 2504:     my $notif_sender;
 2505:     if (ref($settings) eq 'HASH') {
 2506:         $notif_sender = $settings->{'sender_uname'};
 2507:     }
 2508:     my $datatable='<tr class="LC_odd_row">'.
 2509:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 2510:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2511:                   '<input type="radio" name="autoenroll_run"'.
 2512:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2513:                   '<label><input type="radio" name="autoenroll_run"'.
 2514:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 2515:                   '</tr><tr>'.
 2516:                   '<td>'.&mt('Notification messages - sender').
 2517:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 2518:                   &mt('username').':&nbsp;'.
 2519:                   '<input type="text" name="sender_uname" value="'.
 2520:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 2521:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 2522:                   '<tr class="LC_odd_row">'.
 2523:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 2524:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2525:                   '<input type="radio" name="autoassign_coowners"'.
 2526:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2527:                   '<label><input type="radio" name="autoassign_coowners"'.
 2528:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 2529:                   '</tr><tr>'.
 2530:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 2531:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 2532:                   '<input type="text" name="autoenroll_failsafe"'.
 2533:                   ' value="'.$failsafe.'" size="4" /></span></td></tr>';
 2534:     $$rowtotal += 4;
 2535:     return $datatable;
 2536: }
 2537: 
 2538: sub print_autoupdate {
 2539:     my ($position,$dom,$settings,$rowtotal) = @_;
 2540:     my $datatable;
 2541:     if ($position eq 'top') {
 2542:         my $updateon = ' ';
 2543:         my $updateoff = ' checked="checked" ';
 2544:         my $classlistson = ' ';
 2545:         my $classlistsoff = ' checked="checked" ';
 2546:         if (ref($settings) eq 'HASH') {
 2547:             if ($settings->{'run'} eq '1') {
 2548:                 $updateon = $updateoff;
 2549:                 $updateoff = ' ';
 2550:             }
 2551:             if ($settings->{'classlists'} eq '1') {
 2552:                 $classlistson = $classlistsoff;
 2553:                 $classlistsoff = ' ';
 2554:             }
 2555:         }
 2556:         my %title = (
 2557:                    run => 'Auto-update active?',
 2558:                    classlists => 'Update information in classlists?',
 2559:                     );
 2560:         $datatable = '<tr class="LC_odd_row">'. 
 2561:                   '<td>'.&mt($title{'run'}).'</td>'.
 2562:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2563:                   '<input type="radio" name="autoupdate_run"'.
 2564:                   $updateon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2565:                   '<label><input type="radio" name="autoupdate_run"'.
 2566:                   $updateoff.'value="0" />'.&mt('No').'</label></span></td>'.
 2567:                   '</tr><tr>'.
 2568:                   '<td>'.&mt($title{'classlists'}).'</td>'.
 2569:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 2570:                   '<label><input type="radio" name="classlists"'.
 2571:                   $classlistson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2572:                   '<label><input type="radio" name="classlists"'.
 2573:                   $classlistsoff.'value="0" />'.&mt('No').'</label></span></td>'.
 2574:                   '</tr>';
 2575:         $$rowtotal += 2;
 2576:     } elsif ($position eq 'middle') {
 2577:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2578:         my $numinrow = 3;
 2579:         my $locknamesettings;
 2580:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 2581:                                      $dom,$numinrow,$othertitle,
 2582:                                     'lockablenames',$rowtotal);
 2583:         $$rowtotal ++;
 2584:     } else {
 2585:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2586:         my @fields = ('lastname','firstname','middlename','generation',
 2587:                       'permanentemail','id');
 2588:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 2589:         my $numrows = 0;
 2590:         if (ref($types) eq 'ARRAY') {
 2591:             if (@{$types} > 0) {
 2592:                 $datatable = 
 2593:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 2594:                                          \@fields,$types,\$numrows);
 2595:                     $$rowtotal += @{$types}; 
 2596:             }
 2597:         }
 2598:         $datatable .= 
 2599:             &usertype_update_row($settings,{'default' => $othertitle},
 2600:                                  \%fieldtitles,\@fields,['default'],
 2601:                                  \$numrows);
 2602:         $$rowtotal ++;     
 2603:     }
 2604:     return $datatable;
 2605: }
 2606: 
 2607: sub print_autocreate {
 2608:     my ($dom,$settings,$rowtotal) = @_;
 2609:     my (%createon,%createoff,%currhash);
 2610:     my @types = ('xml','req');
 2611:     if (ref($settings) eq 'HASH') {
 2612:         foreach my $item (@types) {
 2613:             $createoff{$item} = ' checked="checked" ';
 2614:             $createon{$item} = ' ';
 2615:             if (exists($settings->{$item})) {
 2616:                 if ($settings->{$item}) {
 2617:                     $createon{$item} = ' checked="checked" ';
 2618:                     $createoff{$item} = ' ';
 2619:                 }
 2620:             }
 2621:         }
 2622:         if ($settings->{'xmldc'} ne '') {
 2623:             $currhash{$settings->{'xmldc'}} = 1;
 2624:         }
 2625:     } else {
 2626:         foreach my $item (@types) {
 2627:             $createoff{$item} = ' checked="checked" ';
 2628:             $createon{$item} = ' ';
 2629:         }
 2630:     }
 2631:     $$rowtotal += 2;
 2632:     my $numinrow = 2;
 2633:     my $datatable='<tr class="LC_odd_row">'.
 2634:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 2635:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2636:                   '<input type="radio" name="autocreate_xml"'.
 2637:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2638:                   '<label><input type="radio" name="autocreate_xml"'.
 2639:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 2640:                   '</td></tr><tr>'.
 2641:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 2642:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2643:                   '<input type="radio" name="autocreate_req"'.
 2644:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2645:                   '<label><input type="radio" name="autocreate_req"'.
 2646:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 2647:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 2648:                                                    'autocreate_xmldc',%currhash);
 2649:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 2650:     if ($numdc > 1) {
 2651:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 2652:                       '</td><td class="LC_left_item">';
 2653:     } else {
 2654:         $datatable .= &mt('Course creation processed as:').
 2655:                       '</td><td class="LC_right_item">';
 2656:     }
 2657:     $datatable .= $dctable.'</td></tr>';
 2658:     $$rowtotal += $rows;
 2659:     return $datatable;
 2660: }
 2661: 
 2662: sub print_directorysrch {
 2663:     my ($position,$dom,$settings,$rowtotal) = @_;
 2664:     my $datatable;
 2665:     if ($position eq 'top') {
 2666:         my $instsrchon = ' ';
 2667:         my $instsrchoff = ' checked="checked" ';
 2668:         my ($exacton,$containson,$beginson);
 2669:         my $instlocalon = ' ';
 2670:         my $instlocaloff = ' checked="checked" ';
 2671:         if (ref($settings) eq 'HASH') {
 2672:             if ($settings->{'available'} eq '1') {
 2673:                 $instsrchon = $instsrchoff;
 2674:                 $instsrchoff = ' ';
 2675:             }
 2676:             if ($settings->{'localonly'} eq '1') {
 2677:                 $instlocalon = $instlocaloff;
 2678:                 $instlocaloff = ' ';
 2679:             }
 2680:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 2681:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 2682:                     if ($type eq 'exact') {
 2683:                         $exacton = ' checked="checked" ';
 2684:                     } elsif ($type eq 'contains') {
 2685:                         $containson = ' checked="checked" ';
 2686:                     } elsif ($type eq 'begins') {
 2687:                         $beginson = ' checked="checked" ';
 2688:                     }
 2689:                 }
 2690:             } else {
 2691:                 if ($settings->{'searchtypes'} eq 'exact') {
 2692:                     $exacton = ' checked="checked" ';
 2693:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 2694:                     $containson = ' checked="checked" ';
 2695:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 2696:                     $exacton = ' checked="checked" ';
 2697:                     $containson = ' checked="checked" ';
 2698:                 }
 2699:             }
 2700:         }
 2701:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 2702:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2703: 
 2704:         my $numinrow = 4;
 2705:         my $cansrchrow = 0;
 2706:         $datatable='<tr class="LC_odd_row">'.
 2707:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 2708:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2709:                    '<input type="radio" name="dirsrch_available"'.
 2710:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2711:                    '<label><input type="radio" name="dirsrch_available"'.
 2712:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 2713:                    '</tr><tr>'.
 2714:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 2715:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2716:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 2717:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 2718:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 2719:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 2720:                    '</tr>';
 2721:         $$rowtotal += 2;
 2722:         if (ref($usertypes) eq 'HASH') {
 2723:             if (keys(%{$usertypes}) > 0) {
 2724:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 2725:                                              $numinrow,$othertitle,'cansearch',
 2726:                                              $rowtotal);
 2727:                 $cansrchrow = 1;
 2728:             }
 2729:         }
 2730:         if ($cansrchrow) {
 2731:             $$rowtotal ++;
 2732:             $datatable .= '<tr>';
 2733:         } else {
 2734:             $datatable .= '<tr class="LC_odd_row">';
 2735:         }
 2736:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 2737:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 2738:         foreach my $title (@{$titleorder}) {
 2739:             if (defined($searchtitles->{$title})) {
 2740:                 my $check = ' ';
 2741:                 if (ref($settings) eq 'HASH') {
 2742:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 2743:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 2744:                             $check = ' checked="checked" ';
 2745:                         }
 2746:                     }
 2747:                 }
 2748:                 $datatable .= '<td class="LC_left_item">'.
 2749:                               '<span class="LC_nobreak"><label>'.
 2750:                               '<input type="checkbox" name="searchby" '.
 2751:                               'value="'.$title.'"'.$check.'/>'.
 2752:                               $searchtitles->{$title}.'</label></span></td>';
 2753:             }
 2754:         }
 2755:         $datatable .= '</tr></table></td></tr>';
 2756:         $$rowtotal ++;
 2757:         if ($cansrchrow) {
 2758:             $datatable .= '<tr class="LC_odd_row">';
 2759:         } else {
 2760:             $datatable .= '<tr>';
 2761:         }
 2762:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 2763:                       '<td class="LC_left_item" colspan="2">'.
 2764:                       '<span class="LC_nobreak"><label>'.
 2765:                       '<input type="checkbox" name="searchtypes" '.
 2766:                       $exacton.' value="exact" />'.&mt('Exact match').
 2767:                       '</label>&nbsp;'.
 2768:                       '<label><input type="checkbox" name="searchtypes" '.
 2769:                       $beginson.' value="begins" />'.&mt('Begins with').
 2770:                       '</label>&nbsp;'.
 2771:                       '<label><input type="checkbox" name="searchtypes" '.
 2772:                       $containson.' value="contains" />'.&mt('Contains').
 2773:                       '</label></span></td></tr>';
 2774:         $$rowtotal ++;
 2775:     } else {
 2776:         my $domsrchon = ' checked="checked" ';
 2777:         my $domsrchoff = ' ';
 2778:         my $domlocalon = ' ';
 2779:         my $domlocaloff = ' checked="checked" ';
 2780:         if (ref($settings) eq 'HASH') {
 2781:             if ($settings->{'lclocalonly'} eq '1') {
 2782:                 $domlocalon = $domlocaloff;
 2783:                 $domlocaloff = ' ';
 2784:             }
 2785:             if ($settings->{'lcavailable'} eq '0') {
 2786:                 $domsrchoff = $domsrchon;
 2787:                 $domsrchon = ' ';
 2788:             }
 2789:         }
 2790:         $datatable='<tr class="LC_odd_row">'.
 2791:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 2792:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2793:                       '<input type="radio" name="dirsrch_domavailable"'.
 2794:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2795:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 2796:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 2797:                       '</tr><tr>'.
 2798:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 2799:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2800:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 2801:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 2802:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 2803:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 2804:                       '</tr>';
 2805:         $$rowtotal += 2;
 2806:     }
 2807:     return $datatable;
 2808: }
 2809: 
 2810: sub print_contacts {
 2811:     my ($position,$dom,$settings,$rowtotal) = @_;
 2812:     my $datatable;
 2813:     my @contacts = ('adminemail','supportemail');
 2814:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 2815:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings);
 2816:     if ($position eq 'top') {
 2817:         if (ref($settings) eq 'HASH') {
 2818:             foreach my $item (@contacts) {
 2819:                 if (exists($settings->{$item})) {
 2820:                     $to{$item} = $settings->{$item};
 2821:                 }
 2822:             }
 2823:         }
 2824:     } elsif ($position eq 'middle') {
 2825:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 2826:                      'updatesmail','idconflictsmail','hostipmail');
 2827:         foreach my $type (@mailings) {
 2828:             $otheremails{$type} = '';
 2829:         }
 2830:     } else {
 2831:         @mailings = ('helpdeskmail','otherdomsmail');
 2832:         foreach my $type (@mailings) {
 2833:             $otheremails{$type} = '';
 2834:         }
 2835:         $bccemails{'helpdeskmail'} = '';
 2836:         $bccemails{'otherdomsmail'} = '';
 2837:         $includestr{'helpdeskmail'} = '';
 2838:         $includestr{'otherdomsmail'} = '';
 2839:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 2840:     }
 2841:     if (ref($settings) eq 'HASH') {
 2842:         unless ($position eq 'top') {
 2843:             foreach my $type (@mailings) {
 2844:                 if (exists($settings->{$type})) {
 2845:                     if (ref($settings->{$type}) eq 'HASH') {
 2846:                         foreach my $item (@contacts) {
 2847:                             if ($settings->{$type}{$item}) {
 2848:                                 $checked{$type}{$item} = ' checked="checked" ';
 2849:                             }
 2850:                         }
 2851:                         $otheremails{$type} = $settings->{$type}{'others'};
 2852:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 2853:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 2854:                             if ($settings->{$type}{'include'} ne '') {
 2855:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 2856:                                 $includestr{$type} = &unescape($includestr{$type});
 2857:                             }
 2858:                         }
 2859:                     }
 2860:                 } elsif ($type eq 'lonstatusmail') {
 2861:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 2862:                 }
 2863:             }
 2864:         }
 2865:         if ($position eq 'bottom') {
 2866:             foreach my $type (@mailings) {
 2867:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 2868:                 if ($settings->{$type}{'include'} ne '') {
 2869:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 2870:                     $includestr{$type} = &unescape($includestr{$type});
 2871:                 }
 2872:             }
 2873:             if (ref($settings->{'helpform'}) eq 'HASH') {
 2874:                 if (ref($fields) eq 'ARRAY') {
 2875:                     foreach my $field (@{$fields}) {
 2876:                         $currfield{$field} = $settings->{'helpform'}{$field};
 2877:                     }
 2878:                 }
 2879:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 2880:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 2881:                 } else {
 2882:                     $maxsize = '1.0';
 2883:                 }
 2884:             } else {
 2885:                 if (ref($fields) eq 'ARRAY') {
 2886:                     foreach my $field (@{$fields}) {
 2887:                         $currfield{$field} = 'yes';
 2888:                     }
 2889:                 }
 2890:                 $maxsize = '1.0';
 2891:             }
 2892:         }
 2893:     } else {
 2894:         if ($position eq 'top') {
 2895:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 2896:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 2897:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 2898:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 2899:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 2900:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 2901:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 2902:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 2903:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 2904:         } elsif ($position eq 'bottom') {
 2905:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 2906:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 2907:             if (ref($fields) eq 'ARRAY') {
 2908:                 foreach my $field (@{$fields}) {
 2909:                     $currfield{$field} = 'yes';
 2910:                 }
 2911:             }
 2912:             $maxsize = '1.0';
 2913:         }
 2914:     }
 2915:     my ($titles,$short_titles) = &contact_titles();
 2916:     my $rownum = 0;
 2917:     my $css_class;
 2918:     if ($position eq 'top') {
 2919:         foreach my $item (@contacts) {
 2920:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 2921:             $datatable .= '<tr'.$css_class.'>'. 
 2922:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 2923:                           '</span></td><td class="LC_right_item">'.
 2924:                           '<input type="text" name="'.$item.'" value="'.
 2925:                           $to{$item}.'" /></td></tr>';
 2926:             $rownum ++;
 2927:         }
 2928:     } else {
 2929:         foreach my $type (@mailings) {
 2930:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 2931:             $datatable .= '<tr'.$css_class.'>'.
 2932:                           '<td><span class="LC_nobreak">'.
 2933:                           $titles->{$type}.': </span></td>'.
 2934:                           '<td class="LC_left_item">';
 2935:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 2936:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 2937:             }
 2938:             $datatable .= '<span class="LC_nobreak">';
 2939:             foreach my $item (@contacts) {
 2940:                 $datatable .= '<label>'.
 2941:                               '<input type="checkbox" name="'.$type.'"'.
 2942:                               $checked{$type}{$item}.
 2943:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 2944:                               '</label>&nbsp;';
 2945:             }
 2946:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 2947:                           '<input type="text" name="'.$type.'_others" '.
 2948:                           'value="'.$otheremails{$type}.'"  />';
 2949:             my %locchecked;
 2950:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 2951:                 foreach my $loc ('s','b') {
 2952:                     if ($includeloc{$type} eq $loc) {
 2953:                         $locchecked{$loc} = ' checked="checked"';
 2954:                         last;
 2955:                     }
 2956:                 }
 2957:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 2958:                               '<input type="text" name="'.$type.'_bcc" '.
 2959:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 2960:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 2961:                               &mt('Text automatically added to e-mail:').' '.
 2962:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 2963:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 2964:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 2965:                               ('&nbsp;'x2).
 2966:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 2967:                               '</span></fieldset>';
 2968:             }
 2969:             $datatable .= '</td></tr>'."\n";
 2970:             $rownum ++;
 2971:         }
 2972:     }
 2973:     if ($position eq 'middle') {
 2974:         my %choices;
 2975:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',
 2976:                                        &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 2977:                                        &mt('LON-CAPA core group - MSU'),600,500));
 2978:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 2979:                                         &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 2980:                                         &mt('LON-CAPA core group - MSU'),600,500));
 2981:         my @toggles = ('reporterrors','reportupdates');
 2982:         my %defaultchecked = ('reporterrors'  => 'on',
 2983:                               'reportupdates' => 'on');
 2984:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 2985:                                                    \%choices,$rownum);
 2986:         $datatable .= $reports;
 2987:     } elsif ($position eq 'bottom') {
 2988:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 2989:         $datatable .= '<tr'.$css_class.'>'.
 2990:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 2991:                       &mt('(e-mail, subject, and description always shown)').
 2992:                       '</td><td class="LC_left_item">';
 2993:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 2994:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 2995:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 2996:             foreach my $field (@{$fields}) {
 2997:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 2998:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 2999:                     $datatable .= ' '.&mt('(logged-in users)');
 3000:                 }
 3001:                 $datatable .='</td><td>';
 3002:                 my $clickaction;
 3003:                 if ($field eq 'screenshot') {
 3004:                     $clickaction = ' onclick="screenshotSize(this);"';
 3005:                 }
 3006:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 3007:                     foreach my $option (@{$possoptions->{$field}}) {
 3008:                         my $checked;
 3009:                         if ($currfield{$field} eq $option) {
 3010:                             $checked = ' checked="checked"';
 3011:                         }
 3012:                         $datatable .= '<span class="LC_nobreak"><label>'.
 3013:                                       '<input type="radio" name="helpform_'.$field.'" '.
 3014:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 3015:                                       '</label></span>'.('&nbsp;'x2);
 3016:                     }
 3017:                 }
 3018:                 if ($field eq 'screenshot') {
 3019:                     my $display;
 3020:                     if ($currfield{$field} eq 'no') {
 3021:                         $display = ' style="display:none"';
 3022:                     }
 3023:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 3024:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 3025:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 3026:                 }
 3027:                 $datatable .= '</td></tr>';
 3028:             }
 3029:             $datatable .= '</table>';
 3030:         }
 3031:         $datatable .= '</td></tr>'."\n";
 3032:         $rownum ++;
 3033:     }
 3034:     $$rowtotal += $rownum;
 3035:     return $datatable;
 3036: }
 3037: 
 3038: sub contacts_javascript {
 3039:     return <<"ENDSCRIPT";
 3040: 
 3041: <script type="text/javascript">
 3042: // <![CDATA[
 3043: 
 3044: function screenshotSize(field) {
 3045:     if (document.getElementById('help_screenshotsize')) {
 3046:         if (field.value == 'no') {
 3047:             document.getElementById('help_screenshotsize').style.display="none";
 3048:         } else {
 3049:             document.getElementById('help_screenshotsize').style.display="";
 3050:         }
 3051:     }
 3052:     return;
 3053: }
 3054: 
 3055: // ]]>
 3056: </script>
 3057: 
 3058: ENDSCRIPT
 3059: }
 3060: 
 3061: sub print_helpsettings {
 3062:     my ($position,$dom,$settings,$rowtotal) = @_;
 3063:     my $confname = $dom.'-domainconfig';
 3064:     my $formname = 'display';
 3065:     my ($datatable,$itemcount);
 3066:     if ($position eq 'top') {
 3067:         $itemcount = 1;
 3068:         my (%choices,%defaultchecked,@toggles);
 3069:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 3070:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 3071:                                      &mt('LON-CAPA bug tracker'),600,500));
 3072:         %defaultchecked = ('submitbugs' => 'on');
 3073:         @toggles = ('submitbugs');
 3074:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3075:                                                      \%choices,$itemcount);
 3076:         $$rowtotal ++;
 3077:     } else {
 3078:         my $css_class;
 3079:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 3080:         my (%customroles,%ordered,%current);
 3081:         if (ref($settings) eq 'HASH') {
 3082:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 3083:                 %current = %{$settings->{'adhoc'}};
 3084:             }
 3085:         }
 3086:         my $count = 0;
 3087:         foreach my $key (sort(keys(%existing))) {
 3088:             if ($key=~/^rolesdef\_(\w+)$/) {
 3089:                 my $rolename = $1;
 3090:                 my (%privs,$order);
 3091:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 3092:                 $customroles{$rolename} = \%privs;
 3093:                 if (ref($current{$rolename}) eq 'HASH') {
 3094:                     $order = $current{$rolename}{'order'};
 3095:                 }
 3096:                 if ($order eq '') {
 3097:                     $order = $count;
 3098:                 }
 3099:                 $ordered{$order} = $rolename;
 3100:                 $count++;
 3101:             }
 3102:         }
 3103:         my $maxnum = scalar(keys(%ordered));
 3104:         my @roles_by_num = ();
 3105:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3106:             push(@roles_by_num,$item);
 3107:         }
 3108:         my $context = 'domprefs';
 3109:         my $crstype = 'Course';
 3110:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3111:         my @accesstypes = ('all','dh','da','none');
 3112:         my ($numstatustypes,@jsarray);
 3113:         if (ref($types) eq 'ARRAY') {
 3114:             if (@{$types} > 0) {
 3115:                 $numstatustypes = scalar(@{$types});
 3116:                 push(@accesstypes,'status');
 3117:                 @jsarray = ('bystatus');
 3118:             }
 3119:         }
 3120:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 3121:         if (keys(%domhelpdesk)) {
 3122:             push(@accesstypes,('inc','exc'));
 3123:             push(@jsarray,('notinc','notexc'));
 3124:         }
 3125:         my $hiddenstr = join("','",@jsarray);
 3126:         $datatable .= &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname);
 3127:         my $context = 'domprefs';
 3128:         my $crstype = 'Course';
 3129:         my $prefix = 'helproles_';
 3130:         my $add_class = 'LC_hidden';
 3131:         foreach my $num (@roles_by_num) {
 3132:             my $role = $ordered{$num};
 3133:             my ($desc,$access,@statuses);
 3134:             if (ref($current{$role}) eq 'HASH') {
 3135:                 $desc = $current{$role}{'desc'};
 3136:                 $access = $current{$role}{'access'};
 3137:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 3138:                     @statuses = @{$current{$role}{'insttypes'}};
 3139:                 }
 3140:             }
 3141:             if ($desc eq '') {
 3142:                 $desc = $role;
 3143:             }
 3144:             my $identifier = 'custhelp'.$num;
 3145:             my %full=();
 3146:             my %levels= (
 3147:                          course => {},
 3148:                          domain => {},
 3149:                          system => {},
 3150:                         );
 3151:             my %levelscurrent=(
 3152:                                course => {},
 3153:                                domain => {},
 3154:                                system => {},
 3155:                               );
 3156:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 3157:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 3158:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3159:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 3160:             $datatable .= '<tr '.$css_class.'><td valign="top"><b>'.$role.'</b><br />'.
 3161:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 3162:             for (my $k=0; $k<=$maxnum; $k++) {
 3163:                 my $vpos = $k+1;
 3164:                 my $selstr;
 3165:                 if ($k == $num) {
 3166:                     $selstr = ' selected="selected" ';
 3167:                 }
 3168:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 3169:             }
 3170:             $datatable .= '</select>'.('&nbsp;'x2).
 3171:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 3172:                           '</td>'.
 3173:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 3174:                           &mt('Name shown to users:').
 3175:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 3176:                           '</fieldset>'.
 3177:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 3178:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 3179:                           '<fieldset>'.
 3180:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 3181:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 3182:                                                                    \%levelscurrent,$identifier,
 3183:                                                                    'LC_hidden',$prefix.$num.'_privs').
 3184:                           '</fieldset></td>';
 3185:             $itemcount ++;
 3186:         }
 3187:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3188:         my $newcust = 'custhelp'.$count;
 3189:         my (%privs,%levelscurrent);
 3190:         my %full=();
 3191:         my %levels= (
 3192:                      course => {},
 3193:                      domain => {},
 3194:                      system => {},
 3195:                     );
 3196:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 3197:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 3198:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 3199:         $datatable .= '<tr '.$css_class.'><td valign="top"><span class="LC_nobreak"><label>'.
 3200:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 3201:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 3202:         for (my $k=0; $k<$maxnum+1; $k++) {
 3203:             my $vpos = $k+1;
 3204:             my $selstr;
 3205:             if ($k == $maxnum) {
 3206:                 $selstr = ' selected="selected" ';
 3207:             }
 3208:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 3209:         }
 3210:         $datatable .= '</select>&nbsp;'."\n".
 3211:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 3212:                       '</label></span></td>'.
 3213:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 3214:                       '<span class="LC_nobreak">'.
 3215:                       &mt('Internal name:').
 3216:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 3217:                       '</span>'.('&nbsp;'x4).
 3218:                       '<span class="LC_nobreak">'.
 3219:                       &mt('Name shown to users:').
 3220:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 3221:                       '</span></fieldset>'.
 3222:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 3223:                                              $usertypes,$types,\%domhelpdesk).
 3224:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 3225:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 3226:                                                                 \@templateroles,$newcust).
 3227:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 3228:                                                                \%levelscurrent,$newcust).
 3229:                       '</fieldset>'.
 3230:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 3231:                       '</td></tr>';
 3232:         $count ++;
 3233:         $$rowtotal += $count;
 3234:     }
 3235:     return $datatable;
 3236: }
 3237: 
 3238: sub adhocbutton {
 3239:     my ($prefix,$num,$field,$visibility) = @_;
 3240:     my %lt = &Apache::lonlocal::texthash(
 3241:                                           show => 'Show details',
 3242:                                           hide => 'Hide details',
 3243:                                         );
 3244:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 3245:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 3246:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 3247:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 3248: }
 3249: 
 3250: sub helpsettings_javascript {
 3251:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 3252:     return unless(ref($roles_by_num) eq 'ARRAY');
 3253:     my %html_js_lt = &Apache::lonlocal::texthash(
 3254:                                           show => 'Show details',
 3255:                                           hide => 'Hide details',
 3256:                                         );
 3257:     &html_escape(\%html_js_lt);
 3258:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 3259:     return <<"ENDSCRIPT";
 3260: <script type="text/javascript">
 3261: // <![CDATA[
 3262: 
 3263: function reorderHelpRoles(form,item) {
 3264:     var changedVal;
 3265: $jstext
 3266:     var newpos = 'helproles_${total}_pos';
 3267:     var maxh = 1 + $total;
 3268:     var current = new Array();
 3269:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3270:     if (item == newpos) {
 3271:         changedVal = newitemVal;
 3272:     } else {
 3273:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3274:         current[newitemVal] = newpos;
 3275:     }
 3276:     for (var i=0; i<helproles.length; i++) {
 3277:         var elementName = 'helproles_'+helproles[i]+'_pos';
 3278:         if (elementName != item) {
 3279:             if (form.elements[elementName]) {
 3280:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3281:                 current[currVal] = elementName;
 3282:             }
 3283:         }
 3284:     }
 3285:     var oldVal;
 3286:     for (var j=0; j<maxh; j++) {
 3287:         if (current[j] == undefined) {
 3288:             oldVal = j;
 3289:         }
 3290:     }
 3291:     if (oldVal < changedVal) {
 3292:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3293:            var elementName = current[k];
 3294:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3295:         }
 3296:     } else {
 3297:         for (var k=changedVal; k<oldVal; k++) {
 3298:             var elementName = current[k];
 3299:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3300:         }
 3301:     }
 3302:     return;
 3303: }
 3304: 
 3305: function helpdeskAccess(num) {
 3306:     var curraccess = null;
 3307:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 3308:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 3309:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 3310:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 3311:             }
 3312:         }
 3313:     }
 3314:     var shown = Array();
 3315:     var hidden = Array();
 3316:     if (curraccess == 'none') {
 3317:         hidden = Array('$hiddenstr');
 3318:     } else {
 3319:         if (curraccess == 'status') {
 3320:             shown = Array('bystatus');
 3321:             hidden = Array('notinc','notexc');
 3322:         } else {
 3323:             if (curraccess == 'exc') {
 3324:                 shown = Array('notexc');
 3325:                 hidden = Array('notinc','bystatus');
 3326:             }
 3327:             if (curraccess == 'inc') {
 3328:                 shown = Array('notinc');
 3329:                 hidden = Array('notexc','bystatus');
 3330:             }
 3331:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 3332:                 hidden = Array('notinc','notexc','bystatus');
 3333:             }
 3334:         }
 3335:     }
 3336:     if (hidden.length > 0) {
 3337:         for (var i=0; i<hidden.length; i++) {
 3338:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 3339:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 3340:             }
 3341:         }
 3342:     }
 3343:     if (shown.length > 0) {
 3344:         for (var i=0; i<shown.length; i++) {
 3345:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 3346:                 if (shown[i] == 'privs') {
 3347:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 3348:                 } else {
 3349:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 3350:                 }
 3351:             }
 3352:         }
 3353:     }
 3354:     return;
 3355: }
 3356: 
 3357: function toggleHelpdeskItem(num,field) {
 3358:     if (document.getElementById('helproles_'+num+'_'+field)) {
 3359:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 3360:             document.getElementById('helproles_'+num+'_'+field).className =
 3361:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 3362:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 3363:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 3364:             }
 3365:         } else {
 3366:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 3367:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 3368:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 3369:             }
 3370:         }
 3371:     }
 3372:     return;
 3373: }
 3374: 
 3375: // ]]>
 3376: </script>
 3377: 
 3378: ENDSCRIPT
 3379: }
 3380: 
 3381: sub helpdeskroles_access {
 3382:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 3383:         $usertypes,$types,$domhelpdesk) = @_;
 3384:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 3385:     my %lt = &Apache::lonlocal::texthash(
 3386:                     'rou'    => 'Role usage',
 3387:                     'whi'    => 'Which helpdesk personnel may use this role?',
 3388:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 3389:                     'dh'     => 'All with domain helpdesk role',
 3390:                     'da'     => 'All with domain helpdesk assistant role',
 3391:                     'none'   => 'None',
 3392:                     'status' => 'Determined based on institutional status',
 3393:                     'inc'    => 'Include all, but exclude specific personnel',
 3394:                     'exc'    => 'Exclude all, but include specific personnel',
 3395:                   );
 3396:     my %usecheck = (
 3397:                      all => ' checked="checked"',
 3398:                    );
 3399:     my %displaydiv = (
 3400:                       status => 'none',
 3401:                       inc    => 'none',
 3402:                       exc    => 'none',
 3403:                       priv   => 'block',
 3404:                      );
 3405:     my $output;
 3406:     if (ref($current) eq 'HASH') {
 3407:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 3408:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 3409:                 $usecheck{$current->{access}} = $usecheck{'all'};
 3410:                 delete($usecheck{'all'});
 3411:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 3412:                     my $access = $1;
 3413:                     $displaydiv{$access} = 'inline';
 3414:                 } elsif ($current->{access} eq 'none') {
 3415:                     $displaydiv{'priv'} = 'none';
 3416:                 }
 3417:             }
 3418:         }
 3419:     }
 3420:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 3421:               '<p>'.$lt{'whi'}.'</p>';
 3422:     foreach my $access (@{$accesstypes}) {
 3423:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 3424:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 3425:                    $lt{$access}.'</label>';
 3426:         if ($access eq 'status') {
 3427:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 3428:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 3429:                                                                  $othertitle,$usertypes,$types).
 3430:                        '</div>';
 3431:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 3432:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 3433:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 3434:                        '</div>';
 3435:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 3436:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 3437:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 3438:                        '</div>';
 3439:         }
 3440:         $output .= '</p>';
 3441:     }
 3442:     $output .= '</fieldset>';
 3443:     return $output;
 3444: }
 3445: 
 3446: sub radiobutton_prefs {
 3447:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 3448:         $additional,$align) = @_;
 3449:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 3450:                    (ref($choices) eq 'HASH'));
 3451: 
 3452:     my (%checkedon,%checkedoff,$datatable,$css_class);
 3453: 
 3454:     foreach my $item (@{$toggles}) {
 3455:         if ($defaultchecked->{$item} eq 'on') {
 3456:             $checkedon{$item} = ' checked="checked" ';
 3457:             $checkedoff{$item} = ' ';
 3458:         } elsif ($defaultchecked->{$item} eq 'off') {
 3459:             $checkedoff{$item} = ' checked="checked" ';
 3460:             $checkedon{$item} = ' ';
 3461:         }
 3462:     }
 3463:     if (ref($settings) eq 'HASH') {
 3464:         foreach my $item (@{$toggles}) {
 3465:             if ($settings->{$item} eq '1') {
 3466:                 $checkedon{$item} =  ' checked="checked" ';
 3467:                 $checkedoff{$item} = ' ';
 3468:             } elsif ($settings->{$item} eq '0') {
 3469:                 $checkedoff{$item} =  ' checked="checked" ';
 3470:                 $checkedon{$item} = ' ';
 3471:             }
 3472:         }
 3473:     }
 3474:     if ($onclick) {
 3475:         $onclick = ' onclick="'.$onclick.'"';
 3476:     }
 3477:     foreach my $item (@{$toggles}) {
 3478:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3479:         $datatable .=
 3480:             '<tr'.$css_class.'><td valign="top">'.
 3481:             '<span class="LC_nobreak">'.$choices->{$item}.
 3482:             '</span></td>';
 3483:         if ($align eq 'left') {
 3484:             $datatable .= '<td class="LC_left_item">';
 3485:         } else {
 3486:             $datatable .= '<td class="LC_right_item">';
 3487:         }
 3488:         $datatable .=
 3489:             '<span class="LC_nobreak">'.
 3490:             '<label><input type="radio" name="'.
 3491:             $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 3492:             '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 3493:             $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>'.
 3494:             '</span>'.$additional.
 3495:             '</td>'.
 3496:             '</tr>';
 3497:         $itemcount ++;
 3498:     }
 3499:     return ($datatable,$itemcount);
 3500: }
 3501: 
 3502: sub print_coursedefaults {
 3503:     my ($position,$dom,$settings,$rowtotal) = @_;
 3504:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 3505:     my $itemcount = 1;
 3506:     my %choices =  &Apache::lonlocal::texthash (
 3507:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 3508:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 3509:         coursecredits        => 'Credits can be specified for courses',
 3510:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 3511:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 3512:         texengine            => 'Default method to display mathematics',
 3513:         postsubmit           => 'Disable submit button/keypress following student submission',
 3514:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 3515:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 3516:     );
 3517:     my %staticdefaults = (
 3518:                            anonsurvey_threshold => 10,
 3519:                            uploadquota          => 500,
 3520:                            postsubmit           => 60,
 3521:                            mysqltables          => 172800,
 3522:                          );
 3523:     if ($position eq 'top') {
 3524:         %defaultchecked = (
 3525:                             'uselcmath'       => 'on',
 3526:                             'usejsme'         => 'on',
 3527:                             'canclone'        => 'none',
 3528:                           );
 3529:         @toggles = ('uselcmath','usejsme');
 3530:         my $deftex = $Apache::lonnet::deftex;
 3531:         if (ref($settings) eq 'HASH') {
 3532:             if ($settings->{'texengine'}) {
 3533:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 3534:                     $deftex = $settings->{'texengine'};
 3535:                 }
 3536:             }
 3537:         }
 3538:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3539:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 3540:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 3541:                        '</span></td><td class="LC_right_item">'.
 3542:                        '<select name="texengine">'."\n";
 3543:         my %texoptions = (
 3544:                             MathJax  => 'MathJax',
 3545:                             mimetex  => &mt('Convert to Images'),
 3546:                             tth      => &mt('TeX to HTML'),
 3547:                          );
 3548:         foreach my $renderer ('MathJax','mimetex','tth') {
 3549:             my $selected = '';
 3550:             if ($renderer eq $deftex) {
 3551:                 $selected = ' selected="selected"';
 3552:             }
 3553:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 3554:         }
 3555:         $mathdisp .= '</select></td></tr>'."\n";
 3556:         $itemcount ++;
 3557:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3558:                                                      \%choices,$itemcount);
 3559:         $datatable = $mathdisp.$datatable;
 3560:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3561:         $datatable .=
 3562:             '<tr'.$css_class.'><td valign="top">'.
 3563:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 3564:             '</span></td><td class="LC_left_item">';
 3565:         my $currcanclone = 'none';
 3566:         my $onclick;
 3567:         my @cloneoptions = ('none','domain');
 3568:         my %clonetitles = (
 3569:                              none     => 'No additional course requesters',
 3570:                              domain   => "Any course requester in course's domain",
 3571:                              instcode => 'Course requests for official courses ...',
 3572:                           );
 3573:         my (%codedefaults,@code_order,@posscodes);
 3574:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 3575:                                                     \@code_order) eq 'ok') {
 3576:             if (@code_order > 0) {
 3577:                 push(@cloneoptions,'instcode');
 3578:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 3579:             }
 3580:         }
 3581:         if (ref($settings) eq 'HASH') {
 3582:             if ($settings->{'canclone'}) {
 3583:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 3584:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 3585:                         if (@code_order > 0) {
 3586:                             $currcanclone = 'instcode';
 3587:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 3588:                         }
 3589:                     }
 3590:                 } elsif ($settings->{'canclone'} eq 'domain') {
 3591:                     $currcanclone = $settings->{'canclone'};
 3592:                 }
 3593:             }
 3594:         }
 3595:         foreach my $option (@cloneoptions) {
 3596:             my ($checked,$additional);
 3597:             if ($currcanclone eq $option) {
 3598:                 $checked = ' checked="checked"';
 3599:             }
 3600:             if ($option eq 'instcode') {
 3601:                 if (@code_order) {
 3602:                     my $show = 'none';
 3603:                     if ($checked) {
 3604:                         $show = 'block';
 3605:                     }
 3606:                     $additional = '<div id="cloneinstcode" style="display:'.$show.'" />'.
 3607:                                   &mt('Institutional codes for new and cloned course have identical:').
 3608:                                   '<br />';
 3609:                     foreach my $item (@code_order) {
 3610:                         my $codechk;
 3611:                         if ($checked) {
 3612:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 3613:                                 $codechk = ' checked="checked"';
 3614:                             }
 3615:                         }
 3616:                         $additional .= '<label>'.
 3617:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 3618:                                        $item.'</label>';
 3619:                     }
 3620:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 3621:                 }
 3622:             }
 3623:             $datatable .=
 3624:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 3625:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 3626:                 '</label>&nbsp;'.$additional.'</span><br />';
 3627:         }
 3628:         $datatable .= '</td>'.
 3629:                       '</tr>';
 3630:         $itemcount ++;
 3631:     } else {
 3632:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3633:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 3634:         my $currusecredits = 0;
 3635:         my $postsubmitclient = 1;
 3636:         my @types = ('official','unofficial','community','textbook');
 3637:         if (ref($settings) eq 'HASH') {
 3638:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 3639:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 3640:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 3641:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 3642:                 }
 3643:             }
 3644:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 3645:                 foreach my $type (@types) {
 3646:                     next if ($type eq 'community');
 3647:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 3648:                     if ($defcredits{$type} ne '') {
 3649:                         $currusecredits = 1;
 3650:                     }
 3651:                 }
 3652:             }
 3653:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 3654:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 3655:                     $postsubmitclient = 0;
 3656:                     foreach my $type (@types) {
 3657:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3658:                     }
 3659:                 } else {
 3660:                     foreach my $type (@types) {
 3661:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 3662:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 3663:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 3664:                             } else {
 3665:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3666:                             }
 3667:                         } else {
 3668:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3669:                         }
 3670:                     }
 3671:                 }
 3672:             } else {
 3673:                 foreach my $type (@types) {
 3674:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3675:                 }
 3676:             }
 3677:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 3678:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 3679:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 3680:                 }
 3681:             } else {
 3682:                 foreach my $type (@types) {
 3683:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 3684:                 }
 3685:             }
 3686:         } else {
 3687:             foreach my $type (@types) {
 3688:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3689:             }
 3690:         }
 3691:         if (!$currdefresponder) {
 3692:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 3693:         } elsif ($currdefresponder < 1) {
 3694:             $currdefresponder = 1;
 3695:         }
 3696:         foreach my $type (@types) {
 3697:             if ($curruploadquota{$type} eq '') {
 3698:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 3699:             }
 3700:         }
 3701:         $datatable .=
 3702:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 3703:                 $choices{'anonsurvey_threshold'}.
 3704:                 '</span></td>'.
 3705:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 3706:                 '<input type="text" name="anonsurvey_threshold"'.
 3707:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 3708:                 '</td></tr>'."\n";
 3709:         $itemcount ++;
 3710:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3711:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 3712:                       $choices{'uploadquota'}.
 3713:                       '</span></td>'.
 3714:                       '<td align="right" class="LC_right_item">'.
 3715:                       '<table><tr>';
 3716:         foreach my $type (@types) {
 3717:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 3718:                            '<input type="text" name="uploadquota_'.$type.'"'.
 3719:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 3720:         }
 3721:         $datatable .= '</tr></table></td></tr>'."\n";
 3722:         $itemcount ++;
 3723:         my $onclick = "toggleDisplay(this.form,'credits');";
 3724:         my $display = 'none';
 3725:         if ($currusecredits) {
 3726:             $display = 'block';
 3727:         }
 3728:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 3729:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 3730:         foreach my $type (@types) {
 3731:             next if ($type eq 'community');
 3732:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 3733:                            '<input type="text" name="'.$type.'_credits"'.
 3734:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 3735:         }
 3736:         $additional .= '</tr></table></div>'."\n";
 3737:         %defaultchecked = ('coursecredits' => 'off');
 3738:         @toggles = ('coursecredits');
 3739:         my $current = {
 3740:                         'coursecredits' => $currusecredits,
 3741:                       };
 3742:         (my $table,$itemcount) =
 3743:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 3744:                                \%choices,$itemcount,$onclick,$additional,'left');
 3745:         $datatable .= $table;
 3746:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 3747:         my $display = 'none';
 3748:         if ($postsubmitclient) {
 3749:             $display = 'block';
 3750:         }
 3751:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 3752:                       &mt('Number of seconds submit is disabled').'<br />'.
 3753:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 3754:                       '<table><tr>';
 3755:         foreach my $type (@types) {
 3756:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 3757:                            '<input type="text" name="'.$type.'_timeout" value="'.
 3758:                            $deftimeout{$type}.'" size="5" /></td>';
 3759:         }
 3760:         $additional .= '</tr></table></div>'."\n";
 3761:         %defaultchecked = ('postsubmit' => 'on');
 3762:         @toggles = ('postsubmit');
 3763:         $current = {
 3764:                        'postsubmit' => $postsubmitclient,
 3765:                    };
 3766:         ($table,$itemcount) =
 3767:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 3768:                                \%choices,$itemcount,$onclick,$additional,'left');
 3769:         $datatable .= $table;
 3770:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3771:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 3772:                       $choices{'mysqltables'}.
 3773:                       '</span></td>'.
 3774:                       '<td align="right" class="LC_right_item">'.
 3775:                       '<table><tr>';
 3776:         foreach my $type (@types) {
 3777:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 3778:                            '<input type="text" name="mysqltables_'.$type.'"'.
 3779:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 3780:         }
 3781:         $datatable .= '</tr></table></td></tr>'."\n";
 3782:         $itemcount ++;
 3783: 
 3784:     }
 3785:     $$rowtotal += $itemcount;
 3786:     return $datatable;
 3787: }
 3788: 
 3789: sub print_selfenrollment {
 3790:     my ($position,$dom,$settings,$rowtotal) = @_;
 3791:     my ($css_class,$datatable);
 3792:     my $itemcount = 1;
 3793:     my @types = ('official','unofficial','community','textbook');
 3794:     if (($position eq 'top') || ($position eq 'middle')) {
 3795:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 3796:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 3797:         my @rows;
 3798:         my $key;
 3799:         if ($position eq 'top') {
 3800:             $key = 'admin'; 
 3801:             if (ref($rowsref) eq 'ARRAY') {
 3802:                 @rows = @{$rowsref};
 3803:             }
 3804:         } elsif ($position eq 'middle') {
 3805:             $key = 'default';
 3806:             @rows = ('types','registered','approval','limit');
 3807:         }
 3808:         foreach my $row (@rows) {
 3809:             if (defined($titlesref->{$row})) {
 3810:                 $itemcount ++;
 3811:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3812:                 $datatable .= '<tr'.$css_class.'>'.
 3813:                               '<td>'.$titlesref->{$row}.'</td>'.
 3814:                               '<td class="LC_left_item">'.
 3815:                               '<table><tr>';
 3816:                 my (%current,%currentcap);
 3817:                 if (ref($settings) eq 'HASH') {
 3818:                     if (ref($settings->{$key}) eq 'HASH') {
 3819:                         foreach my $type (@types) {
 3820:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 3821:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 3822:                             }
 3823:                             if (($row eq 'limit') && ($key eq 'default')) {
 3824:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 3825:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 3826:                                 }
 3827:                             }
 3828:                         }
 3829:                     }
 3830:                 }
 3831:                 my %roles = (
 3832:                              '0' => &Apache::lonnet::plaintext('dc'),
 3833:                             ); 
 3834:             
 3835:                 foreach my $type (@types) {
 3836:                     unless (($row eq 'registered') && ($key eq 'default')) {
 3837:                         $datatable .= '<th>'.&mt($type).'</th>';
 3838:                     }
 3839:                 }
 3840:                 unless (($row eq 'registered') && ($key eq 'default')) {
 3841:                     $datatable .= '</tr><tr>';
 3842:                 }
 3843:                 foreach my $type (@types) {
 3844:                     if ($type eq 'community') {
 3845:                         $roles{'1'} = &mt('Community personnel');
 3846:                     } else {
 3847:                         $roles{'1'} = &mt('Course personnel');
 3848:                     }
 3849:                     $datatable .= '<td style="vertical-align: top">';
 3850:                     if ($position eq 'top') {
 3851:                         my %checked;
 3852:                         if ($current{$type} eq '0') {
 3853:                             $checked{'0'} = ' checked="checked"';
 3854:                         } else {
 3855:                             $checked{'1'} = ' checked="checked"';
 3856:                         }
 3857:                         foreach my $role ('1','0') {
 3858:                             $datatable .= '<span class="LC_nobreak"><label>'.
 3859:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 3860:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 3861:                                           $roles{$role}.'</label></span> ';
 3862:                         }
 3863:                     } else {
 3864:                         if ($row eq 'types') {
 3865:                             my %checked;
 3866:                             if ($current{$type} =~ /^(all|dom)$/) {
 3867:                                 $checked{$1} = ' checked="checked"';
 3868:                             } else {
 3869:                                 $checked{''} = ' checked="checked"';
 3870:                             }
 3871:                             foreach my $val ('','dom','all') {
 3872:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 3873:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 3874:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 3875:                             }
 3876:                         } elsif ($row eq 'registered') {
 3877:                             my %checked;
 3878:                             if ($current{$type} eq '1') {
 3879:                                 $checked{'1'} = ' checked="checked"';
 3880:                             } else {
 3881:                                 $checked{'0'} = ' checked="checked"';
 3882:                             }
 3883:                             foreach my $val ('0','1') {
 3884:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 3885:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 3886:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 3887:                             }
 3888:                         } elsif ($row eq 'approval') {
 3889:                             my %checked;
 3890:                             if ($current{$type} =~ /^([12])$/) {
 3891:                                 $checked{$1} = ' checked="checked"';
 3892:                             } else {
 3893:                                 $checked{'0'} = ' checked="checked"';
 3894:                             }
 3895:                             for my $val (0..2) {
 3896:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 3897:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 3898:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 3899:                             }
 3900:                         } elsif ($row eq 'limit') {
 3901:                             my %checked;
 3902:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 3903:                                 $checked{$1} = ' checked="checked"';
 3904:                             } else {
 3905:                                 $checked{'none'} = ' checked="checked"';
 3906:                             }
 3907:                             my $cap;
 3908:                             if ($currentcap{$type} =~ /^\d+$/) {
 3909:                                 $cap = $currentcap{$type};
 3910:                             }
 3911:                             foreach my $val ('none','allstudents','selfenrolled') {
 3912:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 3913:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 3914:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 3915:                             }
 3916:                             $datatable .= '<br />'.
 3917:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 3918:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 3919:                                           '</span>'; 
 3920:                         }
 3921:                     }
 3922:                     $datatable .= '</td>';
 3923:                 }
 3924:                 $datatable .= '</tr>';
 3925:             }
 3926:             $datatable .= '</table></td></tr>';
 3927:         }
 3928:     } elsif ($position eq 'bottom') {
 3929:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 3930:     }
 3931:     $$rowtotal += $itemcount;
 3932:     return $datatable;
 3933: }
 3934: 
 3935: sub print_validation_rows {
 3936:     my ($caller,$dom,$settings,$rowtotal) = @_;
 3937:     my ($itemsref,$namesref,$fieldsref);
 3938:     if ($caller eq 'selfenroll') { 
 3939:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 3940:     } elsif ($caller eq 'requestcourses') {
 3941:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 3942:     }
 3943:     my %currvalidation;
 3944:     if (ref($settings) eq 'HASH') {
 3945:         if (ref($settings->{'validation'}) eq 'HASH') {
 3946:             %currvalidation = %{$settings->{'validation'}};
 3947:         }
 3948:     }
 3949:     my $datatable;
 3950:     my $itemcount = 0;
 3951:     foreach my $item (@{$itemsref}) {
 3952:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3953:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 3954:                       $namesref->{$item}.
 3955:                       '</span></td>'.
 3956:                       '<td class="LC_left_item">';
 3957:         if (($item eq 'url') || ($item eq 'button')) {
 3958:             $datatable .= '<span class="LC_nobreak">'.
 3959:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 3960:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 3961:         } elsif ($item eq 'fields') {
 3962:             my @currfields;
 3963:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 3964:                 @currfields = @{$currvalidation{$item}};
 3965:             }
 3966:             foreach my $field (@{$fieldsref}) {
 3967:                 my $check = '';
 3968:                 if (grep(/^\Q$field\E$/,@currfields)) {
 3969:                     $check = ' checked="checked"';
 3970:                 }
 3971:                 $datatable .= '<span class="LC_nobreak"><label>'.
 3972:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 3973:                               ' value="'.$field.'"'.$check.' />'.$field.
 3974:                               '</label></span> ';
 3975:             }
 3976:         } elsif ($item eq 'markup') {
 3977:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 3978:                            $currvalidation{$item}.
 3979:                               '</textarea>';
 3980:         }
 3981:         $datatable .= '</td></tr>'."\n";
 3982:         if (ref($rowtotal)) {
 3983:             $itemcount ++;
 3984:         }
 3985:     }
 3986:     if ($caller eq 'requestcourses') {
 3987:         my %currhash;
 3988:         if (ref($settings) eq 'HASH') {
 3989:             if (ref($settings->{'validation'}) eq 'HASH') {
 3990:                 if ($settings->{'validation'}{'dc'} ne '') {
 3991:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 3992:                 }
 3993:             }
 3994:         }
 3995:         my $numinrow = 2;
 3996:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 3997:                                                        'validationdc',%currhash);
 3998:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3999:         $datatable .= '<tr'.$css_class.'><td>';
 4000:         if ($numdc > 1) {
 4001:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 4002:         } else {
 4003:             $datatable .=  &mt('Course creation processed as: ');
 4004:         }
 4005:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 4006:         $itemcount ++;
 4007:     }
 4008:     if (ref($rowtotal)) {
 4009:         $$rowtotal += $itemcount;
 4010:     }
 4011:     return $datatable;
 4012: }
 4013: 
 4014: sub print_usersessions {
 4015:     my ($position,$dom,$settings,$rowtotal) = @_;
 4016:     my ($css_class,$datatable,%checked,%choices);
 4017:     my (%by_ip,%by_location,@intdoms);
 4018:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
 4019: 
 4020:     my @alldoms = &Apache::lonnet::all_domains();
 4021:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 4022:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 4023:     my %altids = &id_for_thisdom(%servers);
 4024:     my $itemcount = 1;
 4025:     if ($position eq 'top') {
 4026:         if (keys(%serverhomes) > 1) {
 4027:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 4028:             my $curroffloadnow;
 4029:             if (ref($settings) eq 'HASH') {
 4030:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 4031:                     $curroffloadnow = $settings->{'offloadnow'};
 4032:                 }
 4033:             }
 4034:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,$curroffloadnow,$rowtotal);
 4035:         } else {
 4036:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 4037:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.');
 4038:         }
 4039:     } else {
 4040:         if (keys(%by_location) == 0) {
 4041:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 4042:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.');
 4043:         } else {
 4044:             my %lt = &usersession_titles();
 4045:             my $numinrow = 5;
 4046:             my $prefix;
 4047:             my @types;
 4048:             if ($position eq 'bottom') {
 4049:                 $prefix = 'remote';
 4050:                 @types = ('version','excludedomain','includedomain');
 4051:             } else {
 4052:                 $prefix = 'hosted';
 4053:                 @types = ('excludedomain','includedomain');
 4054:             }
 4055:             my (%current,%checkedon,%checkedoff);
 4056:             my @lcversions = &Apache::lonnet::all_loncaparevs();
 4057:             my @locations = sort(keys(%by_location));
 4058:             foreach my $type (@types) {
 4059:                 $checkedon{$type} = '';
 4060:                 $checkedoff{$type} = ' checked="checked"';
 4061:             }
 4062:             if (ref($settings) eq 'HASH') {
 4063:                 if (ref($settings->{$prefix}) eq 'HASH') {
 4064:                     foreach my $key (keys(%{$settings->{$prefix}})) {
 4065:                         $current{$key} = $settings->{$prefix}{$key};
 4066:                         if ($key eq 'version') {
 4067:                             if ($current{$key} ne '') {
 4068:                                 $checkedon{$key} = ' checked="checked"';
 4069:                                 $checkedoff{$key} = '';
 4070:                             }
 4071:                         } elsif (ref($current{$key}) eq 'ARRAY') {
 4072:                             $checkedon{$key} = ' checked="checked"';
 4073:                             $checkedoff{$key} = '';
 4074:                         }
 4075:                     }
 4076:                 }
 4077:             }
 4078:             foreach my $type (@types) {
 4079:                 next if ($type ne 'version' && !@locations);
 4080:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4081:                 $datatable .= '<tr'.$css_class.'>
 4082:                                <td><span class="LC_nobreak">'.$lt{$type}.'</span><br />
 4083:                                <span class="LC_nobreak">&nbsp;
 4084:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 4085:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 4086:                 if ($type eq 'version') {
 4087:                     my $selector = '<select name="'.$prefix.'_version">';
 4088:                     foreach my $version (@lcversions) {
 4089:                         my $selected = '';
 4090:                         if ($current{'version'} eq $version) {
 4091:                             $selected = ' selected="selected"';
 4092:                         }
 4093:                         $selector .= ' <option value="'.$version.'"'.
 4094:                                      $selected.'>'.$version.'</option>';
 4095:                     }
 4096:                     $selector .= '</select> ';
 4097:                     $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 4098:                 } else {
 4099:                     $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 4100:                                  'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 4101:                                  ' />'.('&nbsp;'x2).
 4102:                                  '<input type="button" value="'.&mt('uncheck all').'" '.
 4103:                                  'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 4104:                                  "\n".
 4105:                                  '</div><div><table>';
 4106:                     my $rem;
 4107:                     for (my $i=0; $i<@locations; $i++) {
 4108:                         my ($showloc,$value,$checkedtype);
 4109:                         if (ref($by_location{$locations[$i]}) eq 'ARRAY') {
 4110:                             my $ip = $by_location{$locations[$i]}->[0];
 4111:                             if (ref($by_ip{$ip}) eq 'ARRAY') {
 4112:                                  $value = join(':',@{$by_ip{$ip}});
 4113:                                 $showloc = join(', ',@{$by_ip{$ip}});
 4114:                                 if (ref($current{$type}) eq 'ARRAY') {
 4115:                                     foreach my $loc (@{$by_ip{$ip}}) {  
 4116:                                         if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 4117:                                             $checkedtype = ' checked="checked"';
 4118:                                             last;
 4119:                                         }
 4120:                                     }
 4121:                                 }
 4122:                             }
 4123:                         }
 4124:                         $rem = $i%($numinrow);
 4125:                         if ($rem == 0) {
 4126:                             if ($i > 0) {
 4127:                                 $datatable .= '</tr>';
 4128:                             }
 4129:                             $datatable .= '<tr>';
 4130:                         }
 4131:                         $datatable .= '<td class="LC_left_item">'.
 4132:                                       '<span class="LC_nobreak"><label>'.
 4133:                                       '<input type="checkbox" name="'.$prefix.'_'.$type.
 4134:                                       '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 4135:                                       '</label></span></td>';
 4136:                     }
 4137:                     $rem = @locations%($numinrow);
 4138:                     my $colsleft = $numinrow - $rem;
 4139:                     if ($colsleft > 1 ) {
 4140:                         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4141:                                       '&nbsp;</td>';
 4142:                     } elsif ($colsleft == 1) {
 4143:                         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 4144:                     }
 4145:                     $datatable .= '</tr></table>';
 4146:                 }
 4147:                 $datatable .= '</td></tr>';
 4148:                 $itemcount ++;
 4149:             }
 4150:         }
 4151:     }
 4152:     $$rowtotal += $itemcount;
 4153:     return $datatable;
 4154: }
 4155: 
 4156: sub build_location_hashes {
 4157:     my ($intdoms,$by_ip,$by_location) = @_;
 4158:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 4159:                   (ref($by_location) eq 'HASH')); 
 4160:     my %iphost = &Apache::lonnet::get_iphost();
 4161:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 4162:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 4163:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 4164:         foreach my $id (@{$iphost{$primary_ip}}) {
 4165:             my $intdom = &Apache::lonnet::internet_dom($id);
 4166:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 4167:                 push(@{$intdoms},$intdom);
 4168:             }
 4169:         }
 4170:     }
 4171:     foreach my $ip (keys(%iphost)) {
 4172:         if (ref($iphost{$ip}) eq 'ARRAY') {
 4173:             foreach my $id (@{$iphost{$ip}}) {
 4174:                 my $location = &Apache::lonnet::internet_dom($id);
 4175:                 if ($location) {
 4176:                     next if (grep(/^\Q$location\E$/,@{$intdoms}));
 4177:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 4178:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 4179:                             push(@{$by_ip->{$ip}},$location);
 4180:                         }
 4181:                     } else {
 4182:                         $by_ip->{$ip} = [$location];
 4183:                     }
 4184:                 }
 4185:             }
 4186:         }
 4187:     }
 4188:     foreach my $ip (sort(keys(%{$by_ip}))) {
 4189:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 4190:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 4191:             my $first = $by_ip->{$ip}->[0];
 4192:             if (ref($by_location->{$first}) eq 'ARRAY') {
 4193:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 4194:                     push(@{$by_location->{$first}},$ip);
 4195:                 }
 4196:             } else {
 4197:                 $by_location->{$first} = [$ip];
 4198:             }
 4199:         }
 4200:     }
 4201:     return;
 4202: }
 4203: 
 4204: sub current_offloads_to {
 4205:     my ($dom,$settings,$servers) = @_;
 4206:     my (%spareid,%otherdomconfigs);
 4207:     if (ref($servers) eq 'HASH') {
 4208:         foreach my $lonhost (sort(keys(%{$servers}))) {
 4209:             my $gotspares;
 4210:             if (ref($settings) eq 'HASH') {
 4211:                 if (ref($settings->{'spares'}) eq 'HASH') {
 4212:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 4213:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 4214:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 4215:                         $gotspares = 1;
 4216:                     }
 4217:                 }
 4218:             }
 4219:             unless ($gotspares) {
 4220:                 my $gotspares;
 4221:                 my $serverhomeID =
 4222:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 4223:                 my $serverhomedom =
 4224:                     &Apache::lonnet::host_domain($serverhomeID);
 4225:                 if ($serverhomedom ne $dom) {
 4226:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 4227:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 4228:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 4229:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 4230:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 4231:                                 $gotspares = 1;
 4232:                             }
 4233:                         }
 4234:                     } else {
 4235:                         $otherdomconfigs{$serverhomedom} =
 4236:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 4237:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 4238:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 4239:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 4240:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 4241:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 4242:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 4243:                                         $gotspares = 1;
 4244:                                     }
 4245:                                 }
 4246:                             }
 4247:                         }
 4248:                     }
 4249:                 }
 4250:             }
 4251:             unless ($gotspares) {
 4252:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 4253:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 4254:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 4255:                } else {
 4256:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 4257:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 4258:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 4259:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 4260:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 4261:                     } else {
 4262:                         my %what = (
 4263:                              spareid => 1,
 4264:                         );
 4265:                         my ($result,$returnhash) = 
 4266:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 4267:                         if ($result eq 'ok') { 
 4268:                             if (ref($returnhash) eq 'HASH') {
 4269:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 4270:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 4271:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 4272:                                 }
 4273:                             }
 4274:                         }
 4275:                     }
 4276:                 }
 4277:             }
 4278:         }
 4279:     }
 4280:     return %spareid;
 4281: }
 4282: 
 4283: sub spares_row {
 4284:     my ($dom,$servers,$spareid,$serverhomes,$altids,$curroffloadnow,$rowtotal) = @_;
 4285:     my $css_class;
 4286:     my $numinrow = 4;
 4287:     my $itemcount = 1;
 4288:     my $datatable;
 4289:     my %typetitles = &sparestype_titles();
 4290:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 4291:         foreach my $server (sort(keys(%{$servers}))) {
 4292:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 4293:             my ($othercontrol,$serverdom);
 4294:             if ($serverhome ne $server) {
 4295:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 4296:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 4297:             } else {
 4298:                 $serverdom = &Apache::lonnet::host_domain($server);
 4299:                 if ($serverdom ne $dom) {
 4300:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 4301:                 }
 4302:             }
 4303:             next unless (ref($spareid->{$server}) eq 'HASH');
 4304:             my $checkednow;
 4305:             if (ref($curroffloadnow) eq 'HASH') {
 4306:                 if ($curroffloadnow->{$server}) {
 4307:                     $checkednow = ' checked="checked"';
 4308:                 }
 4309:             }
 4310:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4311:             $datatable .= '<tr'.$css_class.'>
 4312:                            <td rowspan="2">
 4313:                             <span class="LC_nobreak">'.
 4314:                           &mt('[_1] when busy, offloads to:'
 4315:                               ,'<b>'.$server.'</b>').'</span><br />'.
 4316:                           '<span class="LC_nobreak">'."\n".
 4317:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 4318:                           '&nbsp;'.&mt('Switch active users on next access').'</label></span>'.
 4319:                           "\n";
 4320:             my (%current,%canselect);
 4321:             my @choices = 
 4322:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 4323:             foreach my $type ('primary','default') {
 4324:                 if (ref($spareid->{$server}) eq 'HASH') {
 4325:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 4326:                         my @spares = @{$spareid->{$server}{$type}};
 4327:                         if (@spares > 0) {
 4328:                             if ($othercontrol) {
 4329:                                 $current{$type} = join(', ',@spares);
 4330:                             } else {
 4331:                                 $current{$type} .= '<table>';
 4332:                                 my $numspares = scalar(@spares);
 4333:                                 for (my $i=0;  $i<@spares; $i++) {
 4334:                                     my $rem = $i%($numinrow);
 4335:                                     if ($rem == 0) {
 4336:                                         if ($i > 0) {
 4337:                                             $current{$type} .= '</tr>';
 4338:                                         }
 4339:                                         $current{$type} .= '<tr>';
 4340:                                     }
 4341:                                     $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;'.
 4342:                                                        $spareid->{$server}{$type}[$i].
 4343:                                                        '</label></td>'."\n";
 4344:                                 }
 4345:                                 my $rem = @spares%($numinrow);
 4346:                                 my $colsleft = $numinrow - $rem;
 4347:                                 if ($colsleft > 1 ) {
 4348:                                     $current{$type} .= '<td colspan="'.$colsleft.
 4349:                                                        '" class="LC_left_item">'.
 4350:                                                        '&nbsp;</td>';
 4351:                                 } elsif ($colsleft == 1) {
 4352:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 4353:                                 }
 4354:                                 $current{$type} .= '</tr></table>';
 4355:                             }
 4356:                         }
 4357:                     }
 4358:                     if ($current{$type} eq '') {
 4359:                         $current{$type} = &mt('None specified');
 4360:                     }
 4361:                     if ($othercontrol) {
 4362:                         if ($type eq 'primary') {
 4363:                             $canselect{$type} = $othercontrol;
 4364:                         }
 4365:                     } else {
 4366:                         $canselect{$type} = 
 4367:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 4368:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 4369:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 4370:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 4371:                         if (@choices > 0) {
 4372:                             foreach my $lonhost (@choices) {
 4373:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 4374:                             }
 4375:                         }
 4376:                         $canselect{$type} .= '</select>'."\n";
 4377:                     }
 4378:                 } else {
 4379:                     $current{$type} = &mt('Could not be determined');
 4380:                     if ($type eq 'primary') {
 4381:                         $canselect{$type} =  $othercontrol;
 4382:                     }
 4383:                 }
 4384:                 if ($type eq 'default') {
 4385:                     $datatable .= '<tr'.$css_class.'>';
 4386:                 }
 4387:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 4388:                               '<td>'.$current{$type}.'</td>'."\n".
 4389:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 4390:             }
 4391:             $itemcount ++;
 4392:         }
 4393:     }
 4394:     $$rowtotal += $itemcount;
 4395:     return $datatable;
 4396: }
 4397: 
 4398: sub possible_newspares {
 4399:     my ($server,$currspares,$serverhomes,$altids) = @_;
 4400:     my $serverhostname = &Apache::lonnet::hostname($server);
 4401:     my %excluded;
 4402:     if ($serverhostname ne '') {
 4403:         %excluded = (
 4404:                        $serverhostname => 1,
 4405:                     );
 4406:     }
 4407:     if (ref($currspares) eq 'HASH') {
 4408:         foreach my $type (keys(%{$currspares})) {
 4409:             if (ref($currspares->{$type}) eq 'ARRAY') {
 4410:                 if (@{$currspares->{$type}} > 0) {
 4411:                     foreach my $curr (@{$currspares->{$type}}) {
 4412:                         my $hostname = &Apache::lonnet::hostname($curr);
 4413:                         $excluded{$hostname} = 1;
 4414:                     }
 4415:                 }
 4416:             }
 4417:         }
 4418:     }
 4419:     my @choices;
 4420:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 4421:         if (keys(%{$serverhomes}) > 1) {
 4422:             foreach my $name (sort(keys(%{$serverhomes}))) {
 4423:                 unless ($excluded{$name}) {
 4424:                     if (exists($altids->{$serverhomes->{$name}})) {
 4425:                         push(@choices,$altids->{$serverhomes->{$name}});
 4426:                     } else {
 4427:                         push(@choices,$serverhomes->{$name});
 4428:                     }
 4429:                 }
 4430:             }
 4431:         }
 4432:     }
 4433:     return sort(@choices);
 4434: }
 4435: 
 4436: sub print_loadbalancing {
 4437:     my ($dom,$settings,$rowtotal) = @_;
 4438:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 4439:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 4440:     my $numinrow = 1;
 4441:     my $datatable;
 4442:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 4443:     my (%currbalancer,%currtargets,%currrules,%existing);
 4444:     if (ref($settings) eq 'HASH') {
 4445:         %existing = %{$settings};
 4446:     }
 4447:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 4448:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 4449:                                   \%currtargets,\%currrules);
 4450:     } else {
 4451:         return;
 4452:     }
 4453:     my ($othertitle,$usertypes,$types) =
 4454:         &Apache::loncommon::sorted_inst_types($dom);
 4455:     my $rownum = 8;
 4456:     if (ref($types) eq 'ARRAY') {
 4457:         $rownum += scalar(@{$types});
 4458:     }
 4459:     my @css_class = ('LC_odd_row','LC_even_row');
 4460:     my $balnum = 0;
 4461:     my $islast;
 4462:     my (@toshow,$disabledtext);
 4463:     if (keys(%currbalancer) > 0) {
 4464:         @toshow = sort(keys(%currbalancer));
 4465:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 4466:             push(@toshow,'');
 4467:         }
 4468:     } else {
 4469:         @toshow = ('');
 4470:         $disabledtext = &mt('No existing load balancer');
 4471:     }
 4472:     foreach my $lonhost (@toshow) {
 4473:         if ($balnum == scalar(@toshow)-1) {
 4474:             $islast = 1;
 4475:         } else {
 4476:             $islast = 0;
 4477:         }
 4478:         my $cssidx = $balnum%2;
 4479:         my $targets_div_style = 'display: none';
 4480:         my $disabled_div_style = 'display: block';
 4481:         my $homedom_div_style = 'display: none';
 4482:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 4483:                       '<td rowspan="'.$rownum.'" valign="top">'.
 4484:                       '<p>';
 4485:         if ($lonhost eq '') {
 4486:             $datatable .= '<span class="LC_nobreak">';
 4487:             if (keys(%currbalancer) > 0) {
 4488:                 $datatable .= &mt('Add balancer:');
 4489:             } else {
 4490:                 $datatable .= &mt('Enable balancer:');
 4491:             }
 4492:             $datatable .= '&nbsp;'.
 4493:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 4494:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 4495:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 4496:                           '<option value="" selected="selected">'.&mt('None').
 4497:                           '</option>'."\n";
 4498:             foreach my $server (sort(keys(%servers))) {
 4499:                 next if ($currbalancer{$server});
 4500:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 4501:             }
 4502:             $datatable .=
 4503:                 '</select>'."\n".
 4504:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 4505:         } else {
 4506:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 4507:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 4508:                            &mt('Stop balancing').'</label>'.
 4509:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 4510:             $targets_div_style = 'display: block';
 4511:             $disabled_div_style = 'display: none';
 4512:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 4513:                 $homedom_div_style = 'display: block';
 4514:             }
 4515:         }
 4516:         $datatable .= '</p></td><td rowspan="'.$rownum.'" valign="top">'.
 4517:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 4518:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 4519:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 4520:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 4521:         my @sparestypes = ('primary','default');
 4522:         my %typetitles = &sparestype_titles();
 4523:         my %hostherechecked = (
 4524:                                   no => ' checked="checked"',
 4525:                               );
 4526:         foreach my $sparetype (@sparestypes) {
 4527:             my $targettable;
 4528:             for (my $i=0; $i<$numspares; $i++) {
 4529:                 my $checked;
 4530:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 4531:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 4532:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 4533:                             $checked = ' checked="checked"';
 4534:                         }
 4535:                     }
 4536:                 }
 4537:                 my ($chkboxval,$disabled);
 4538:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 4539:                     $chkboxval = $spares[$i];
 4540:                 }
 4541:                 if (exists($currbalancer{$spares[$i]})) {
 4542:                     $disabled = ' disabled="disabled"';
 4543:                 }
 4544:                 $targettable .=
 4545:                     '<td><span class="LC_nobreak"><label>'.
 4546:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 4547:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 4548:                     '</span></label></span></td>';
 4549:                 my $rem = $i%($numinrow);
 4550:                 if ($rem == 0) {
 4551:                     if (($i > 0) && ($i < $numspares-1)) {
 4552:                         $targettable .= '</tr>';
 4553:                     }
 4554:                     if ($i < $numspares-1) {
 4555:                         $targettable .= '<tr>';
 4556:                     }
 4557:                 }
 4558:             }
 4559:             if ($targettable ne '') {
 4560:                 my $rem = $numspares%($numinrow);
 4561:                 my $colsleft = $numinrow - $rem;
 4562:                 if ($colsleft > 1 ) {
 4563:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4564:                                     '&nbsp;</td>';
 4565:                 } elsif ($colsleft == 1) {
 4566:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 4567:                 }
 4568:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 4569:                                '<table><tr>'.$targettable.'</tr></table><br />';
 4570:             }
 4571:             $hostherechecked{$sparetype} = '';
 4572:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 4573:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 4574:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 4575:                         $hostherechecked{$sparetype} = ' checked="checked"';
 4576:                         $hostherechecked{'no'} = '';
 4577:                     }
 4578:                 }
 4579:             }
 4580:         }
 4581:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 4582:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 4583:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 4584:         foreach my $sparetype (@sparestypes) {
 4585:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 4586:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 4587:                           '</i></label><br />';
 4588:         }
 4589:         $datatable .= '</div></td></tr>'.
 4590:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 4591:                                            $othertitle,$usertypes,$types,\%servers,
 4592:                                            \%currbalancer,$lonhost,
 4593:                                            $targets_div_style,$homedom_div_style,
 4594:                                            $css_class[$cssidx],$balnum,$islast);
 4595:         $$rowtotal += $rownum;
 4596:         $balnum ++;
 4597:     }
 4598:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 4599:     return $datatable;
 4600: }
 4601: 
 4602: sub get_loadbalancers_config {
 4603:     my ($servers,$existing,$currbalancer,$currtargets,$currrules) = @_;
 4604:     return unless ((ref($servers) eq 'HASH') &&
 4605:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 4606:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH'));
 4607:     if (keys(%{$existing}) > 0) {
 4608:         my $oldlonhost;
 4609:         foreach my $key (sort(keys(%{$existing}))) {
 4610:             if ($key eq 'lonhost') {
 4611:                 $oldlonhost = $existing->{'lonhost'};
 4612:                 $currbalancer->{$oldlonhost} = 1;
 4613:             } elsif ($key eq 'targets') {
 4614:                 if ($oldlonhost) {
 4615:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 4616:                 }
 4617:             } elsif ($key eq 'rules') {
 4618:                 if ($oldlonhost) {
 4619:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 4620:                 }
 4621:             } elsif (ref($existing->{$key}) eq 'HASH') {
 4622:                 $currbalancer->{$key} = 1;
 4623:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 4624:                 $currrules->{$key} = $existing->{$key}{'rules'};
 4625:             }
 4626:         }
 4627:     } else {
 4628:         my ($balancerref,$targetsref) =
 4629:                 &Apache::lonnet::get_lonbalancer_config($servers);
 4630:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 4631:             foreach my $server (sort(keys(%{$balancerref}))) {
 4632:                 $currbalancer->{$server} = 1;
 4633:                 $currtargets->{$server} = $targetsref->{$server};
 4634:             }
 4635:         }
 4636:     }
 4637:     return;
 4638: }
 4639: 
 4640: sub loadbalancing_rules {
 4641:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 4642:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 4643:         $css_class,$balnum,$islast) = @_;
 4644:     my $output;
 4645:     my $num = 0;
 4646:     my ($alltypes,$othertypes,$titles) =
 4647:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 4648:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 4649:         foreach my $type (@{$alltypes}) {
 4650:             $num ++;
 4651:             my $current;
 4652:             if (ref($currrules) eq 'HASH') {
 4653:                 $current = $currrules->{$type};
 4654:             }
 4655:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 4656:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 4657:                     $current = '';
 4658:                 }
 4659:             }
 4660:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 4661:                                              $servers,$currbalancer,$lonhost,$dom,
 4662:                                              $targets_div_style,$homedom_div_style,
 4663:                                              $css_class,$balnum,$num,$islast);
 4664:         }
 4665:     }
 4666:     return $output;
 4667: }
 4668: 
 4669: sub loadbalancing_titles {
 4670:     my ($dom,$intdom,$usertypes,$types) = @_;
 4671:     my %othertypes = (
 4672:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 4673:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 4674:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 4675:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 4676:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 4677:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 4678:                      );
 4679:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 4680:     my @available;
 4681:     if (ref($types) eq 'ARRAY') {
 4682:         @available = @{$types};
 4683:     }
 4684:     unless (grep(/^default$/,@available)) {
 4685:         push(@available,'default');
 4686:     }
 4687:     unshift(@alltypes,@available);
 4688:     my %titles;
 4689:     foreach my $type (@alltypes) {
 4690:         if ($type =~ /^_LC_/) {
 4691:             $titles{$type} = $othertypes{$type};
 4692:         } elsif ($type eq 'default') {
 4693:             $titles{$type} = &mt('All users from [_1]',$dom);
 4694:             if (ref($types) eq 'ARRAY') {
 4695:                 if (@{$types} > 0) {
 4696:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 4697:                 }
 4698:             }
 4699:         } elsif (ref($usertypes) eq 'HASH') {
 4700:             $titles{$type} = $usertypes->{$type};
 4701:         }
 4702:     }
 4703:     return (\@alltypes,\%othertypes,\%titles);
 4704: }
 4705: 
 4706: sub loadbalance_rule_row {
 4707:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 4708:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 4709:     my @rulenames;
 4710:     my %ruletitles = &offloadtype_text();
 4711:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 4712:         @rulenames = ('balancer','offloadedto','specific');
 4713:     } else {
 4714:         @rulenames = ('default','homeserver');
 4715:         if ($type eq '_LC_external') {
 4716:             push(@rulenames,'externalbalancer');
 4717:         } else {
 4718:             push(@rulenames,'specific');
 4719:         }
 4720:         push(@rulenames,'none');
 4721:     }
 4722:     my $style = $targets_div_style;
 4723:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 4724:         $style = $homedom_div_style;
 4725:     }
 4726:     my $space;
 4727:     if ($islast && $num == 1) {
 4728:         $space = '<div display="inline-block">&nbsp;</div>';
 4729:     }
 4730:     my $output =
 4731:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td valign="top">'.$space.
 4732:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 4733:         '<td valaign="top">'.$space.
 4734:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 4735:     for (my $i=0; $i<@rulenames; $i++) {
 4736:         my $rule = $rulenames[$i];
 4737:         my ($checked,$extra);
 4738:         if ($rulenames[$i] eq 'default') {
 4739:             $rule = '';
 4740:         }
 4741:         if ($rulenames[$i] eq 'specific') {
 4742:             if (ref($servers) eq 'HASH') {
 4743:                 my $default;
 4744:                 if (($current ne '') && (exists($servers->{$current}))) {
 4745:                     $checked = ' checked="checked"';
 4746:                 }
 4747:                 unless ($checked) {
 4748:                     $default = ' selected="selected"';
 4749:                 }
 4750:                 $extra =
 4751:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 4752:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 4753:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 4754:                     '<option value=""'.$default.'></option>'."\n";
 4755:                 foreach my $server (sort(keys(%{$servers}))) {
 4756:                     if (ref($currbalancer) eq 'HASH') {
 4757:                         next if (exists($currbalancer->{$server}));
 4758:                     }
 4759:                     my $selected;
 4760:                     if ($server eq $current) {
 4761:                         $selected = ' selected="selected"';
 4762:                     }
 4763:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 4764:                 }
 4765:                 $extra .= '</select>';
 4766:             }
 4767:         } elsif ($rule eq $current) {
 4768:             $checked = ' checked="checked"';
 4769:         }
 4770:         $output .= '<span class="LC_nobreak"><label>'.
 4771:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 4772:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 4773:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 4774:                    ')"'.$checked.' />&nbsp;';
 4775:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 4776:             $output .= $ruletitles{'particular'};
 4777:         } else {
 4778:             $output .= $ruletitles{$rulenames[$i]};
 4779:         }
 4780:         $output .= '</label>'.$extra.'</span><br />'."\n";
 4781:     }
 4782:     $output .= '</div></td></tr>'."\n";
 4783:     return $output;
 4784: }
 4785: 
 4786: sub offloadtype_text {
 4787:     my %ruletitles = &Apache::lonlocal::texthash (
 4788:            'default'          => 'Offloads to default destinations',
 4789:            'homeserver'       => "Offloads to user's home server",
 4790:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 4791:            'specific'         => 'Offloads to specific server',
 4792:            'none'             => 'No offload',
 4793:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 4794:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 4795:            'particular'       => 'Session hosted (after re-auth) on server:',
 4796:     );
 4797:     return %ruletitles;
 4798: }
 4799: 
 4800: sub sparestype_titles {
 4801:     my %typestitles = &Apache::lonlocal::texthash (
 4802:                           'primary' => 'primary',
 4803:                           'default' => 'default',
 4804:                       );
 4805:     return %typestitles;
 4806: }
 4807: 
 4808: sub contact_titles {
 4809:     my %titles = &Apache::lonlocal::texthash (
 4810:                    'supportemail'    => 'Support E-mail address',
 4811:                    'adminemail'      => 'Default Server Admin E-mail address',
 4812:                    'errormail'       => 'Error reports to be e-mailed to',
 4813:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 4814:                    'helpdeskmail'    => "Helpdesk requests for this domain's users",
 4815:                    'otherdomsmail'   => 'Helpdesk requests for other (unconfigured) domains',
 4816:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 4817:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 4818:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 4819:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 4820:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 4821:                  );
 4822:     my %short_titles = &Apache::lonlocal::texthash (
 4823:                            adminemail   => 'Admin E-mail address',
 4824:                            supportemail => 'Support E-mail',
 4825:                        );   
 4826:     return (\%titles,\%short_titles);
 4827: }
 4828: 
 4829: sub helpform_fields {
 4830:     my %titles =  &Apache::lonlocal::texthash (
 4831:                        'username'   => 'Name',
 4832:                        'user'       => 'Username/domain',
 4833:                        'phone'      => 'Phone',
 4834:                        'cc'         => 'Cc e-mail',
 4835:                        'course'     => 'Course Details',
 4836:                        'section'    => 'Sections',
 4837:                        'screenshot' => 'File upload',
 4838:     );
 4839:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 4840:     my %possoptions = (
 4841:                         username     => ['yes','no','req'],
 4842:                         phone        => ['yes','no','req'],
 4843:                         user         => ['yes','no'],
 4844:                         cc           => ['yes','no'],
 4845:                         course       => ['yes','no'],
 4846:                         section      => ['yes','no'],
 4847:                         screenshot   => ['yes','no'],
 4848:                       );
 4849:     my %fieldoptions = &Apache::lonlocal::texthash (
 4850:                          'yes'  => 'Optional',
 4851:                          'req'  => 'Required',
 4852:                          'no'   => "Not shown",
 4853:     );
 4854:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 4855: }
 4856: 
 4857: sub tool_titles {
 4858:     my %titles = &Apache::lonlocal::texthash (
 4859:                      aboutme    => 'Personal web page',
 4860:                      blog       => 'Blog',
 4861:                      webdav     => 'WebDAV',
 4862:                      portfolio  => 'Portfolio',
 4863:                      official   => 'Official courses (with institutional codes)',
 4864:                      unofficial => 'Unofficial courses',
 4865:                      community  => 'Communities',
 4866:                      textbook   => 'Textbook courses',
 4867:                  );
 4868:     return %titles;
 4869: }
 4870: 
 4871: sub courserequest_titles {
 4872:     my %titles = &Apache::lonlocal::texthash (
 4873:                                    official   => 'Official',
 4874:                                    unofficial => 'Unofficial',
 4875:                                    community  => 'Communities',
 4876:                                    textbook   => 'Textbook',
 4877:                                    norequest  => 'Not allowed',
 4878:                                    approval   => 'Approval by Dom. Coord.',
 4879:                                    validate   => 'With validation',
 4880:                                    autolimit  => 'Numerical limit',
 4881:                                    unlimited  => '(blank for unlimited)',
 4882:                  );
 4883:     return %titles;
 4884: }
 4885: 
 4886: sub authorrequest_titles {
 4887:     my %titles = &Apache::lonlocal::texthash (
 4888:                                    norequest  => 'Not allowed',
 4889:                                    approval   => 'Approval by Dom. Coord.',
 4890:                                    automatic  => 'Automatic approval',
 4891:                  );
 4892:     return %titles;
 4893: }
 4894: 
 4895: sub courserequest_conditions {
 4896:     my %conditions = &Apache::lonlocal::texthash (
 4897:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 4898:        validate   => '(Processing of request subject to institutional validation).',
 4899:                  );
 4900:     return %conditions;
 4901: }
 4902: 
 4903: 
 4904: sub print_usercreation {
 4905:     my ($position,$dom,$settings,$rowtotal) = @_;
 4906:     my $numinrow = 4;
 4907:     my $datatable;
 4908:     if ($position eq 'top') {
 4909:         $$rowtotal ++;
 4910:         my $rowcount = 0;
 4911:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 4912:         if (ref($rules) eq 'HASH') {
 4913:             if (keys(%{$rules}) > 0) {
 4914:                 $datatable .= &user_formats_row('username',$settings,$rules,
 4915:                                                 $ruleorder,$numinrow,$rowcount);
 4916:                 $$rowtotal ++;
 4917:                 $rowcount ++;
 4918:             }
 4919:         }
 4920:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 4921:         if (ref($idrules) eq 'HASH') {
 4922:             if (keys(%{$idrules}) > 0) {
 4923:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 4924:                                                 $idruleorder,$numinrow,$rowcount);
 4925:                 $$rowtotal ++;
 4926:                 $rowcount ++;
 4927:             }
 4928:         }
 4929:         if ($rowcount == 0) {
 4930:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 4931:             $$rowtotal ++;
 4932:             $rowcount ++;
 4933:         }
 4934:     } elsif ($position eq 'middle') {
 4935:         my @creators = ('author','course','requestcrs');
 4936:         my ($rules,$ruleorder) =
 4937:             &Apache::lonnet::inst_userrules($dom,'username');
 4938:         my %lt = &usercreation_types();
 4939:         my %checked;
 4940:         if (ref($settings) eq 'HASH') {
 4941:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 4942:                 foreach my $item (@creators) {
 4943:                     $checked{$item} = $settings->{'cancreate'}{$item};
 4944:                 }
 4945:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 4946:                 foreach my $item (@creators) {
 4947:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 4948:                         $checked{$item} = 'none';
 4949:                     }
 4950:                 }
 4951:             }
 4952:         }
 4953:         my $rownum = 0;
 4954:         foreach my $item (@creators) {
 4955:             $rownum ++;
 4956:             if ($checked{$item} eq '') {
 4957:                 $checked{$item} = 'any';
 4958:             }
 4959:             my $css_class;
 4960:             if ($rownum%2) {
 4961:                 $css_class = '';
 4962:             } else {
 4963:                 $css_class = ' class="LC_odd_row" ';
 4964:             }
 4965:             $datatable .= '<tr'.$css_class.'>'.
 4966:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 4967:                          '</span></td><td align="right">';
 4968:             my @options = ('any');
 4969:             if (ref($rules) eq 'HASH') {
 4970:                 if (keys(%{$rules}) > 0) {
 4971:                     push(@options,('official','unofficial'));
 4972:                 }
 4973:             }
 4974:             push(@options,'none');
 4975:             foreach my $option (@options) {
 4976:                 my $type = 'radio';
 4977:                 my $check = ' ';
 4978:                 if ($checked{$item} eq $option) {
 4979:                     $check = ' checked="checked" ';
 4980:                 } 
 4981:                 $datatable .= '<span class="LC_nobreak"><label>'.
 4982:                               '<input type="'.$type.'" name="can_createuser_'.
 4983:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 4984:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 4985:             }
 4986:             $datatable .= '</td></tr>';
 4987:         }
 4988:     } else {
 4989:         my @contexts = ('author','course','domain');
 4990:         my @authtypes = ('int','krb4','krb5','loc');
 4991:         my %checked;
 4992:         if (ref($settings) eq 'HASH') {
 4993:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 4994:                 foreach my $item (@contexts) {
 4995:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 4996:                         foreach my $auth (@authtypes) {
 4997:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 4998:                                 $checked{$item}{$auth} = ' checked="checked" ';
 4999:                             }
 5000:                         }
 5001:                     }
 5002:                 }
 5003:             }
 5004:         } else {
 5005:             foreach my $item (@contexts) {
 5006:                 foreach my $auth (@authtypes) {
 5007:                     $checked{$item}{$auth} = ' checked="checked" ';
 5008:                 }
 5009:             }
 5010:         }
 5011:         my %title = &context_names();
 5012:         my %authname = &authtype_names();
 5013:         my $rownum = 0;
 5014:         my $css_class; 
 5015:         foreach my $item (@contexts) {
 5016:             if ($rownum%2) {
 5017:                 $css_class = '';
 5018:             } else {
 5019:                 $css_class = ' class="LC_odd_row" ';
 5020:             }
 5021:             $datatable .=   '<tr'.$css_class.'>'.
 5022:                             '<td>'.$title{$item}.
 5023:                             '</td><td class="LC_left_item">'.
 5024:                             '<span class="LC_nobreak">';
 5025:             foreach my $auth (@authtypes) {
 5026:                 $datatable .= '<label>'. 
 5027:                               '<input type="checkbox" name="'.$item.'_auth" '.
 5028:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 5029:                               $authname{$auth}.'</label>&nbsp;';
 5030:             }
 5031:             $datatable .= '</span></td></tr>';
 5032:             $rownum ++;
 5033:         }
 5034:         $$rowtotal += $rownum;
 5035:     }
 5036:     return $datatable;
 5037: }
 5038: 
 5039: sub print_selfcreation {
 5040:     my ($position,$dom,$settings,$rowtotal) = @_;
 5041:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 5042:         $emaildomain,$datatable);
 5043:     if (ref($settings) eq 'HASH') {
 5044:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 5045:             $createsettings = $settings->{'cancreate'};
 5046:             if (ref($createsettings) eq 'HASH') {
 5047:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 5048:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 5049:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 5050:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 5051:                         @selfcreate = ('email','login','sso');
 5052:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 5053:                         @selfcreate = ($createsettings->{'selfcreate'});
 5054:                     }
 5055:                 }
 5056:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 5057:                     $processing = $createsettings->{'selfcreateprocessing'};
 5058:                 }
 5059:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 5060:                     $emailoptions = $createsettings->{'emailoptions'};
 5061:                 }
 5062:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 5063:                     $emailverified = $createsettings->{'emailverified'};
 5064:                 }
 5065:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 5066:                     $emaildomain = $createsettings->{'emaildomain'};
 5067:                 }
 5068:             }
 5069:         }
 5070:     }
 5071:     my %radiohash;
 5072:     my $numinrow = 4;
 5073:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 5074:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5075:     if ($position eq 'top') {
 5076:         my %choices = &Apache::lonlocal::texthash (
 5077:                                                       cancreate_login      => 'Institutional Login',
 5078:                                                       cancreate_sso        => 'Institutional Single Sign On',
 5079:                                                   );
 5080:         my @toggles = sort(keys(%choices));
 5081:         my %defaultchecked = (
 5082:                                'cancreate_login' => 'off',
 5083:                                'cancreate_sso'   => 'off',
 5084:                              );
 5085:         my ($onclick,$itemcount);
 5086:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 5087:                                                      \%choices,$itemcount,$onclick);
 5088:         $$rowtotal += $itemcount;
 5089: 
 5090:         if (ref($usertypes) eq 'HASH') {
 5091:             if (keys(%{$usertypes}) > 0) {
 5092:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 5093:                                              $dom,$numinrow,$othertitle,
 5094:                                              'statustocreate',$rowtotal);
 5095:                 $$rowtotal ++;
 5096:             }
 5097:         }
 5098:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 5099:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 5100:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 5101:         my $rem;
 5102:         my $numperrow = 2;
 5103:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 5104:         $datatable .= '<tr'.$css_class.'>'.
 5105:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 5106:                      '<td class="LC_left_item">'."\n".
 5107:                      '<table>'."\n";
 5108:         for (my $i=0; $i<@fields; $i++) {
 5109:             $rem = $i%($numperrow);
 5110:             if ($rem == 0) {
 5111:                 if ($i > 0) {
 5112:                     $datatable .= '</tr>';
 5113:                 }
 5114:                 $datatable .= '<tr>';
 5115:             }
 5116:             my $currval;
 5117:             if (ref($createsettings) eq 'HASH') {
 5118:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 5119:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 5120:                 }
 5121:             }
 5122:             $datatable .= '<td class="LC_left_item">'.
 5123:                           '<span class="LC_nobreak">'.
 5124:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 5125:                           'value="'.$currval.'" size="10" />&nbsp;'.
 5126:                           $fieldtitles{$fields[$i]}.'</span></td>';
 5127:         }
 5128:         my $colsleft = $numperrow - $rem;
 5129:         if ($colsleft > 1 ) {
 5130:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 5131:                          '&nbsp;</td>';
 5132:         } elsif ($colsleft == 1) {
 5133:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 5134:         }
 5135:         $datatable .= '</tr></table></td></tr>';
 5136:         $$rowtotal ++;
 5137:     } elsif ($position eq 'middle') {
 5138:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 5139:         my @posstypes;
 5140:         if (ref($types) eq 'ARRAY') {
 5141:             @posstypes = @{$types};
 5142:         }
 5143:         unless (grep(/^default$/,@posstypes)) {
 5144:             push(@posstypes,'default');
 5145:         }
 5146:         my %usertypeshash;
 5147:         if (ref($usertypes) eq 'HASH') {
 5148:             %usertypeshash = %{$usertypes};
 5149:         }
 5150:         $usertypeshash{'default'} = $othertitle;
 5151:         foreach my $status (@posstypes) {
 5152:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 5153:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 5154:             $$rowtotal ++;
 5155:         }
 5156:     } else {
 5157:         my %choices = &Apache::lonlocal::texthash (
 5158:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 5159:                                                   );
 5160:         my @toggles = sort(keys(%choices));
 5161:         my %defaultchecked = (
 5162:                                'cancreate_email' => 'off',
 5163:                              );
 5164:         my $customclass = 'LC_selfcreate_email';
 5165:         my $classprefix = 'LC_canmodify_emailusername_';
 5166:         my $optionsprefix = 'LC_options_emailusername_';
 5167:         my $display = 'none';
 5168:         my $rowstyle = 'display:none';
 5169:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 5170:             $display = 'block';
 5171:             $rowstyle = 'display:table-row';
 5172:         }
 5173:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
 5174:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 5175:                                                      \%choices,$$rowtotal,$onclick);
 5176:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
 5177:                                          $rowstyle);
 5178:         $$rowtotal ++;
 5179:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
 5180:                                       $rowstyle);
 5181:         $$rowtotal ++;
 5182:         my (@ordered,@posstypes,%usertypeshash);
 5183:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 5184:         my ($emailrules,$emailruleorder) =
 5185:             &Apache::lonnet::inst_userrules($dom,'email');
 5186:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 5187:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 5188:         if (ref($types) eq 'ARRAY') {
 5189:             @posstypes = @{$types};
 5190:         }
 5191:         if (@posstypes) {
 5192:             unless (grep(/^default$/,@posstypes)) {
 5193:                 push(@posstypes,'default');
 5194:             }
 5195:             if (ref($usertypes) eq 'HASH') {
 5196:                 %usertypeshash = %{$usertypes};
 5197:             }
 5198:             my $currassign;
 5199:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
 5200:                 $currassign = {
 5201:                                   selfassign => $domdefaults{'inststatusguest'},
 5202:                               };
 5203:                 @ordered = @{$domdefaults{'inststatusguest'}};
 5204:             } else {
 5205:                 $currassign = { selfassign => [] };
 5206:             }
 5207:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
 5208:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
 5209:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
 5210:                                          $numinrow,$othertitle,'selfassign',
 5211:                                          $rowtotal,$onclicktypes,$customclass,
 5212:                                          $rowstyle);
 5213:             $$rowtotal ++;
 5214:             $usertypeshash{'default'} = $othertitle;
 5215:             foreach my $status (@posstypes) {
 5216:                 my $css_class;
 5217:                 if ($$rowtotal%2) {
 5218:                     $css_class = 'LC_odd_row ';
 5219:                 }
 5220:                 $css_class .= $customclass;
 5221:                 my $rowid = $optionsprefix.$status;
 5222:                 my $hidden = 1;
 5223:                 my $currstyle = 'display:none';
 5224:                 if (grep(/^\Q$status\E$/,@ordered)) {
 5225:                     $currstyle = $rowstyle;
 5226:                     $hidden = 0;
 5227:                 }
 5228:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 5229:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
 5230:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
 5231:                 unless ($hidden) {
 5232:                     $$rowtotal ++;
 5233:                 }
 5234:             }
 5235:         } else {
 5236:             my $css_class;
 5237:             if ($$rowtotal%2) {
 5238:                 $css_class = 'LC_odd_row ';
 5239:             }
 5240:             $css_class .= $customclass;
 5241:             $usertypeshash{'default'} = $othertitle;
 5242:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 5243:                                          $emailrules,$emailruleorder,$settings,'default','',
 5244:                                          $othertitle,$css_class,$rowstyle,$intdom);
 5245:             $$rowtotal ++;
 5246:         }
 5247:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 5248:         $numinrow = 1;
 5249:         if (@posstypes) {
 5250:             foreach my $status (@posstypes) {
 5251:                 my $rowid = $classprefix.$status;
 5252:                 my $datarowstyle = 'display:none';
 5253:                 if (grep(/^\Q$status\E$/,@ordered)) {
 5254:                     $datarowstyle = $rowstyle;
 5255:                 }
 5256:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 5257:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 5258:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
 5259:                 unless ($datarowstyle eq 'display:none') {
 5260:                     $$rowtotal ++;
 5261:                 }
 5262:             }
 5263:         } else {
 5264:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
 5265:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 5266:                                                    $infotitles,'',$customclass,$rowstyle);
 5267:         }
 5268:     }
 5269:     return $datatable;
 5270: }
 5271: 
 5272: sub selfcreate_javascript {
 5273:     return <<"ENDSCRIPT";
 5274: 
 5275: <script type="text/javascript">
 5276: // <![CDATA[
 5277: 
 5278: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
 5279:     var x = document.getElementsByClassName(target);
 5280:     var insttypes = 0;
 5281:     var insttypeRegExp = new RegExp(prefix);
 5282:     if ((x.length != undefined) && (x.length > 0)) {
 5283:         if (form.elements[radio].length != undefined) {
 5284:             for (var i=0; i<form.elements[radio].length; i++) {
 5285:                 if (form.elements[radio][i].checked) {
 5286:                     if (form.elements[radio][i].value == 1) {
 5287:                         for (var j=0; j<x.length; j++) {
 5288:                             if (x[j].id == 'undefined') {
 5289:                                 x[j].style.display = 'table-row';
 5290:                             } else if (insttypeRegExp.test(x[j].id)) {
 5291:                                 insttypes ++;
 5292:                             } else {
 5293:                                 x[j].style.display = 'table-row';
 5294:                             }
 5295:                         }
 5296:                     } else {
 5297:                         for (var j=0; j<x.length; j++) {
 5298:                             x[j].style.display = 'none';
 5299:                         }
 5300:                     }
 5301:                     break;
 5302:                 }
 5303:             }
 5304:             if (insttypes > 0) {
 5305:                 toggleDataRow(form,checkbox,target,altprefix);
 5306:                 toggleDataRow(form,checkbox,target,prefix,1);
 5307:             }
 5308:         }
 5309:     }
 5310:     return;
 5311: }
 5312: 
 5313: function toggleDataRow(form,checkbox,target,prefix,docount) {
 5314:     if (form.elements[checkbox].length != undefined) {
 5315:         var count = 0;
 5316:         if (docount) {
 5317:             for (var i=0; i<form.elements[checkbox].length; i++) {
 5318:                 if (form.elements[checkbox][i].checked) {
 5319:                     count ++;
 5320:                 }
 5321:             }
 5322:         }
 5323:         for (var i=0; i<form.elements[checkbox].length; i++) {
 5324:             var type = form.elements[checkbox][i].value;
 5325:             if (document.getElementById(prefix+type)) {
 5326:                 if (form.elements[checkbox][i].checked) {
 5327:                     document.getElementById(prefix+type).style.display = 'table-row';
 5328:                     if (count % 2 == 1) {
 5329:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 5330:                     } else {
 5331:                         document.getElementById(prefix+type).className = target;
 5332:                     }
 5333:                     count ++;
 5334:                 } else {
 5335:                     document.getElementById(prefix+type).style.display = 'none';
 5336:                 }
 5337:             }
 5338:         }
 5339:     }
 5340:     return;
 5341: }
 5342: 
 5343: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
 5344:     var caller = radio+'_'+status;
 5345:     if (form.elements[caller].length != undefined) {
 5346:         for (var i=0; i<form.elements[caller].length; i++) {
 5347:             if (form.elements[caller][i].checked) {
 5348:                 if (document.getElementById(altprefix+'_inst_'+status)) {
 5349:                     var curr = form.elements[caller][i].value;
 5350:                     if (prefix) {
 5351:                         document.getElementById(prefix+'_'+status).style.display = 'none';
 5352:                     }
 5353:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
 5354:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
 5355:                     if (curr == 'custom') {
 5356:                         if (prefix) {
 5357:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
 5358:                         }
 5359:                     } else if (curr == 'inst') {
 5360:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
 5361:                     } else if (curr == 'noninst') {
 5362:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
 5363:                     }
 5364:                     break;
 5365:                 }
 5366:             }
 5367:         }
 5368:     }
 5369: }
 5370: 
 5371: // ]]>
 5372: </script>
 5373: 
 5374: ENDSCRIPT
 5375: }
 5376: 
 5377: sub noninst_users {
 5378:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
 5379:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_;
 5380:     my $class = 'LC_left_item';
 5381:     if ($css_class) {
 5382:         $css_class = ' class="'.$css_class.'"';
 5383:     }
 5384:     if ($rowid) {
 5385:         $rowid = ' id="'.$rowid.'"';
 5386:     }
 5387:     if ($rowstyle) {
 5388:         $rowstyle = ' style="'.$rowstyle.'"';
 5389:     }
 5390:     my ($output,$description);
 5391:     if ($type eq 'default') {
 5392:         $description = &mt('Requests for: [_1]',$typetitle);
 5393:     } else {
 5394:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
 5395:     }
 5396:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 5397:               "<td>$description</td>\n".
 5398:               '<td class="'.$class.'" colspan="2">'.
 5399:               '<table><tr>';
 5400:     my %headers = &Apache::lonlocal::texthash(
 5401:               approve  => 'Processing',
 5402:               email    => 'E-mail',
 5403:               username => 'Username',
 5404:     );
 5405:     foreach my $item ('approve','email','username') {
 5406:         $output .= '<th>'.$headers{$item}.'</th>';
 5407:     }
 5408:     $output .= '</tr><tr>';
 5409:     foreach my $item ('approve','email','username') {
 5410:         $output .= '<td valign="top">';
 5411:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
 5412:         if ($item eq 'approve') {
 5413:             %choices = &Apache::lonlocal::texthash (
 5414:                                                      automatic => 'Automatically approved',
 5415:                                                      approval  => 'Queued for approval',
 5416:                                                    );
 5417:             @options = ('automatic','approval');
 5418:             $hashref = $processing;
 5419:             $defoption = 'automatic';
 5420:             $name = 'cancreate_emailprocess_'.$type;
 5421:         } elsif ($item eq 'email') {
 5422:             %choices = &Apache::lonlocal::texthash (
 5423:                                                      any     => 'Any e-mail',
 5424:                                                      inst    => 'Institutional only',
 5425:                                                      noninst => 'Non-institutional only',
 5426:                                                      custom  => 'Custom restrictions',
 5427:                                                    );
 5428:             @options = ('any','inst','noninst');
 5429:             my $showcustom;
 5430:             if (ref($emailrules) eq 'HASH') {
 5431:                 if (keys(%{$emailrules}) > 0) {
 5432:                     push(@options,'custom');
 5433:                     $showcustom = 'cancreate_emailrule';
 5434:                     if (ref($settings) eq 'HASH') {
 5435:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 5436:                             foreach my $rule (@{$settings->{'email_rule'}}) {
 5437:                                 if (exists($emailrules->{$rule})) {
 5438:                                     $hascustom ++;
 5439:                                 }
 5440:                             }
 5441:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
 5442:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
 5443:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
 5444:                                     if (exists($emailrules->{$rule})) {
 5445:                                         $hascustom ++;
 5446:                                     }
 5447:                                 }
 5448:                             }
 5449:                         }
 5450:                     }
 5451:                 }
 5452:             }
 5453:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
 5454:                                                      "'cancreate_emaildomain','$type'".');"';
 5455:             $hashref = $emailoptions;
 5456:             $defoption = 'any';
 5457:             $name = 'cancreate_emailoptions_'.$type;
 5458:         } elsif ($item eq 'username') {
 5459:             %choices = &Apache::lonlocal::texthash (
 5460:                                                      all    => 'Same as e-mail',
 5461:                                                      first  => 'Omit @domain',
 5462:                                                      free   => 'Free to choose',
 5463:                                                    );
 5464:             @options = ('all','first','free');
 5465:             $hashref = $emailverified;
 5466:             $defoption = 'all';
 5467:             $name = 'cancreate_usernameoptions_'.$type;
 5468:         }
 5469:         foreach my $option (@options) {
 5470:             my $checked;
 5471:             if (ref($hashref) eq 'HASH') {
 5472:                 if ($type eq '') {
 5473:                     if (!exists($hashref->{'default'})) {
 5474:                         if ($option eq $defoption) {
 5475:                             $checked = ' checked="checked"';
 5476:                         }
 5477:                     } else {
 5478:                         if ($hashref->{'default'} eq $option) {
 5479:                             $checked = ' checked="checked"';
 5480:                         }
 5481:                     }
 5482:                 } else {
 5483:                     if (!exists($hashref->{$type})) {
 5484:                         if ($option eq $defoption) {
 5485:                             $checked = ' checked="checked"';
 5486:                         }
 5487:                     } else {
 5488:                         if ($hashref->{$type} eq $option) {
 5489:                             $checked = ' checked="checked"';
 5490:                         }
 5491:                     }
 5492:                 }
 5493:             } elsif (($item eq 'email') && ($hascustom)) {
 5494:                 if ($option eq 'custom') {
 5495:                     $checked = ' checked="checked"';
 5496:                 }
 5497:             } elsif ($option eq $defoption) {
 5498:                 $checked = ' checked="checked"';
 5499:             }
 5500:             $output .= '<span class="LC_nobreak"><label>'.
 5501:                        '<input type="radio" name="'.$name.'"'.
 5502:                        $checked.' value="'.$option.'"'.$onclick.' />'.
 5503:                        $choices{$option}.'</label></span><br />';
 5504:             if ($item eq 'email') {
 5505:                 if ($option eq 'custom') {
 5506:                     my $id = 'cancreate_emailrule_'.$type;
 5507:                     my $display = 'none';
 5508:                     if ($checked) {
 5509:                         $display = 'inline';
 5510:                     }
 5511:                     my $numinrow = 2;
 5512:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
 5513:                                '<legend>'.&mt('Disallow').'</legend><table>'.
 5514:                                &user_formats_row('email',$settings,$emailrules,
 5515:                                                  $emailruleorder,$numinrow,'',$type);
 5516:                               '</table></fieldset>';
 5517:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
 5518:                     my %text = &Apache::lonlocal::texthash (
 5519:                                                              inst    => 'must end:',
 5520:                                                              noninst => 'cannot end:',
 5521:                                                            );
 5522:                     my $value;
 5523:                     if (ref($emaildomain) eq 'HASH') {
 5524:                         if (ref($emaildomain->{$type}) eq 'HASH') {
 5525:                             $value = $emaildomain->{$type}->{$option};
 5526:                         }
 5527:                     }
 5528:                     if ($value eq '') {
 5529:                         $value = '@'.$intdom;
 5530:                     }
 5531:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
 5532:                     my $display = 'none';
 5533:                     if ($checked) {
 5534:                         $display = 'inline';
 5535:                     }
 5536:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
 5537:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
 5538:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
 5539:                                '</div>';
 5540:                 }
 5541:             }
 5542:         }
 5543:         $output .= '</td>'."\n";
 5544:     }
 5545:     }
 5546:     $output .= "</tr></table></td></tr>\n";
 5547:     return $output;
 5548: }
 5549: 
 5550: sub captcha_choice {
 5551:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
 5552:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
 5553:         $vertext,$currver); 
 5554:     my %lt = &captcha_phrases();
 5555:     $keyentry = 'hidden';
 5556:     if ($context eq 'cancreate') {
 5557:         $rowname = &mt('CAPTCHA validation');
 5558:     } elsif ($context eq 'login') {
 5559:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
 5560:     }
 5561:     if (ref($settings) eq 'HASH') {
 5562:         if ($settings->{'captcha'}) {
 5563:             $checked{$settings->{'captcha'}} = ' checked="checked"';
 5564:         } else {
 5565:             $checked{'original'} = ' checked="checked"';
 5566:         }
 5567:         if ($settings->{'captcha'} eq 'recaptcha') {
 5568:             $pubtext = $lt{'pub'};
 5569:             $privtext = $lt{'priv'};
 5570:             $keyentry = 'text';
 5571:             $vertext = $lt{'ver'};
 5572:             $currver = $settings->{'recaptchaversion'};
 5573:             if ($currver ne '2') {
 5574:                 $currver = 1;
 5575:             }
 5576:         }
 5577:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
 5578:             $currpub = $settings->{'recaptchakeys'}{'public'};
 5579:             $currpriv = $settings->{'recaptchakeys'}{'private'};
 5580:         }
 5581:     } else {
 5582:         $checked{'original'} = ' checked="checked"';
 5583:     }
 5584:     my $css_class;
 5585:     if ($itemcount%2) {
 5586:         $css_class = 'LC_odd_row';
 5587:     }
 5588:     if ($customcss) {
 5589:         $css_class .= " $customcss";
 5590:     }
 5591:     $css_class =~ s/^\s+//;
 5592:     if ($css_class) {
 5593:         $css_class = ' class="'.$css_class.'"';
 5594:     }
 5595:     if ($rowstyle) {
 5596:         $css_class .= ' style="'.$rowstyle.'"';
 5597:     }
 5598:     my $output = '<tr'.$css_class.'>'.
 5599:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="2">'."\n".
 5600:                  '<table><tr><td>'."\n";
 5601:     foreach my $option ('original','recaptcha','notused') {
 5602:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
 5603:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
 5604:                    $lt{$option}.'</label></span>';
 5605:         unless ($option eq 'notused') {
 5606:             $output .= ('&nbsp;'x2)."\n";
 5607:         }
 5608:     }
 5609: #
 5610: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
 5611: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
 5612: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
 5613: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
 5614: #
 5615:     $output .= '</td></tr>'."\n".
 5616:                '<tr><td class="LC_zero_height">'."\n".
 5617:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
 5618:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
 5619:                $currpub.'" size="40" /></span><br />'."\n".
 5620:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
 5621:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
 5622:                $currpriv.'" size="40" /></span><br />'.
 5623:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
 5624:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
 5625:                $currver.'" size="3" /></span><br />'.
 5626:                '</td></tr></table>'."\n".
 5627:                '</td></tr>';
 5628:     return $output;
 5629: }
 5630: 
 5631: sub user_formats_row {
 5632:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
 5633:     my $output;
 5634:     my %text = (
 5635:                    'username' => 'new usernames',
 5636:                    'id'       => 'IDs',
 5637:                );
 5638:     unless ($type eq 'email') {
 5639:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 5640:         $output = '<tr '.$css_class.'>'.
 5641:                   '<td><span class="LC_nobreak">'.
 5642:                   &mt("Format rules to check for $text{$type}: ").
 5643:                   '</td><td class="LC_left_item" colspan="2"><table>';
 5644:     }
 5645:     my $rem;
 5646:     if (ref($ruleorder) eq 'ARRAY') {
 5647:         for (my $i=0; $i<@{$ruleorder}; $i++) {
 5648:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
 5649:                 my $rem = $i%($numinrow);
 5650:                 if ($rem == 0) {
 5651:                     if ($i > 0) {
 5652:                         $output .= '</tr>';
 5653:                     }
 5654:                     $output .= '<tr>';
 5655:                 }
 5656:                 my $check = ' ';
 5657:                 if (ref($settings) eq 'HASH') {
 5658:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
 5659:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
 5660:                             $check = ' checked="checked" ';
 5661:                         }
 5662:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
 5663:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
 5664:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
 5665:                                 $check = ' checked="checked" ';
 5666:                             }
 5667:                         }
 5668:                     }
 5669:                 }
 5670:                 my $name = $type.'_rule';
 5671:                 if ($type eq 'email') {
 5672:                     $name .= '_'.$status;
 5673:                 }
 5674:                 $output .= '<td class="LC_left_item">'.
 5675:                            '<span class="LC_nobreak"><label>'.
 5676:                            '<input type="checkbox" name="'.$name.'" '.
 5677:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
 5678:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
 5679:             }
 5680:         }
 5681:         $rem = @{$ruleorder}%($numinrow);
 5682:     }
 5683:     my $colsleft;
 5684:     if ($rem) {
 5685:         $colsleft = $numinrow - $rem;
 5686:     }
 5687:     if ($colsleft > 1 ) {
 5688:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 5689:                    '&nbsp;</td>';
 5690:     } elsif ($colsleft == 1) {
 5691:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 5692:     }
 5693:     $output .= '</tr></table>';
 5694:     unless ($type eq 'email') {
 5695:         $output .= '</td></tr>';
 5696:     }
 5697:     return $output;
 5698: }
 5699: 
 5700: sub usercreation_types {
 5701:     my %lt = &Apache::lonlocal::texthash (
 5702:                     author     => 'When adding a co-author',
 5703:                     course     => 'When adding a user to a course',
 5704:                     requestcrs => 'When requesting a course',
 5705:                     any        => 'Any',
 5706:                     official   => 'Institutional only ',
 5707:                     unofficial => 'Non-institutional only',
 5708:                     none       => 'None',
 5709:     );
 5710:     return %lt;
 5711: }
 5712: 
 5713: sub selfcreation_types {
 5714:     my %lt = &Apache::lonlocal::texthash (
 5715:                     selfcreate => 'User creates own account',
 5716:                     any        => 'Any',
 5717:                     official   => 'Institutional only ',
 5718:                     unofficial => 'Non-institutional only',
 5719:                     email      => 'E-mail address',
 5720:                     login      => 'Institutional Login',
 5721:                     sso        => 'SSO',
 5722:              );
 5723: }
 5724: 
 5725: sub authtype_names {
 5726:     my %lt = &Apache::lonlocal::texthash(
 5727:                       int    => 'Internal',
 5728:                       krb4   => 'Kerberos 4',
 5729:                       krb5   => 'Kerberos 5',
 5730:                       loc    => 'Local',
 5731:                   );
 5732:     return %lt;
 5733: }
 5734: 
 5735: sub context_names {
 5736:     my %context_title = &Apache::lonlocal::texthash(
 5737:        author => 'Creating users when an Author',
 5738:        course => 'Creating users when in a course',
 5739:        domain => 'Creating users when a Domain Coordinator',
 5740:     );
 5741:     return %context_title;
 5742: }
 5743: 
 5744: sub print_usermodification {
 5745:     my ($position,$dom,$settings,$rowtotal) = @_;
 5746:     my $numinrow = 4;
 5747:     my ($context,$datatable,$rowcount);
 5748:     if ($position eq 'top') {
 5749:         $rowcount = 0;
 5750:         $context = 'author'; 
 5751:         foreach my $role ('ca','aa') {
 5752:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 5753:                                                    $numinrow,$rowcount);
 5754:             $$rowtotal ++;
 5755:             $rowcount ++;
 5756:         }
 5757:     } elsif ($position eq 'bottom') {
 5758:         $context = 'course';
 5759:         $rowcount = 0;
 5760:         foreach my $role ('st','ep','ta','in','cr') {
 5761:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 5762:                                                    $numinrow,$rowcount);
 5763:             $$rowtotal ++;
 5764:             $rowcount ++;
 5765:         }
 5766:     }
 5767:     return $datatable;
 5768: }
 5769: 
 5770: sub print_defaults {
 5771:     my ($position,$dom,$settings,$rowtotal) = @_;
 5772:     my $rownum = 0;
 5773:     my ($datatable,$css_class,$titles);
 5774:     unless ($position eq 'bottom') {
 5775:         $titles = &defaults_titles($dom);
 5776:     }
 5777:     if ($position eq 'top') {
 5778:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
 5779:                      'datelocale_def','portal_def');
 5780:         my %defaults;
 5781:         if (ref($settings) eq 'HASH') {
 5782:             %defaults = %{$settings};
 5783:         } else {
 5784:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 5785:             foreach my $item (@items) {
 5786:                 $defaults{$item} = $domdefaults{$item};
 5787:             }
 5788:         }
 5789:         foreach my $item (@items) {
 5790:             if ($rownum%2) {
 5791:                 $css_class = '';
 5792:             } else {
 5793:                 $css_class = ' class="LC_odd_row" ';
 5794:             }
 5795:             $datatable .= '<tr'.$css_class.'>'.
 5796:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 5797:                           '</span></td><td class="LC_right_item" colspan="3">';
 5798:             if ($item eq 'auth_def') {
 5799:                 my @authtypes = ('internal','krb4','krb5','localauth');
 5800:                 my %shortauth = (
 5801:                                  internal => 'int',
 5802:                                  krb4 => 'krb4',
 5803:                                  krb5 => 'krb5',
 5804:                                  localauth  => 'loc'
 5805:                                 );
 5806:                 my %authnames = &authtype_names();
 5807:                 foreach my $auth (@authtypes) {
 5808:                     my $checked = ' ';
 5809:                     if ($defaults{$item} eq $auth) {
 5810:                         $checked = ' checked="checked" ';
 5811:                     }
 5812:                     $datatable .= '<label><input type="radio" name="'.$item.
 5813:                                   '" value="'.$auth.'"'.$checked.'/>'.
 5814:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
 5815:                 }
 5816:             } elsif ($item eq 'timezone_def') {
 5817:                 my $includeempty = 1;
 5818:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
 5819:             } elsif ($item eq 'datelocale_def') {
 5820:                 my $includeempty = 1;
 5821:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
 5822:             } elsif ($item eq 'lang_def') {
 5823:                 my $includeempty = 1;
 5824:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
 5825:             } else {
 5826:                 my $size;
 5827:                 if ($item eq 'portal_def') {
 5828:                     $size = ' size="25"';
 5829:                 }
 5830:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 5831:                               $defaults{$item}.'"'.$size.' />';
 5832:             }
 5833:             $datatable .= '</td></tr>';
 5834:             $rownum ++;
 5835:         }
 5836:     } elsif ($position eq 'middle') {
 5837:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 5838:         my %defaults;
 5839:         if (ref($settings) eq 'HASH') {
 5840:             %defaults = %{$settings};
 5841:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 5842:                 $defaults{'intauth_cost'} = 10;
 5843:             }
 5844:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 5845:                 $defaults{'intauth_check'} = 0;
 5846:             }
 5847:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 5848:                 $defaults{'intauth_switch'} = 0;
 5849:             }
 5850:         } else {
 5851:             %defaults = (
 5852:                           'intauth_cost'   => 10,
 5853:                           'intauth_check'  => 0,
 5854:                           'intauth_switch' => 0,
 5855:                         );
 5856:         }
 5857:         foreach my $item (@items) {
 5858:             if ($rownum%2) {
 5859:                 $css_class = '';
 5860:             } else {
 5861:                 $css_class = ' class="LC_odd_row" ';
 5862:             }
 5863:             $datatable .= '<tr'.$css_class.'>'.
 5864:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 5865:                           '</span></td><td class="LC_left_item" colspan="3">';
 5866:             if ($item eq 'intauth_switch') {
 5867:                 my @options = (0,1,2);
 5868:                 my %optiondesc = &Apache::lonlocal::texthash (
 5869:                                    0 => 'No',
 5870:                                    1 => 'Yes',
 5871:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 5872:                                  );
 5873:                 $datatable .= '<table width="100%">';
 5874:                 foreach my $option (@options) {
 5875:                     my $checked = ' ';
 5876:                     if ($defaults{$item} eq $option) {
 5877:                         $checked = ' checked="checked"';
 5878:                     }
 5879:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 5880:                                   '<label><input type="radio" name="'.$item.
 5881:                                   '" value="'.$option.'"'.$checked.' />'.
 5882:                                   $optiondesc{$option}.'</label></span></td></tr>';
 5883:                 }
 5884:                 $datatable .= '</table>';
 5885:             } elsif ($item eq 'intauth_check') {
 5886:                 my @options = (0,1,2);
 5887:                 my %optiondesc = &Apache::lonlocal::texthash (
 5888:                                    0 => 'No',
 5889:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 5890:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 5891:                                  );
 5892:                 $datatable .= '<table width="100%">';
 5893:                 foreach my $option (@options) {
 5894:                     my $checked = ' ';
 5895:                     my $onclick;
 5896:                     if ($defaults{$item} eq $option) {
 5897:                         $checked = ' checked="checked"';
 5898:                     }
 5899:                     if ($option == 2) {
 5900:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 5901:                     }
 5902:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 5903:                                   '<label><input type="radio" name="'.$item.
 5904:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 5905:                                   $optiondesc{$option}.'</label></span></td></tr>';
 5906:                 }
 5907:                 $datatable .= '</table>';
 5908:             } else {
 5909:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 5910:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 5911:             }
 5912:             $datatable .= '</td></tr>';
 5913:             $rownum ++;
 5914:         }
 5915:     } else {
 5916:         my %defaults;
 5917:         if (ref($settings) eq 'HASH') {
 5918:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 5919:                 my $maxnum = @{$settings->{'inststatusorder'}};
 5920:                 for (my $i=0; $i<$maxnum; $i++) {
 5921:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
 5922:                     my $item = $settings->{'inststatusorder'}->[$i];
 5923:                     my $title = $settings->{'inststatustypes'}->{$item};
 5924:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
 5925:                     $datatable .= '<tr'.$css_class.'>'.
 5926:                                   '<td><span class="LC_nobreak">'.
 5927:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
 5928:                     for (my $k=0; $k<=$maxnum; $k++) {
 5929:                         my $vpos = $k+1;
 5930:                         my $selstr;
 5931:                         if ($k == $i) {
 5932:                             $selstr = ' selected="selected" ';
 5933:                         }
 5934:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5935:                     }
 5936:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
 5937:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
 5938:                                   &mt('delete').'</span></td>'.
 5939:                                   '<td class="LC_left_item"><span class="LC_nobreak">'.&mt('Name displayed:').
 5940:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
 5941:                                   '</span></td></tr>';
 5942:                 }
 5943:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
 5944:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
 5945:                 $datatable .= '<tr '.$css_class.'>'.
 5946:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
 5947:                 for (my $k=0; $k<=$maxnum; $k++) {
 5948:                     my $vpos = $k+1;
 5949:                     my $selstr;
 5950:                     if ($k == $maxnum) {
 5951:                         $selstr = ' selected="selected" ';
 5952:                     }
 5953:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5954:                 }
 5955:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
 5956:                               '<input type="text" size="10" name="addinststatus" value="" />'.
 5957:                               '&nbsp;'.&mt('(new)').
 5958:                               '</span></td><td class="LC_left_item"><span class="LC_nobreak">'.
 5959:                               &mt('Name displayed:').
 5960:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
 5961:                               '</tr>'."\n";
 5962:                 $rownum ++;
 5963:             }
 5964:         }
 5965:     }
 5966:     $$rowtotal += $rownum;
 5967:     return $datatable;
 5968: }
 5969: 
 5970: sub get_languages_hash {
 5971:     my %langchoices;
 5972:     foreach my $id (&Apache::loncommon::languageids()) {
 5973:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 5974:         if ($code ne '') {
 5975:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 5976:         }
 5977:     }
 5978:     return %langchoices;
 5979: }
 5980: 
 5981: sub defaults_titles {
 5982:     my ($dom) = @_;
 5983:     my %titles = &Apache::lonlocal::texthash (
 5984:                    'auth_def'      => 'Default authentication type',
 5985:                    'auth_arg_def'  => 'Default authentication argument',
 5986:                    'lang_def'      => 'Default language',
 5987:                    'timezone_def'  => 'Default timezone',
 5988:                    'datelocale_def' => 'Default locale for dates',
 5989:                    'portal_def'     => 'Portal/Default URL',
 5990:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
 5991:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
 5992:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
 5993:                  );
 5994:     if ($dom) {
 5995:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
 5996:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 5997:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
 5998:         $protocol = 'http' if ($protocol ne 'https');
 5999:         if ($uint_dom) {
 6000:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
 6001:                                          $uint_dom);
 6002:         }
 6003:     }
 6004:     return (\%titles);
 6005: }
 6006: 
 6007: sub print_scantronformat {
 6008:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
 6009:     my $itemcount = 1;
 6010:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
 6011:         %confhash);
 6012:     my $switchserver = &check_switchserver($dom,$confname);
 6013:     my %lt = &Apache::lonlocal::texthash (
 6014:                 default => 'Default bubblesheet format file error',
 6015:                 custom  => 'Custom bubblesheet format file error',
 6016:              );
 6017:     my %scantronfiles = (
 6018:         default => 'default.tab',
 6019:         custom => 'custom.tab',
 6020:     );
 6021:     foreach my $key (keys(%scantronfiles)) {
 6022:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
 6023:                               .$scantronfiles{$key};
 6024:     }
 6025:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
 6026:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
 6027:         if (!$switchserver) {
 6028:             my $servadm = $r->dir_config('lonAdmEMail');
 6029:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
 6030:             if ($configuserok eq 'ok') {
 6031:                 if ($author_ok eq 'ok') {
 6032:                     my %legacyfile = (
 6033:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab', 
 6034:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab', 
 6035:                     );
 6036:                     my %md5chk;
 6037:                     foreach my $type (keys(%legacyfile)) {
 6038:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
 6039:                         chomp($md5chk{$type});
 6040:                     }
 6041:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
 6042:                         foreach my $type (keys(%legacyfile)) {
 6043:                             ($scantronurls{$type},my $error) = 
 6044:                                 &legacy_scantronformat($r,$dom,$confname,
 6045:                                                  $type,$legacyfile{$type},
 6046:                                                  $scantronurls{$type},
 6047:                                                  $scantronfiles{$type});
 6048:                             if ($error ne '') {
 6049:                                 $error{$type} = $error;
 6050:                             }
 6051:                         }
 6052:                         if (keys(%error) == 0) {
 6053:                             $is_custom = 1;
 6054:                             $confhash{'scantron'}{'scantronformat'} = 
 6055:                                 $scantronurls{'custom'};
 6056:                             my $putresult = 
 6057:                                 &Apache::lonnet::put_dom('configuration',
 6058:                                                          \%confhash,$dom);
 6059:                             if ($putresult ne 'ok') {
 6060:                                 $error{'custom'} = 
 6061:                                     '<span class="LC_error">'.
 6062:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 6063:                             }
 6064:                         }
 6065:                     } else {
 6066:                         ($scantronurls{'default'},my $error) =
 6067:                             &legacy_scantronformat($r,$dom,$confname,
 6068:                                           'default',$legacyfile{'default'},
 6069:                                           $scantronurls{'default'},
 6070:                                           $scantronfiles{'default'});
 6071:                         if ($error eq '') {
 6072:                             $confhash{'scantron'}{'scantronformat'} = ''; 
 6073:                             my $putresult =
 6074:                                 &Apache::lonnet::put_dom('configuration',
 6075:                                                          \%confhash,$dom);
 6076:                             if ($putresult ne 'ok') {
 6077:                                 $error{'default'} =
 6078:                                     '<span class="LC_error">'.
 6079:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 6080:                             }
 6081:                         } else {
 6082:                             $error{'default'} = $error;
 6083:                         }
 6084:                     }
 6085:                 }
 6086:             }
 6087:         } else {
 6088:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
 6089:         }
 6090:     }
 6091:     if (ref($settings) eq 'HASH') {
 6092:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
 6093:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
 6094:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
 6095:                 $scantronurl = '';
 6096:             } else {
 6097:                 $scantronurl = $settings->{'scantronformat'};
 6098:             }
 6099:             $is_custom = 1;
 6100:         } else {
 6101:             $scantronurl = $scantronurls{'default'};
 6102:         }
 6103:     } else {
 6104:         if ($is_custom) {
 6105:             $scantronurl = $scantronurls{'custom'};
 6106:         } else {
 6107:             $scantronurl = $scantronurls{'default'};
 6108:         }
 6109:     }
 6110:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6111:     $datatable .= '<tr'.$css_class.'>';
 6112:     if (!$is_custom) {
 6113:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
 6114:                       '<span class="LC_nobreak">';
 6115:         if ($scantronurl) {
 6116:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
 6117:                                                          undef,undef,undef,undef,'background-color:#ffffff');
 6118:         } else {
 6119:             $datatable = &mt('File unavailable for display');
 6120:         }
 6121:         $datatable .= '</span></td>';
 6122:         if (keys(%error) == 0) { 
 6123:             $datatable .= '<td valign="bottom">';
 6124:             if (!$switchserver) {
 6125:                 $datatable .= &mt('Upload:').'<br />';
 6126:             }
 6127:         } else {
 6128:             my $errorstr;
 6129:             foreach my $key (sort(keys(%error))) {
 6130:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 6131:             }
 6132:             $datatable .= '<td>'.$errorstr;
 6133:         }
 6134:     } else {
 6135:         if (keys(%error) > 0) {
 6136:             my $errorstr;
 6137:             foreach my $key (sort(keys(%error))) {
 6138:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 6139:             } 
 6140:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
 6141:         } elsif ($scantronurl) {
 6142:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
 6143:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 6144:             $datatable .= '<td><span class="LC_nobreak">'.
 6145:                           $link.
 6146:                           '<label><input type="checkbox" name="scantronformat_del"'.
 6147:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
 6148:                           '<td><span class="LC_nobreak">&nbsp;'.
 6149:                           &mt('Replace:').'</span><br />';
 6150:         }
 6151:     }
 6152:     if (keys(%error) == 0) {
 6153:         if ($switchserver) {
 6154:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 6155:         } else {
 6156:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 6157:                          '<input type="file" name="scantronformat" /></span>';
 6158:         }
 6159:     }
 6160:     $datatable .= '</td></tr>';
 6161:     $$rowtotal ++;
 6162:     return $datatable;
 6163: }
 6164: 
 6165: sub legacy_scantronformat {
 6166:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
 6167:     my ($url,$error);
 6168:     my @statinfo = &Apache::lonnet::stat_file($newurl);
 6169:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
 6170:         (my $result,$url) =
 6171:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
 6172:                          '','',$newfile);
 6173:         if ($result ne 'ok') {
 6174:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
 6175:         }
 6176:     }
 6177:     return ($url,$error);
 6178: }
 6179: 
 6180: sub print_coursecategories {
 6181:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
 6182:     my $datatable;
 6183:     if ($position eq 'top') {
 6184:         my (%checked);
 6185:         my @catitems = ('unauth','auth');
 6186:         my @cattypes = ('std','domonly','codesrch','none');
 6187:         $checked{'unauth'} = 'std';
 6188:         $checked{'auth'} = 'std';
 6189:         if (ref($settings) eq 'HASH') {
 6190:             foreach my $type (@cattypes) {
 6191:                 if ($type eq $settings->{'unauth'}) {
 6192:                     $checked{'unauth'} = $type;
 6193:                 }
 6194:                 if ($type eq $settings->{'auth'}) {
 6195:                     $checked{'auth'} = $type;
 6196:                 }
 6197:             }
 6198:         }
 6199:         my %lt = &Apache::lonlocal::texthash (
 6200:                                                unauth   => 'Catalog type for unauthenticated users',
 6201:                                                auth     => 'Catalog type for authenticated users',
 6202:                                                none     => 'No catalog',
 6203:                                                std      => 'Standard catalog',
 6204:                                                domonly  => 'Domain-only catalog',
 6205:                                                codesrch => "Code search form",
 6206:                                              );
 6207:        my $itemcount = 0;
 6208:        foreach my $item (@catitems) {
 6209:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 6210:            $datatable .= '<tr '.$css_class.'>'.
 6211:                          '<td>'.$lt{$item}.'</td>'.
 6212:                          '<td class="LC_right_item"><span class="LC_nobreak">';
 6213:            foreach my $type (@cattypes) {
 6214:                my $ischecked;
 6215:                if ($checked{$item} eq $type) {
 6216:                    $ischecked=' checked="checked"';
 6217:                }
 6218:                $datatable .= '<label>'.
 6219:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
 6220:                              ' />'.$lt{$type}.'</label>&nbsp;';
 6221:            }
 6222:            $datatable .= '</span></td></tr>';
 6223:            $itemcount ++;
 6224:         }
 6225:         $$rowtotal += $itemcount;
 6226:     } elsif ($position eq 'middle') {
 6227:         my $toggle_cats_crs = ' ';
 6228:         my $toggle_cats_dom = ' checked="checked" ';
 6229:         my $can_cat_crs = ' ';
 6230:         my $can_cat_dom = ' checked="checked" ';
 6231:         my $toggle_catscomm_comm = ' ';
 6232:         my $toggle_catscomm_dom = ' checked="checked" ';
 6233:         my $can_catcomm_comm = ' ';
 6234:         my $can_catcomm_dom = ' checked="checked" ';
 6235: 
 6236:         if (ref($settings) eq 'HASH') {
 6237:             if ($settings->{'togglecats'} eq 'crs') {
 6238:                 $toggle_cats_crs = $toggle_cats_dom;
 6239:                 $toggle_cats_dom = ' ';
 6240:             }
 6241:             if ($settings->{'categorize'} eq 'crs') {
 6242:                 $can_cat_crs = $can_cat_dom;
 6243:                 $can_cat_dom = ' ';
 6244:             }
 6245:             if ($settings->{'togglecatscomm'} eq 'comm') {
 6246:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
 6247:                 $toggle_catscomm_dom = ' ';
 6248:             }
 6249:             if ($settings->{'categorizecomm'} eq 'comm') {
 6250:                 $can_catcomm_comm = $can_catcomm_dom;
 6251:                 $can_catcomm_dom = ' ';
 6252:             }
 6253:         }
 6254:         my %title = &Apache::lonlocal::texthash (
 6255:                      togglecats     => 'Show/Hide a course in catalog',
 6256:                      togglecatscomm => 'Show/Hide a community in catalog',
 6257:                      categorize     => 'Assign a category to a course',
 6258:                      categorizecomm => 'Assign a category to a community',
 6259:                     );
 6260:         my %level = &Apache::lonlocal::texthash (
 6261:                      dom  => 'Set in Domain',
 6262:                      crs  => 'Set in Course',
 6263:                      comm => 'Set in Community',
 6264:                     );
 6265:         $datatable = '<tr class="LC_odd_row">'.
 6266:                   '<td>'.$title{'togglecats'}.'</td>'.
 6267:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 6268:                   '<input type="radio" name="togglecats"'.
 6269:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 6270:                   '<label><input type="radio" name="togglecats"'.
 6271:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
 6272:                   '</tr><tr>'.
 6273:                   '<td>'.$title{'categorize'}.'</td>'.
 6274:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 6275:                   '<label><input type="radio" name="categorize"'.
 6276:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 6277:                   '<label><input type="radio" name="categorize"'.
 6278:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
 6279:                   '</tr><tr class="LC_odd_row">'.
 6280:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
 6281:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 6282:                   '<input type="radio" name="togglecatscomm"'.
 6283:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 6284:                   '<label><input type="radio" name="togglecatscomm"'.
 6285:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
 6286:                   '</tr><tr>'.
 6287:                   '<td>'.$title{'categorizecomm'}.'</td>'.
 6288:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 6289:                   '<label><input type="radio" name="categorizecomm"'.
 6290:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 6291:                   '<label><input type="radio" name="categorizecomm"'.
 6292:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
 6293:                   '</tr>';
 6294:         $$rowtotal += 4;
 6295:     } else {
 6296:         my $css_class;
 6297:         my $itemcount = 1;
 6298:         my $cathash; 
 6299:         if (ref($settings) eq 'HASH') {
 6300:             $cathash = $settings->{'cats'};
 6301:         }
 6302:         if (ref($cathash) eq 'HASH') {
 6303:             my (@cats,@trails,%allitems,%idx,@jsarray);
 6304:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
 6305:                                                    \%allitems,\%idx,\@jsarray);
 6306:             my $maxdepth = scalar(@cats);
 6307:             my $colattrib = '';
 6308:             if ($maxdepth > 2) {
 6309:                 $colattrib = ' colspan="2" ';
 6310:             }
 6311:             my @path;
 6312:             if (@cats > 0) {
 6313:                 if (ref($cats[0]) eq 'ARRAY') {
 6314:                     my $numtop = @{$cats[0]};
 6315:                     my $maxnum = $numtop;
 6316:                     my %default_names = (
 6317:                           instcode    => &mt('Official courses'),
 6318:                           communities => &mt('Communities'),
 6319:                     );
 6320: 
 6321:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
 6322:                         ($cathash->{'instcode::0'} eq '') ||
 6323:                         (!grep(/^communities$/,@{$cats[0]})) || 
 6324:                         ($cathash->{'communities::0'} eq '')) {
 6325:                         $maxnum ++;
 6326:                     }
 6327:                     my $lastidx;
 6328:                     for (my $i=0; $i<$numtop; $i++) {
 6329:                         my $parent = $cats[0][$i];
 6330:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6331:                         my $item = &escape($parent).'::0';
 6332:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
 6333:                         $lastidx = $idx{$item};
 6334:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 6335:                                       .'<select name="'.$item.'"'.$chgstr.'>';
 6336:                         for (my $k=0; $k<=$maxnum; $k++) {
 6337:                             my $vpos = $k+1;
 6338:                             my $selstr;
 6339:                             if ($k == $i) {
 6340:                                 $selstr = ' selected="selected" ';
 6341:                             }
 6342:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6343:                         }
 6344:                         $datatable .= '</select></span></td><td>';
 6345:                         if ($parent eq 'instcode' || $parent eq 'communities') {
 6346:                             $datatable .=  '<span class="LC_nobreak">'
 6347:                                            .$default_names{$parent}.'</span>';
 6348:                             if ($parent eq 'instcode') {
 6349:                                 $datatable .= '<br /><span class="LC_nobreak">('
 6350:                                               .&mt('with institutional codes')
 6351:                                               .')</span></td><td'.$colattrib.'>';
 6352:                             } else {
 6353:                                 $datatable .= '<table><tr><td>';
 6354:                             }
 6355:                             $datatable .= '<span class="LC_nobreak">'
 6356:                                           .'<label><input type="radio" name="'
 6357:                                           .$parent.'" value="1" checked="checked" />'
 6358:                                           .&mt('Display').'</label>';
 6359:                             if ($parent eq 'instcode') {
 6360:                                 $datatable .= '&nbsp;';
 6361:                             } else {
 6362:                                 $datatable .= '</span></td></tr><tr><td>'
 6363:                                               .'<span class="LC_nobreak">';
 6364:                             }
 6365:                             $datatable .= '<label><input type="radio" name="'
 6366:                                           .$parent.'" value="0" />'
 6367:                                           .&mt('Do not display').'</label></span>';
 6368:                             if ($parent eq 'communities') {
 6369:                                 $datatable .= '</td></tr></table>';
 6370:                             }
 6371:                             $datatable .= '</td>';
 6372:                         } else {
 6373:                             $datatable .= $parent
 6374:                                           .'&nbsp;<span class="LC_nobreak"><label>'
 6375:                                           .'<input type="checkbox" name="deletecategory" '
 6376:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
 6377:                         }
 6378:                         my $depth = 1;
 6379:                         push(@path,$parent);
 6380:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
 6381:                         pop(@path);
 6382:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 6383:                         $itemcount ++;
 6384:                     }
 6385:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6386:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
 6387:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
 6388:                     for (my $k=0; $k<=$maxnum; $k++) {
 6389:                         my $vpos = $k+1;
 6390:                         my $selstr;
 6391:                         if ($k == $numtop) {
 6392:                             $selstr = ' selected="selected" ';
 6393:                         }
 6394:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6395:                     }
 6396:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
 6397:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
 6398:                                   .'</tr>'."\n";
 6399:                     $itemcount ++;
 6400:                     foreach my $default ('instcode','communities') {
 6401:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
 6402:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6403:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
 6404:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
 6405:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
 6406:                             for (my $k=0; $k<=$maxnum; $k++) {
 6407:                                 my $vpos = $k+1;
 6408:                                 my $selstr;
 6409:                                 if ($k == $maxnum) {
 6410:                                     $selstr = ' selected="selected" ';
 6411:                                 }
 6412:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6413:                             }
 6414:                             $datatable .= '</select></span></td>'.
 6415:                                           '<td><span class="LC_nobreak">'.
 6416:                                           $default_names{$default}.'</span>';
 6417:                             if ($default eq 'instcode') {
 6418:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
 6419:                                               .&mt('with institutional codes').')</span>';
 6420:                             }
 6421:                             $datatable .= '</td>'
 6422:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
 6423:                                           .&mt('Display').'</label>&nbsp;'
 6424:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
 6425:                                           .&mt('Do not display').'</label></span></td></tr>';
 6426:                         }
 6427:                     }
 6428:                 }
 6429:             } else {
 6430:                 $datatable .= &initialize_categories($itemcount);
 6431:             }
 6432:         } else {
 6433:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
 6434:                           .&initialize_categories($itemcount);
 6435:         }
 6436:         $$rowtotal += $itemcount;
 6437:     }
 6438:     return $datatable;
 6439: }
 6440: 
 6441: sub print_serverstatuses {
 6442:     my ($dom,$settings,$rowtotal) = @_;
 6443:     my $datatable;
 6444:     my @pages = &serverstatus_pages();
 6445:     my (%namedaccess,%machineaccess);
 6446:     foreach my $type (@pages) {
 6447:         $namedaccess{$type} = '';
 6448:         $machineaccess{$type}= '';
 6449:     }
 6450:     if (ref($settings) eq 'HASH') {
 6451:         foreach my $type (@pages) {
 6452:             if (exists($settings->{$type})) {
 6453:                 if (ref($settings->{$type}) eq 'HASH') {
 6454:                     foreach my $key (keys(%{$settings->{$type}})) {
 6455:                         if ($key eq 'namedusers') {
 6456:                             $namedaccess{$type} = $settings->{$type}->{$key};
 6457:                         } elsif ($key eq 'machines') {
 6458:                             $machineaccess{$type} = $settings->{$type}->{$key};
 6459:                         }
 6460:                     }
 6461:                 }
 6462:             }
 6463:         }
 6464:     }
 6465:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
 6466:     my $rownum = 0;
 6467:     my $css_class;
 6468:     foreach my $type (@pages) {
 6469:         $rownum ++;
 6470:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 6471:         $datatable .= '<tr'.$css_class.'>'.
 6472:                       '<td><span class="LC_nobreak">'.
 6473:                       $titles->{$type}.'</span></td>'.
 6474:                       '<td class="LC_left_item">'.
 6475:                       '<input type="text" name="'.$type.'_namedusers" '.
 6476:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
 6477:                       '<td class="LC_right_item">'.
 6478:                       '<span class="LC_nobreak">'.
 6479:                       '<input type="text" name="'.$type.'_machines" '.
 6480:                       'value="'.$machineaccess{$type}.'" size="10" />'.
 6481:                       '</span></td></tr>'."\n";
 6482:     }
 6483:     $$rowtotal += $rownum;
 6484:     return $datatable;
 6485: }
 6486: 
 6487: sub serverstatus_pages {
 6488:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
 6489:             'checksums','clusterstatus','metadata_keywords','metadata_harvest',
 6490:             'takeoffline','takeonline','showenv','toggledebug','ping','domconf',
 6491:             'uniquecodes','diskusage','coursecatalog');
 6492: }
 6493: 
 6494: sub defaults_javascript {
 6495:     my ($settings) = @_;
 6496:     my $intauthcheck = &mt('Warning: disallowing login for an authenticated user if the stored cost is less than the default will require a password reset by/for the user.');
 6497:     my $intauthcost = &mt('Warning: bcrypt encryption cost for internal authentication must be an integer.');
 6498:     &js_escape(\$intauthcheck);
 6499:     &js_escape(\$intauthcost);
 6500:     my $intauthjs = <<"ENDSCRIPT";
 6501: 
 6502: function warnIntAuth(field) {
 6503:     if (field.name == 'intauth_check') {
 6504:         if (field.value == '2') {
 6505:             alert('$intauthcheck');
 6506:         }
 6507:     }
 6508:     if (field.name == 'intauth_cost') {
 6509:         field.value.replace(/\s/g,'');
 6510:         if (field.value != '') {
 6511:             var regexdigit=/^\\d+\$/;
 6512:             if (!regexdigit.test(field.value)) {
 6513:                 alert('$intauthcost');
 6514:             }
 6515:         }
 6516:     }
 6517:     return;
 6518: }
 6519: 
 6520: ENDSCRIPT
 6521: 
 6522:     if (ref($settings) ne 'HASH') {
 6523:         return &Apache::lonhtmlcommon::scripttag($intauthjs);
 6524:     }
 6525:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 6526:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
 6527:         if ($maxnum eq '') {
 6528:             $maxnum = 0;
 6529:         }
 6530:         $maxnum ++;
 6531:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
 6532:         return <<"ENDSCRIPT";
 6533: <script type="text/javascript">
 6534: // <![CDATA[
 6535: function reorderTypes(form,caller) {
 6536:     var changedVal;
 6537: $jstext 
 6538:     var newpos = 'addinststatus_pos';
 6539:     var current = new Array;
 6540:     var maxh = $maxnum;
 6541:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 6542:     var oldVal;
 6543:     if (caller == newpos) {
 6544:         changedVal = newitemVal;
 6545:     } else {
 6546:         var curritem = 'inststatus_pos_'+caller;
 6547:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
 6548:         current[newitemVal] = newpos;
 6549:     }
 6550:     for (var i=0; i<inststatuses.length; i++) {
 6551:         if (inststatuses[i] != caller) {
 6552:             var elementName = 'inststatus_pos_'+inststatuses[i];
 6553:             if (form.elements[elementName]) {
 6554:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 6555:                 current[currVal] = elementName;
 6556:             }
 6557:         }
 6558:     }
 6559:     for (var j=0; j<maxh; j++) {
 6560:         if (current[j] == undefined) {
 6561:             oldVal = j;
 6562:         }
 6563:     }
 6564:     if (oldVal < changedVal) {
 6565:         for (var k=oldVal+1; k<=changedVal ; k++) {
 6566:            var elementName = current[k];
 6567:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 6568:         }
 6569:     } else {
 6570:         for (var k=changedVal; k<oldVal; k++) {
 6571:             var elementName = current[k];
 6572:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 6573:         }
 6574:     }
 6575:     return;
 6576: }
 6577: 
 6578: $intauthjs
 6579: 
 6580: // ]]>
 6581: </script>
 6582: 
 6583: ENDSCRIPT
 6584:     } else {
 6585:         return &Apache::lonhtmlcommon::scripttag($intauthjs);
 6586:     }
 6587: }
 6588: 
 6589: sub coursecategories_javascript {
 6590:     my ($settings) = @_;
 6591:     my ($output,$jstext,$cathash);
 6592:     if (ref($settings) eq 'HASH') {
 6593:         $cathash = $settings->{'cats'};
 6594:     }
 6595:     if (ref($cathash) eq 'HASH') {
 6596:         my (@cats,@jsarray,%idx);
 6597:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
 6598:         if (@jsarray > 0) {
 6599:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
 6600:             for (my $i=0; $i<@jsarray; $i++) {
 6601:                 if (ref($jsarray[$i]) eq 'ARRAY') {
 6602:                     my $catstr = join('","',@{$jsarray[$i]});
 6603:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
 6604:                 }
 6605:             }
 6606:         }
 6607:     } else {
 6608:         $jstext  = '    var categories = Array(1);'."\n".
 6609:                    '    categories[0] = Array("instcode_pos");'."\n"; 
 6610:     }
 6611:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
 6612:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
 6613:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
 6614:     &js_escape(\$instcode_reserved);
 6615:     &js_escape(\$communities_reserved);
 6616:     &js_escape(\$choose_again);
 6617:     $output = <<"ENDSCRIPT";
 6618: <script type="text/javascript">
 6619: // <![CDATA[
 6620: function reorderCats(form,parent,item,idx) {
 6621:     var changedVal;
 6622: $jstext
 6623:     var newpos = 'addcategory_pos';
 6624:     if (parent == '') {
 6625:         var has_instcode = 0;
 6626:         var maxtop = categories[idx].length;
 6627:         for (var j=0; j<maxtop; j++) {
 6628:             if (categories[idx][j] == 'instcode::0') {
 6629:                 has_instcode == 1;
 6630:             }
 6631:         }
 6632:         if (has_instcode == 0) {
 6633:             categories[idx][maxtop] = 'instcode_pos';
 6634:         }
 6635:     } else {
 6636:         newpos += '_'+parent;
 6637:     }
 6638:     var maxh = 1 + categories[idx].length;
 6639:     var current = new Array;
 6640:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 6641:     if (item == newpos) {
 6642:         changedVal = newitemVal;
 6643:     } else {
 6644:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 6645:         current[newitemVal] = newpos;
 6646:     }
 6647:     for (var i=0; i<categories[idx].length; i++) {
 6648:         var elementName = categories[idx][i];
 6649:         if (elementName != item) {
 6650:             if (form.elements[elementName]) {
 6651:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 6652:                 current[currVal] = elementName;
 6653:             }
 6654:         }
 6655:     }
 6656:     var oldVal;
 6657:     for (var j=0; j<maxh; j++) {
 6658:         if (current[j] == undefined) {
 6659:             oldVal = j;
 6660:         }
 6661:     }
 6662:     if (oldVal < changedVal) {
 6663:         for (var k=oldVal+1; k<=changedVal ; k++) {
 6664:            var elementName = current[k];
 6665:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 6666:         }
 6667:     } else {
 6668:         for (var k=changedVal; k<oldVal; k++) {
 6669:             var elementName = current[k];
 6670:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 6671:         }
 6672:     }
 6673:     return;
 6674: }
 6675: 
 6676: function categoryCheck(form) {
 6677:     if (form.elements['addcategory_name'].value == 'instcode') {
 6678:         alert('$instcode_reserved\\n$choose_again');
 6679:         return false;
 6680:     }
 6681:     if (form.elements['addcategory_name'].value == 'communities') {
 6682:         alert('$communities_reserved\\n$choose_again');
 6683:         return false;
 6684:     }
 6685:     return true;
 6686: }
 6687: 
 6688: // ]]>
 6689: </script>
 6690: 
 6691: ENDSCRIPT
 6692:     return $output;
 6693: }
 6694: 
 6695: sub initialize_categories {
 6696:     my ($itemcount) = @_;
 6697:     my ($datatable,$css_class,$chgstr);
 6698:     my %default_names = (
 6699:                       instcode    => 'Official courses (with institutional codes)',
 6700:                       communities => 'Communities',
 6701:                         );
 6702:     my $select0 = ' selected="selected"';
 6703:     my $select1 = '';
 6704:     foreach my $default ('instcode','communities') {
 6705:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6706:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
 6707:         if ($default eq 'communities') {
 6708:             $select1 = $select0;
 6709:             $select0 = '';
 6710:         }
 6711:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 6712:                      .'<select name="'.$default.'_pos">'
 6713:                      .'<option value="0"'.$select0.'>1</option>'
 6714:                      .'<option value="1"'.$select1.'>2</option>'
 6715:                      .'<option value="2">3</option></select>&nbsp;'
 6716:                      .$default_names{$default}
 6717:                      .'</span></td><td><span class="LC_nobreak">'
 6718:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
 6719:                      .&mt('Display').'</label>&nbsp;<label>'
 6720:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
 6721:                  .'</label></span></td></tr>';
 6722:         $itemcount ++;
 6723:     }
 6724:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6725:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
 6726:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 6727:                   .'<select name="addcategory_pos"'.$chgstr.'>'
 6728:                   .'<option value="0">1</option>'
 6729:                   .'<option value="1">2</option>'
 6730:                   .'<option value="2" selected="selected">3</option></select>&nbsp;'
 6731:                   .&mt('Add category').'</span></td><tda<span class="LC_nobreak">>'.&mt('Name:')
 6732:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
 6733:                   .'</td></tr>';
 6734:     return $datatable;
 6735: }
 6736: 
 6737: sub build_category_rows {
 6738:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
 6739:     my ($text,$name,$item,$chgstr);
 6740:     if (ref($cats) eq 'ARRAY') {
 6741:         my $maxdepth = scalar(@{$cats});
 6742:         if (ref($cats->[$depth]) eq 'HASH') {
 6743:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 6744:                 my $numchildren = @{$cats->[$depth]{$parent}};
 6745:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6746:                 $text .= '<td><table class="LC_data_table">';
 6747:                 my ($idxnum,$parent_name,$parent_item);
 6748:                 my $higher = $depth - 1;
 6749:                 if ($higher == 0) {
 6750:                     $parent_name = &escape($parent).'::'.$higher;
 6751:                 } else {
 6752:                     if (ref($path) eq 'ARRAY') {
 6753:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 6754:                     }
 6755:                 }
 6756:                 $parent_item = 'addcategory_pos_'.$parent_name;
 6757:                 for (my $j=0; $j<=$numchildren; $j++) {
 6758:                     if ($j < $numchildren) {
 6759:                         $name = $cats->[$depth]{$parent}[$j];
 6760:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
 6761:                         $idxnum = $idx->{$item};
 6762:                     } else {
 6763:                         $name = $parent_name;
 6764:                         $item = $parent_item;
 6765:                     }
 6766:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
 6767:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
 6768:                     for (my $i=0; $i<=$numchildren; $i++) {
 6769:                         my $vpos = $i+1;
 6770:                         my $selstr;
 6771:                         if ($j == $i) {
 6772:                             $selstr = ' selected="selected" ';
 6773:                         }
 6774:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
 6775:                     }
 6776:                     $text .= '</select>&nbsp;';
 6777:                     if ($j < $numchildren) {
 6778:                         my $deeper = $depth+1;
 6779:                         $text .= $name.'&nbsp;'
 6780:                                  .'<label><input type="checkbox" name="deletecategory" value="'
 6781:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
 6782:                         if(ref($path) eq 'ARRAY') {
 6783:                             push(@{$path},$name);
 6784:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
 6785:                             pop(@{$path});
 6786:                         }
 6787:                     } else {
 6788:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
 6789:                         if ($j == $numchildren) {
 6790:                             $text .= $name;
 6791:                         } else {
 6792:                             $text .= $item;
 6793:                         }
 6794:                         $text .= '" value="" />';
 6795:                     }
 6796:                     $text .= '</td></tr>';
 6797:                 }
 6798:                 $text .= '</table></td>';
 6799:             } else {
 6800:                 my $higher = $depth-1;
 6801:                 if ($higher == 0) {
 6802:                     $name = &escape($parent).'::'.$higher;
 6803:                 } else {
 6804:                     if (ref($path) eq 'ARRAY') {
 6805:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 6806:                     }
 6807:                 }
 6808:                 my $colspan;
 6809:                 if ($parent ne 'instcode') {
 6810:                     $colspan = $maxdepth - $depth - 1;
 6811:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
 6812:                 }
 6813:             }
 6814:         }
 6815:     }
 6816:     return $text;
 6817: }
 6818: 
 6819: sub modifiable_userdata_row {
 6820:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
 6821:         $rowid,$customcss,$rowstyle) = @_;
 6822:     my ($role,$rolename,$statustype);
 6823:     $role = $item;
 6824:     if ($context eq 'cancreate') {
 6825:         if ($item =~ /^(emailusername)_(.+)$/) {
 6826:             $role = $1;
 6827:             $statustype = $2;
 6828:             if (ref($usertypes) eq 'HASH') {
 6829:                 if ($usertypes->{$statustype}) {
 6830:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
 6831:                 } else {
 6832:                     $rolename = &mt('Data provided by user');
 6833:                 }
 6834:             }
 6835:         }
 6836:     } elsif ($context eq 'selfcreate') {
 6837:         if (ref($usertypes) eq 'HASH') {
 6838:             $rolename = $usertypes->{$role};
 6839:         } else {
 6840:             $rolename = $role;
 6841:         }
 6842:     } else {
 6843:         if ($role eq 'cr') {
 6844:             $rolename = &mt('Custom role');
 6845:         } else {
 6846:             $rolename = &Apache::lonnet::plaintext($role);
 6847:         }
 6848:     }
 6849:     my (@fields,%fieldtitles);
 6850:     if (ref($fieldsref) eq 'ARRAY') {
 6851:         @fields = @{$fieldsref};
 6852:     } else {
 6853:         @fields = ('lastname','firstname','middlename','generation',
 6854:                    'permanentemail','id');
 6855:     }
 6856:     if ((ref($titlesref) eq 'HASH')) {
 6857:         %fieldtitles = %{$titlesref};
 6858:     } else {
 6859:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 6860:     }
 6861:     my $output;
 6862:     my $css_class;
 6863:     if ($rowcount%2) {
 6864:         $css_class = 'LC_odd_row';
 6865:     }
 6866:     if ($customcss) {
 6867:         $css_class .= " $customcss";
 6868:     }
 6869:     $css_class =~ s/^\s+//;
 6870:     if ($css_class) {
 6871:         $css_class = ' class="'.$css_class.'"';
 6872:     }
 6873:     if ($rowstyle) {
 6874:         $css_class .= ' style="'.$rowstyle.'"';
 6875:     }
 6876:     if ($rowid) {
 6877:         $rowid = ' id="'.$rowid.'"';
 6878:     }
 6879: 
 6880:     $output = '<tr '.$css_class.$rowid.'>'.
 6881:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
 6882:               '<td class="LC_left_item" colspan="2"><table>';
 6883:     my $rem;
 6884:     my %checks;
 6885:     if (ref($settings) eq 'HASH') {
 6886:         if (ref($settings->{$context}) eq 'HASH') {
 6887:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
 6888:                 my $hashref = $settings->{$context}->{$role};
 6889:                 if ($role eq 'emailusername') {
 6890:                     if ($statustype) {
 6891:                         if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
 6892:                             $hashref = $settings->{$context}->{$role}->{$statustype};
 6893:                             if (ref($hashref) eq 'HASH') { 
 6894:                                 foreach my $field (@fields) {
 6895:                                     if ($hashref->{$field}) {
 6896:                                         $checks{$field} = $hashref->{$field};
 6897:                                     }
 6898:                                 }
 6899:                             }
 6900:                         }
 6901:                     }
 6902:                 } else {
 6903:                     if (ref($hashref) eq 'HASH') {
 6904:                         foreach my $field (@fields) {
 6905:                             if ($hashref->{$field}) {
 6906:                                 $checks{$field} = ' checked="checked" ';
 6907:                             }
 6908:                         }
 6909:                     }
 6910:                 }
 6911:             }
 6912:         }
 6913:     }
 6914: 
 6915:     my $total = scalar(@fields);
 6916:     for (my $i=0; $i<$total; $i++) {
 6917:         $rem = $i%($numinrow);
 6918:         if ($rem == 0) {
 6919:             if ($i > 0) {
 6920:                 $output .= '</tr>';
 6921:             }
 6922:             $output .= '<tr>';
 6923:         }
 6924:         my $check = ' ';
 6925:         unless ($role eq 'emailusername') {
 6926:             if (exists($checks{$fields[$i]})) {
 6927:                 $check = $checks{$fields[$i]}
 6928:             } else {
 6929:                 if ($role eq 'st') {
 6930:                     if (ref($settings) ne 'HASH') {
 6931:                         $check = ' checked="checked" '; 
 6932:                     }
 6933:                 }
 6934:             }
 6935:         }
 6936:         $output .= '<td class="LC_left_item">'.
 6937:                    '<span class="LC_nobreak">';
 6938:         if ($role eq 'emailusername') {
 6939:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
 6940:                 $checks{$fields[$i]} = 'omit';
 6941:             }
 6942:             foreach my $option ('required','optional','omit') {
 6943:                 my $checked='';
 6944:                 if ($checks{$fields[$i]} eq $option) {
 6945:                     $checked='checked="checked" ';
 6946:                 }
 6947:                 $output .= '<label>'.
 6948:                            '<input type="radio" name="canmodify_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
 6949:                            &mt($option).'</label>'.('&nbsp;' x2);
 6950:             }
 6951:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
 6952:         } else {
 6953:             $output .= '<label>'.
 6954:                        '<input type="checkbox" name="canmodify_'.$role.'" '.
 6955:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
 6956:                        '</label>';
 6957:         }
 6958:         $output .= '</span></td>';
 6959:     }
 6960:     $rem = $total%$numinrow;
 6961:     my $colsleft;
 6962:     if ($rem) {
 6963:         $colsleft = $numinrow - $rem;
 6964:     }
 6965:     if ($colsleft > 1) {
 6966:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6967:                    '&nbsp;</td>';
 6968:     } elsif ($colsleft == 1) {
 6969:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 6970:     }
 6971:     $output .= '</tr></table></td></tr>';
 6972:     return $output;
 6973: }
 6974: 
 6975: sub insttypes_row {
 6976:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
 6977:         $customcss,$rowstyle) = @_;
 6978:     my %lt = &Apache::lonlocal::texthash (
 6979:                       cansearch => 'Users allowed to search',
 6980:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
 6981:                       lockablenames => 'User preference to lock name',
 6982:                       selfassign    => 'Self-reportable affiliations',
 6983:              );
 6984:     my $showdom;
 6985:     if ($context eq 'cansearch') {
 6986:         $showdom = ' ('.$dom.')';
 6987:     }
 6988:     my $class = 'LC_left_item';
 6989:     if ($context eq 'statustocreate') {
 6990:         $class = 'LC_right_item';
 6991:     }
 6992:     my $css_class;
 6993:     if ($$rowtotal%2) {
 6994:         $css_class = 'LC_odd_row';
 6995:     }
 6996:     if ($customcss) {
 6997:         $css_class .= ' '.$customcss;
 6998:     }
 6999:     $css_class =~ s/^\s+//;
 7000:     if ($css_class) {
 7001:         $css_class = ' class="'.$css_class.'"';
 7002:     }
 7003:     if ($rowstyle) {
 7004:         $css_class .= ' style="'.$rowstyle.'"';
 7005:     }
 7006:     if ($onclick) {
 7007:         $onclick = 'onclick="'.$onclick.'" ';
 7008:     }
 7009:     my $output = '<tr'.$css_class.'>'.
 7010:                  '<td>'.$lt{$context}.$showdom.
 7011:                  '</td><td class="'.$class.'" colspan="2"><table>';
 7012:     my $rem;
 7013:     if (ref($types) eq 'ARRAY') {
 7014:         for (my $i=0; $i<@{$types}; $i++) {
 7015:             if (defined($usertypes->{$types->[$i]})) {
 7016:                 my $rem = $i%($numinrow);
 7017:                 if ($rem == 0) {
 7018:                     if ($i > 0) {
 7019:                         $output .= '</tr>';
 7020:                     }
 7021:                     $output .= '<tr>';
 7022:                 }
 7023:                 my $check = ' ';
 7024:                 if (ref($settings) eq 'HASH') {
 7025:                     if (ref($settings->{$context}) eq 'ARRAY') {
 7026:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
 7027:                             $check = ' checked="checked" ';
 7028:                         }
 7029:                     } elsif ($context eq 'statustocreate') {
 7030:                         $check = ' checked="checked" ';
 7031:                     }
 7032:                 }
 7033:                 $output .= '<td class="LC_left_item">'.
 7034:                            '<span class="LC_nobreak"><label>'.
 7035:                            '<input type="checkbox" name="'.$context.'" '.
 7036:                            'value="'.$types->[$i].'"'.$check.$onclick.'/>'.
 7037:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 7038:             }
 7039:         }
 7040:         $rem = @{$types}%($numinrow);
 7041:     }
 7042:     my $colsleft = $numinrow - $rem;
 7043:     if ($rem == 0) {
 7044:         $output .= '<tr>';
 7045:     }
 7046:     if ($colsleft > 1) {
 7047:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 7048:     } else {
 7049:         $output .= '<td class="LC_left_item">';
 7050:     }
 7051:     my $defcheck = ' ';
 7052:     if (ref($settings) eq 'HASH') {  
 7053:         if (ref($settings->{$context}) eq 'ARRAY') {
 7054:             if (grep(/^default$/,@{$settings->{$context}})) {
 7055:                 $defcheck = ' checked="checked" ';
 7056:             }
 7057:         } elsif ($context eq 'statustocreate') {
 7058:             $defcheck = ' checked="checked" ';
 7059:         }
 7060:     }
 7061:     $output .= '<span class="LC_nobreak"><label>'.
 7062:                '<input type="checkbox" name="'.$context.'" '.
 7063:                'value="default"'.$defcheck.$onclick.'/>'.
 7064:                $othertitle.'</label></span></td>'.
 7065:                '</tr></table></td></tr>';
 7066:     return $output;
 7067: }
 7068: 
 7069: sub sorted_searchtitles {
 7070:     my %searchtitles = &Apache::lonlocal::texthash(
 7071:                          'uname' => 'username',
 7072:                          'lastname' => 'last name',
 7073:                          'lastfirst' => 'last name, first name',
 7074:                      );
 7075:     my @titleorder = ('uname','lastname','lastfirst');
 7076:     return (\%searchtitles,\@titleorder);
 7077: }
 7078: 
 7079: sub sorted_searchtypes {
 7080:     my %srchtypes_desc = (
 7081:                            exact    => 'is exact match',
 7082:                            contains => 'contains ..',
 7083:                            begins   => 'begins with ..',
 7084:                          );
 7085:     my @srchtypeorder = ('exact','begins','contains');
 7086:     return (\%srchtypes_desc,\@srchtypeorder);
 7087: }
 7088: 
 7089: sub usertype_update_row {
 7090:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
 7091:     my $datatable;
 7092:     my $numinrow = 4;
 7093:     foreach my $type (@{$types}) {
 7094:         if (defined($usertypes->{$type})) {
 7095:             $$rownums ++;
 7096:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
 7097:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
 7098:                           '</td><td class="LC_left_item"><table>';
 7099:             for (my $i=0; $i<@{$fields}; $i++) {
 7100:                 my $rem = $i%($numinrow);
 7101:                 if ($rem == 0) {
 7102:                     if ($i > 0) {
 7103:                         $datatable .= '</tr>';
 7104:                     }
 7105:                     $datatable .= '<tr>';
 7106:                 }
 7107:                 my $check = ' ';
 7108:                 if (ref($settings) eq 'HASH') {
 7109:                     if (ref($settings->{'fields'}) eq 'HASH') {
 7110:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
 7111:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
 7112:                                 $check = ' checked="checked" ';
 7113:                             }
 7114:                         }
 7115:                     }
 7116:                 }
 7117: 
 7118:                 if ($i == @{$fields}-1) {
 7119:                     my $colsleft = $numinrow - $rem;
 7120:                     if ($colsleft > 1) {
 7121:                         $datatable .= '<td colspan="'.$colsleft.'">';
 7122:                     } else {
 7123:                         $datatable .= '<td>';
 7124:                     }
 7125:                 } else {
 7126:                     $datatable .= '<td>';
 7127:                 }
 7128:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7129:                               '<input type="checkbox" name="updateable_'.$type.
 7130:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
 7131:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
 7132:             }
 7133:             $datatable .= '</tr></table></td></tr>';
 7134:         }
 7135:     }
 7136:     return $datatable;
 7137: }
 7138: 
 7139: sub modify_login {
 7140:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
 7141:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
 7142:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon);
 7143:     %title = ( coursecatalog => 'Display course catalog',
 7144:                adminmail => 'Display administrator E-mail address',
 7145:                helpdesk  => 'Display "Contact Helpdesk" link',
 7146:                newuser => 'Link for visitors to create a user account',
 7147:                loginheader => 'Log-in box header');
 7148:     @offon = ('off','on');
 7149:     if (ref($domconfig{login}) eq 'HASH') {
 7150:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
 7151:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
 7152:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
 7153:             }
 7154:         }
 7155:     }
 7156:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
 7157:                                            \%domconfig,\%loginhash);
 7158:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 7159:     foreach my $item (@toggles) {
 7160:         $loginhash{login}{$item} = $env{'form.'.$item};
 7161:     }
 7162:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
 7163:     if (ref($colchanges{'login'}) eq 'HASH') {  
 7164:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
 7165:                                          \%loginhash);
 7166:     }
 7167: 
 7168:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7169:     my %domservers = &Apache::lonnet::get_servers($dom);
 7170:     my @loginvia_attribs = ('serverpath','custompath','exempt');
 7171:     if (keys(%servers) > 1) {
 7172:         foreach my $lonhost (keys(%servers)) {
 7173:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
 7174:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
 7175:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
 7176:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
 7177:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
 7178:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 7179:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 7180:                         $changes{'loginvia'}{$lonhost} = 1;
 7181:                     } else {
 7182:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
 7183:                         $changes{'loginvia'}{$lonhost} = 1;
 7184:                     }
 7185:                 } else {
 7186:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 7187:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 7188:                         $changes{'loginvia'}{$lonhost} = 1;
 7189:                     }
 7190:                 }
 7191:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
 7192:                     foreach my $item (@loginvia_attribs) {
 7193:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
 7194:                     }
 7195:                 } else {
 7196:                     foreach my $item (@loginvia_attribs) {
 7197:                         my $new = $env{'form.'.$lonhost.'_'.$item};
 7198:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
 7199:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
 7200:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
 7201:                                 $new = '/';
 7202:                             }
 7203:                         }
 7204:                         if (($item eq 'custompath') && 
 7205:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
 7206:                             $new = '';
 7207:                         }
 7208:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
 7209:                             $changes{'loginvia'}{$lonhost} = 1;
 7210:                         }
 7211:                         if ($item eq 'exempt') {
 7212:                             $new = &check_exempt_addresses($new);
 7213:                         }
 7214:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
 7215:                     }
 7216:                 }
 7217:             } else {
 7218:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 7219:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 7220:                     $changes{'loginvia'}{$lonhost} = 1;
 7221:                     foreach my $item (@loginvia_attribs) {
 7222:                         my $new = $env{'form.'.$lonhost.'_'.$item};
 7223:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
 7224:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
 7225:                                 $new = '/';
 7226:                             }
 7227:                         }
 7228:                         if (($item eq 'custompath') && 
 7229:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
 7230:                             $new = '';
 7231:                         }
 7232:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
 7233:                     }
 7234:                 }
 7235:             }
 7236:         }
 7237:     }
 7238: 
 7239:     my $servadm = $r->dir_config('lonAdmEMail');
 7240:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 7241:     if (ref($domconfig{'login'}) eq 'HASH') {
 7242:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
 7243:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
 7244:                 if ($lang eq 'nolang') {
 7245:                     push(@currlangs,$lang);
 7246:                 } elsif (defined($langchoices{$lang})) {
 7247:                     push(@currlangs,$lang);
 7248:                 } else {
 7249:                     next;
 7250:                 }
 7251:             }
 7252:         }
 7253:     }
 7254:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
 7255:     if (@currlangs > 0) {
 7256:         foreach my $lang (@currlangs) {
 7257:             if (grep(/^\Q$lang\E$/,@delurls)) {
 7258:                 $changes{'helpurl'}{$lang} = 1;
 7259:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
 7260:                 $changes{'helpurl'}{$lang} = 1;
 7261:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
 7262:                 push(@newlangs,$lang);
 7263:             } else {
 7264:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
 7265:             }
 7266:         }
 7267:     }
 7268:     unless (grep(/^nolang$/,@currlangs)) {
 7269:         if ($env{'form.loginhelpurl_nolang.filename'}) {
 7270:             $changes{'helpurl'}{'nolang'} = 1;
 7271:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
 7272:             push(@newlangs,'nolang');
 7273:         }
 7274:     }
 7275:     if ($env{'form.loginhelpurl_add_lang'}) {
 7276:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
 7277:             ($env{'form.loginhelpurl_add_file.filename'})) {
 7278:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
 7279:             $addedfile = $env{'form.loginhelpurl_add_lang'};
 7280:         }
 7281:     }
 7282:     if ((@newlangs > 0) || ($addedfile)) {
 7283:         my $error;
 7284:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 7285:         if ($configuserok eq 'ok') {
 7286:             if ($switchserver) {
 7287:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
 7288:             } elsif ($author_ok eq 'ok') {
 7289:                 my @allnew = @newlangs;
 7290:                 if ($addedfile ne '') {
 7291:                     push(@allnew,$addedfile);
 7292:                 }
 7293:                 foreach my $lang (@allnew) {
 7294:                     my $formelem = 'loginhelpurl_'.$lang;
 7295:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
 7296:                         $formelem = 'loginhelpurl_add_file';
 7297:                     }
 7298:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 7299:                                                                "help/$lang",'','',$newfile{$lang});
 7300:                     if ($result eq 'ok') {
 7301:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
 7302:                         $changes{'helpurl'}{$lang} = 1;
 7303:                     } else {
 7304:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
 7305:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 7306:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
 7307:                             (!grep(/^\Q$lang\E$/,@delurls))) {
 7308:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
 7309:                         }
 7310:                     }
 7311:                 }
 7312:             } else {
 7313:                 $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);
 7314:             }
 7315:         } else {
 7316:             $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);
 7317:         }
 7318:         if ($error) {
 7319:             &Apache::lonnet::logthis($error);
 7320:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 7321:         }
 7322:     }
 7323: 
 7324:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
 7325:     if (ref($domconfig{'login'}) eq 'HASH') {
 7326:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
 7327:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
 7328:                 if ($domservers{$lonhost}) {
 7329:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
 7330:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
 7331:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
 7332:                     }
 7333:                 }
 7334:             }
 7335:         }
 7336:     }
 7337:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
 7338:     foreach my $lonhost (sort(keys(%domservers))) {
 7339:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
 7340:             $changes{'headtag'}{$lonhost} = 1;
 7341:         } else {
 7342:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
 7343:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
 7344:             }
 7345:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
 7346:                 push(@newhosts,$lonhost);
 7347:             } elsif ($currheadtagurls{$lonhost}) {
 7348:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
 7349:                 if ($currexempt{$lonhost}) {
 7350:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
 7351:                         $changes{'headtag'}{$lonhost} = 1;
 7352:                     }
 7353:                 } elsif ($possexempt{$lonhost}) {
 7354:                     $changes{'headtag'}{$lonhost} = 1;
 7355:                 }
 7356:                 if ($possexempt{$lonhost}) {
 7357:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
 7358:                 }
 7359:             }
 7360:         }
 7361:     }
 7362:     if (@newhosts) {
 7363:         my $error;
 7364:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 7365:         if ($configuserok eq 'ok') {
 7366:             if ($switchserver) {
 7367:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
 7368:             } elsif ($author_ok eq 'ok') {
 7369:                 foreach my $lonhost (@newhosts) {
 7370:                     my $formelem = 'loginheadtag_'.$lonhost;
 7371:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 7372:                                                                           "login/headtag/$lonhost",'','',
 7373:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
 7374:                     if ($result eq 'ok') {
 7375:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
 7376:                         $changes{'headtag'}{$lonhost} = 1;
 7377:                         if ($possexempt{$lonhost}) {
 7378:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
 7379:                         }
 7380:                     } else {
 7381:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
 7382:                                            $newheadtagurls{$lonhost},$result);
 7383:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 7384:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
 7385:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
 7386:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
 7387:                         }
 7388:                     }
 7389:                 }
 7390:             } else {
 7391:                 $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);
 7392:             }
 7393:         } else {
 7394:             $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);
 7395:         }
 7396:         if ($error) {
 7397:             &Apache::lonnet::logthis($error);
 7398:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 7399:         }
 7400:     }
 7401:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
 7402: 
 7403:     my $defaulthelpfile = '/adm/loginproblems.html';
 7404:     my $defaulttext = &mt('Default in use');
 7405: 
 7406:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
 7407:                                              $dom);
 7408:     if ($putresult eq 'ok') {
 7409:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 7410:         my %defaultchecked = (
 7411:                     'coursecatalog' => 'on',
 7412:                     'helpdesk'      => 'on',
 7413:                     'adminmail'     => 'off',
 7414:                     'newuser'       => 'off',
 7415:         );
 7416:         if (ref($domconfig{'login'}) eq 'HASH') {
 7417:             foreach my $item (@toggles) {
 7418:                 if ($defaultchecked{$item} eq 'on') { 
 7419:                     if (($domconfig{'login'}{$item} eq '0') &&
 7420:                         ($env{'form.'.$item} eq '1')) {
 7421:                         $changes{$item} = 1;
 7422:                     } elsif (($domconfig{'login'}{$item} eq '' ||
 7423:                               $domconfig{'login'}{$item} eq '1') &&
 7424:                              ($env{'form.'.$item} eq '0')) {
 7425:                         $changes{$item} = 1;
 7426:                     }
 7427:                 } elsif ($defaultchecked{$item} eq 'off') {
 7428:                     if (($domconfig{'login'}{$item} eq '1') &&
 7429:                         ($env{'form.'.$item} eq '0')) {
 7430:                         $changes{$item} = 1;
 7431:                     } elsif (($domconfig{'login'}{$item} eq '' ||
 7432:                               $domconfig{'login'}{$item} eq '0') &&
 7433:                              ($env{'form.'.$item} eq '1')) {
 7434:                         $changes{$item} = 1;
 7435:                     }
 7436:                 }
 7437:             }
 7438:         }
 7439:         if (keys(%changes) > 0 || $colchgtext) {
 7440:             &Apache::loncommon::devalidate_domconfig_cache($dom);
 7441:             if (ref($lastactref) eq 'HASH') {
 7442:                 $lastactref->{'domainconfig'} = 1;
 7443:             }
 7444:             $resulttext = &mt('Changes made:').'<ul>';
 7445:             foreach my $item (sort(keys(%changes))) {
 7446:                 if ($item eq 'loginvia') {
 7447:                     if (ref($changes{$item}) eq 'HASH') {
 7448:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
 7449:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
 7450:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
 7451:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
 7452:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
 7453:                                     $protocol = 'http' if ($protocol ne 'https');
 7454:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
 7455: 
 7456:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
 7457:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
 7458:                                     } else {
 7459:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
 7460:                                     }
 7461:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
 7462:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
 7463:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
 7464:                                     }
 7465:                                     $resulttext .= '</li>';
 7466:                                 } else {
 7467:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
 7468:                                 }
 7469:                             } else {
 7470:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
 7471:                             }
 7472:                         }
 7473:                         $resulttext .= '</ul></li>';
 7474:                     }
 7475:                 } elsif ($item eq 'helpurl') {
 7476:                     if (ref($changes{$item}) eq 'HASH') {
 7477:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
 7478:                             if (grep(/^\Q$lang\E$/,@delurls)) {
 7479:                                 my ($chg,$link);
 7480:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
 7481:                                 if ($lang eq 'nolang') {
 7482:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
 7483:                                 } else {
 7484:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
 7485:                                 }
 7486:                                 $resulttext .= '<li>'.$chg.'</li>';
 7487:                             } else {
 7488:                                 my $chg;
 7489:                                 if ($lang eq 'nolang') {
 7490:                                     $chg = &mt('custom log-in help file for no preferred language');
 7491:                                 } else {
 7492:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
 7493:                                 }
 7494:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
 7495:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
 7496:                                                       '?inhibitmenu=yes',$chg,600,500).
 7497:                                                '</li>';
 7498:                             }
 7499:                         }
 7500:                     }
 7501:                 } elsif ($item eq 'headtag') {
 7502:                     if (ref($changes{$item}) eq 'HASH') {
 7503:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
 7504:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
 7505:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
 7506:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
 7507:                                 $resulttext .= '<li><a href="'.
 7508:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
 7509:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 7510:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
 7511:                                 if ($possexempt{$lonhost}) {
 7512:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
 7513:                                 } else {
 7514:                                     $resulttext .= &mt('included for any client IP');
 7515:                                 }
 7516:                                 $resulttext .= '</li>';
 7517:                             }
 7518:                         }
 7519:                     }
 7520:                 } elsif ($item eq 'captcha') {
 7521:                     if (ref($loginhash{'login'}) eq 'HASH') {
 7522:                         my $chgtxt;
 7523:                         if ($loginhash{'login'}{$item} eq 'notused') {
 7524:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
 7525:                         } else {
 7526:                             my %captchas = &captcha_phrases();
 7527:                             if ($captchas{$loginhash{'login'}{$item}}) {
 7528:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
 7529:                             } else {
 7530:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
 7531:                             }
 7532:                         }
 7533:                         $resulttext .= '<li>'.$chgtxt.'</li>';
 7534:                     }
 7535:                 } elsif ($item eq 'recaptchakeys') {
 7536:                     if (ref($loginhash{'login'}) eq 'HASH') {
 7537:                         my ($privkey,$pubkey);
 7538:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
 7539:                             $pubkey = $loginhash{'login'}{$item}{'public'};
 7540:                             $privkey = $loginhash{'login'}{$item}{'private'};
 7541:                         }
 7542:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
 7543:                         if (!$pubkey) {
 7544:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
 7545:                         } else {
 7546:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
 7547:                         }
 7548:                         if (!$privkey) {
 7549:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
 7550:                         } else {
 7551:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
 7552:                         }
 7553:                         $chgtxt .= '</ul>';
 7554:                         $resulttext .= '<li>'.$chgtxt.'</li>';
 7555:                     }
 7556:                 } elsif ($item eq 'recaptchaversion') {
 7557:                     if (ref($loginhash{'login'}) eq 'HASH') {
 7558:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
 7559:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
 7560:                                            '</li>';
 7561:                         }
 7562:                     }
 7563:                 } else {
 7564:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
 7565:                 }
 7566:             }
 7567:             $resulttext .= $colchgtext.'</ul>';
 7568:         } else {
 7569:             $resulttext = &mt('No changes made to log-in page settings');
 7570:         }
 7571:     } else {
 7572:         $resulttext = '<span class="LC_error">'.
 7573: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 7574:     }
 7575:     if ($errors) {
 7576:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
 7577:                        $errors.'</ul>';
 7578:     }
 7579:     return $resulttext;
 7580: }
 7581: 
 7582: sub check_exempt_addresses {
 7583:     my ($iplist) = @_;
 7584:     $iplist =~ s/^\s+//;
 7585:     $iplist =~ s/\s+$//;
 7586:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
 7587:     my (@okips,$new);
 7588:     foreach my $ip (@poss_ips) {
 7589:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
 7590:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
 7591:                 push(@okips,$ip);
 7592:             }
 7593:         }
 7594:     }
 7595:     if (@okips > 0) {
 7596:         $new = join(',',@okips);
 7597:     } else {
 7598:         $new = '';
 7599:     }
 7600:     return $new;
 7601: }
 7602: 
 7603: sub color_font_choices {
 7604:     my %choices =
 7605:         &Apache::lonlocal::texthash (
 7606:             img => "Header",
 7607:             bgs => "Background colors",
 7608:             links => "Link colors",
 7609:             images => "Images",
 7610:             font => "Font color",
 7611:             fontmenu => "Font menu",
 7612:             pgbg => "Page",
 7613:             tabbg => "Header",
 7614:             sidebg => "Border",
 7615:             link => "Link",
 7616:             alink => "Active link",
 7617:             vlink => "Visited link",
 7618:         );
 7619:     return %choices;
 7620: }
 7621: 
 7622: sub modify_rolecolors {
 7623:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
 7624:     my ($resulttext,%rolehash);
 7625:     $rolehash{'rolecolors'} = {};
 7626:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
 7627:         if ($domconfig{'rolecolors'} eq '') {
 7628:             $domconfig{'rolecolors'} = {};
 7629:         }
 7630:     }
 7631:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
 7632:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
 7633:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
 7634:                                              $dom);
 7635:     if ($putresult eq 'ok') {
 7636:         if (keys(%changes) > 0) {
 7637:             &Apache::loncommon::devalidate_domconfig_cache($dom);
 7638:             if (ref($lastactref) eq 'HASH') {
 7639:                 $lastactref->{'domainconfig'} = 1;
 7640:             }
 7641:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
 7642:                                              $rolehash{'rolecolors'});
 7643:         } else {
 7644:             $resulttext = &mt('No changes made to default color schemes');
 7645:         }
 7646:     } else {
 7647:         $resulttext = '<span class="LC_error">'.
 7648: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 7649:     }
 7650:     if ($errors) {
 7651:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
 7652:                        $errors.'</ul>';
 7653:     }
 7654:     return $resulttext;
 7655: }
 7656: 
 7657: sub modify_colors {
 7658:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
 7659:     my (%changes,%choices);
 7660:     my @bgs;
 7661:     my @links = ('link','alink','vlink');
 7662:     my @logintext;
 7663:     my @images;
 7664:     my $servadm = $r->dir_config('lonAdmEMail');
 7665:     my $errors;
 7666:     my %defaults;
 7667:     foreach my $role (@{$roles}) {
 7668:         if ($role eq 'login') {
 7669:             %choices = &login_choices();
 7670:             @logintext = ('textcol','bgcol');
 7671:         } else {
 7672:             %choices = &color_font_choices();
 7673:         }
 7674:         if ($role eq 'login') {
 7675:             @images = ('img','logo','domlogo','login');
 7676:             @bgs = ('pgbg','mainbg','sidebg');
 7677:         } else {
 7678:             @images = ('img');
 7679:             @bgs = ('pgbg','tabbg','sidebg');
 7680:         }
 7681:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
 7682:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
 7683:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
 7684:         }
 7685:         if ($role eq 'login') {
 7686:             foreach my $item (@logintext) {
 7687:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
 7688:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
 7689:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
 7690:                 }
 7691:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
 7692:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
 7693:                 }
 7694:             }
 7695:         } else {
 7696:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
 7697:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
 7698:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
 7699:             }
 7700:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
 7701:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
 7702:             }
 7703:         }
 7704:         foreach my $item (@bgs) {
 7705:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
 7706:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
 7707:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
 7708:             }
 7709:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
 7710:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
 7711:             }
 7712:         }
 7713:         foreach my $item (@links) {
 7714:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
 7715:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
 7716:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
 7717:             }
 7718:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
 7719:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
 7720:             }
 7721:         }
 7722:         my ($configuserok,$author_ok,$switchserver) = 
 7723:             &config_check($dom,$confname,$servadm);
 7724:         my ($width,$height) = &thumb_dimensions();
 7725:         if (ref($domconfig->{$role}) ne 'HASH') {
 7726:             $domconfig->{$role} = {};
 7727:         }
 7728:         foreach my $img (@images) {
 7729:             if (($role eq 'login') && (($img eq 'img') || ($img eq 'logo'))) {  
 7730:                 if (defined($env{'form.login_showlogo_'.$img})) {
 7731:                     $confhash->{$role}{'showlogo'}{$img} = 1;
 7732:                 } else { 
 7733:                     $confhash->{$role}{'showlogo'}{$img} = 0;
 7734:                 }
 7735:             } 
 7736: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
 7737: 		 && !defined($domconfig->{$role}{$img})
 7738: 		 && !$env{'form.'.$role.'_del_'.$img}
 7739: 		 && $env{'form.'.$role.'_import_'.$img}) {
 7740: 		# import the old configured image from the .tab setting
 7741: 		# if they haven't provided a new one 
 7742: 		$domconfig->{$role}{$img} = 
 7743: 		    $env{'form.'.$role.'_import_'.$img};
 7744: 	    }
 7745:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
 7746:                 my $error;
 7747:                 if ($configuserok eq 'ok') {
 7748:                     if ($switchserver) {
 7749:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
 7750:                     } else {
 7751:                         if ($author_ok eq 'ok') {
 7752:                             my ($result,$logourl) = 
 7753:                                 &publishlogo($r,'upload',$role.'_'.$img,
 7754:                                            $dom,$confname,$img,$width,$height);
 7755:                             if ($result eq 'ok') {
 7756:                                 $confhash->{$role}{$img} = $logourl;
 7757:                                 $changes{$role}{'images'}{$img} = 1;
 7758:                             } else {
 7759:                                 $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);
 7760:                             }
 7761:                         } else {
 7762:                             $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);
 7763:                         }
 7764:                     }
 7765:                 } else {
 7766:                     $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);
 7767:                 }
 7768:                 if ($error) {
 7769:                     &Apache::lonnet::logthis($error);
 7770:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 7771:                 }
 7772:             } elsif ($domconfig->{$role}{$img} ne '') {
 7773:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 7774:                     my $error;
 7775:                     if ($configuserok eq 'ok') {
 7776: # is confname an author?
 7777:                         if ($switchserver eq '') {
 7778:                             if ($author_ok eq 'ok') {
 7779:                                 my ($result,$logourl) = 
 7780:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
 7781:                                             $dom,$confname,$img,$width,$height);
 7782:                                 if ($result eq 'ok') {
 7783:                                     $confhash->{$role}{$img} = $logourl;
 7784: 				    $changes{$role}{'images'}{$img} = 1;
 7785:                                 }
 7786:                             }
 7787:                         }
 7788:                     }
 7789:                 }
 7790:             }
 7791:         }
 7792:         if (ref($domconfig) eq 'HASH') {
 7793:             if (ref($domconfig->{$role}) eq 'HASH') {
 7794:                 foreach my $img (@images) {
 7795:                     if ($domconfig->{$role}{$img} ne '') {
 7796:                         if ($env{'form.'.$role.'_del_'.$img}) {
 7797:                             $confhash->{$role}{$img} = '';
 7798:                             $changes{$role}{'images'}{$img} = 1;
 7799:                         } else {
 7800:                             if ($confhash->{$role}{$img} eq '') {
 7801:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
 7802:                             }
 7803:                         }
 7804:                     } else {
 7805:                         if ($env{'form.'.$role.'_del_'.$img}) {
 7806:                             $confhash->{$role}{$img} = '';
 7807:                             $changes{$role}{'images'}{$img} = 1;
 7808:                         } 
 7809:                     }
 7810:                     if (($role eq 'login') && (($img eq 'logo') || ($img eq 'img'))) {
 7811:                         if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
 7812:                             if ($confhash->{$role}{'showlogo'}{$img} ne 
 7813:                                 $domconfig->{$role}{'showlogo'}{$img}) {
 7814:                                 $changes{$role}{'showlogo'}{$img} = 1; 
 7815:                             }
 7816:                         } else {
 7817:                             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
 7818:                                 $changes{$role}{'showlogo'}{$img} = 1;
 7819:                             }
 7820:                         }
 7821:                     }
 7822:                 }
 7823:                 if ($domconfig->{$role}{'font'} ne '') {
 7824:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
 7825:                         $changes{$role}{'font'} = 1;
 7826:                     }
 7827:                 } else {
 7828:                     if ($confhash->{$role}{'font'}) {
 7829:                         $changes{$role}{'font'} = 1;
 7830:                     }
 7831:                 }
 7832:                 if ($role ne 'login') {
 7833:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
 7834:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
 7835:                             $changes{$role}{'fontmenu'} = 1;
 7836:                         }
 7837:                     } else {
 7838:                         if ($confhash->{$role}{'fontmenu'}) {
 7839:                             $changes{$role}{'fontmenu'} = 1;
 7840:                         }
 7841:                     }
 7842:                 }
 7843:                 foreach my $item (@bgs) {
 7844:                     if ($domconfig->{$role}{$item} ne '') {
 7845:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
 7846:                             $changes{$role}{'bgs'}{$item} = 1;
 7847:                         } 
 7848:                     } else {
 7849:                         if ($confhash->{$role}{$item}) {
 7850:                             $changes{$role}{'bgs'}{$item} = 1;
 7851:                         }
 7852:                     }
 7853:                 }
 7854:                 foreach my $item (@links) {
 7855:                     if ($domconfig->{$role}{$item} ne '') {
 7856:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
 7857:                             $changes{$role}{'links'}{$item} = 1;
 7858:                         }
 7859:                     } else {
 7860:                         if ($confhash->{$role}{$item}) {
 7861:                             $changes{$role}{'links'}{$item} = 1;
 7862:                         }
 7863:                     }
 7864:                 }
 7865:                 foreach my $item (@logintext) {
 7866:                     if ($domconfig->{$role}{$item} ne '') {
 7867:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
 7868:                             $changes{$role}{'logintext'}{$item} = 1;
 7869:                         }
 7870:                     } else {
 7871:                         if ($confhash->{$role}{$item}) {
 7872:                             $changes{$role}{'logintext'}{$item} = 1;
 7873:                         }
 7874:                     }
 7875:                 }
 7876:             } else {
 7877:                 &default_change_checker($role,\@images,\@links,\@bgs,
 7878:                                         \@logintext,$confhash,\%changes); 
 7879:             }
 7880:         } else {
 7881:             &default_change_checker($role,\@images,\@links,\@bgs,
 7882:                                     \@logintext,$confhash,\%changes); 
 7883:         }
 7884:     }
 7885:     return ($errors,%changes);
 7886: }
 7887: 
 7888: sub config_check {
 7889:     my ($dom,$confname,$servadm) = @_;
 7890:     my ($configuserok,$author_ok,$switchserver,%currroles);
 7891:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
 7892:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
 7893:                                                    $confname,$servadm);
 7894:     if ($configuserok eq 'ok') {
 7895:         $switchserver = &check_switchserver($dom,$confname);
 7896:         if ($switchserver eq '') {
 7897:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
 7898:         }
 7899:     }
 7900:     return ($configuserok,$author_ok,$switchserver);
 7901: }
 7902: 
 7903: sub default_change_checker {
 7904:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
 7905:     foreach my $item (@{$links}) {
 7906:         if ($confhash->{$role}{$item}) {
 7907:             $changes->{$role}{'links'}{$item} = 1;
 7908:         }
 7909:     }
 7910:     foreach my $item (@{$bgs}) {
 7911:         if ($confhash->{$role}{$item}) {
 7912:             $changes->{$role}{'bgs'}{$item} = 1;
 7913:         }
 7914:     }
 7915:     foreach my $item (@{$logintext}) {
 7916:         if ($confhash->{$role}{$item}) {
 7917:             $changes->{$role}{'logintext'}{$item} = 1;
 7918:         }
 7919:     }
 7920:     foreach my $img (@{$images}) {
 7921:         if ($env{'form.'.$role.'_del_'.$img}) {
 7922:             $confhash->{$role}{$img} = '';
 7923:             $changes->{$role}{'images'}{$img} = 1;
 7924:         }
 7925:         if ($role eq 'login') {
 7926:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
 7927:                 $changes->{$role}{'showlogo'}{$img} = 1;
 7928:             }
 7929:         }
 7930:     }
 7931:     if ($confhash->{$role}{'font'}) {
 7932:         $changes->{$role}{'font'} = 1;
 7933:     }
 7934: }
 7935: 
 7936: sub display_colorchgs {
 7937:     my ($dom,$changes,$roles,$confhash) = @_;
 7938:     my (%choices,$resulttext);
 7939:     if (!grep(/^login$/,@{$roles})) {
 7940:         $resulttext = &mt('Changes made:').'<br />';
 7941:     }
 7942:     foreach my $role (@{$roles}) {
 7943:         if ($role eq 'login') {
 7944:             %choices = &login_choices();
 7945:         } else {
 7946:             %choices = &color_font_choices();
 7947:         }
 7948:         if (ref($changes->{$role}) eq 'HASH') {
 7949:             if ($role ne 'login') {
 7950:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
 7951:             }
 7952:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
 7953:                 if ($role ne 'login') {
 7954:                     $resulttext .= '<ul>';
 7955:                 }
 7956:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
 7957:                     if ($role ne 'login') {
 7958:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
 7959:                     }
 7960:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
 7961:                         if (($role eq 'login') && ($key eq 'showlogo')) {
 7962:                             if ($confhash->{$role}{$key}{$item}) {
 7963:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
 7964:                             } else {
 7965:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
 7966:                             }
 7967:                         } elsif ($confhash->{$role}{$item} eq '') {
 7968:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
 7969:                         } else {
 7970:                             my $newitem = $confhash->{$role}{$item};
 7971:                             if ($key eq 'images') {
 7972:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" valign="bottom" />';
 7973:                             }
 7974:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
 7975:                         }
 7976:                     }
 7977:                     if ($role ne 'login') {
 7978:                         $resulttext .= '</ul></li>';
 7979:                     }
 7980:                 } else {
 7981:                     if ($confhash->{$role}{$key} eq '') {
 7982:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
 7983:                     } else {
 7984:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
 7985:                     }
 7986:                 }
 7987:                 if ($role ne 'login') {
 7988:                     $resulttext .= '</ul>';
 7989:                 }
 7990:             }
 7991:         }
 7992:     }
 7993:     return $resulttext;
 7994: }
 7995: 
 7996: sub thumb_dimensions {
 7997:     return ('200','50');
 7998: }
 7999: 
 8000: sub check_dimensions {
 8001:     my ($inputfile) = @_;
 8002:     my ($fullwidth,$fullheight);
 8003:     if ($inputfile =~ m|^[/\w.\-]+$|) {
 8004:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
 8005:             my $imageinfo = <PIPE>;
 8006:             if (!close(PIPE)) {
 8007:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
 8008:             }
 8009:             chomp($imageinfo);
 8010:             my ($fullsize) = 
 8011:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
 8012:             if ($fullsize) {
 8013:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
 8014:             }
 8015:         }
 8016:     }
 8017:     return ($fullwidth,$fullheight);
 8018: }
 8019: 
 8020: sub check_configuser {
 8021:     my ($uhome,$dom,$confname,$servadm) = @_;
 8022:     my ($configuserok,%currroles);
 8023:     if ($uhome eq 'no_host') {
 8024:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
 8025:         my $configpass = &LONCAPA::Enrollment::create_password();
 8026:         $configuserok = 
 8027:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
 8028:                              $configpass,'','','','','',undef,$servadm);
 8029:     } else {
 8030:         $configuserok = 'ok';
 8031:         %currroles = 
 8032:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
 8033:     }
 8034:     return ($configuserok,%currroles);
 8035: }
 8036: 
 8037: sub check_authorstatus {
 8038:     my ($dom,$confname,%currroles) = @_;
 8039:     my $author_ok;
 8040:     if (!$currroles{':'.$dom.':au'}) {
 8041:         my $start = time;
 8042:         my $end = 0;
 8043:         $author_ok = 
 8044:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
 8045:                                         'au',$end,$start,'','','domconfig');
 8046:     } else {
 8047:         $author_ok = 'ok';
 8048:     }
 8049:     return $author_ok;
 8050: }
 8051: 
 8052: sub publishlogo {
 8053:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
 8054:     my ($output,$fname,$logourl);
 8055:     if ($action eq 'upload') {
 8056:         $fname=$env{'form.'.$formname.'.filename'};
 8057:         chop($env{'form.'.$formname});
 8058:     } else {
 8059:         ($fname) = ($formname =~ /([^\/]+)$/);
 8060:     }
 8061:     if ($savefileas ne '') {
 8062:         $fname = $savefileas;
 8063:     }
 8064:     $fname=&Apache::lonnet::clean_filename($fname);
 8065: # See if there is anything left
 8066:     unless ($fname) { return ('error: no uploaded file'); }
 8067:     $fname="$subdir/$fname";
 8068:     my $docroot=$r->dir_config('lonDocRoot');
 8069:     my $filepath="$docroot/priv";
 8070:     my $relpath = "$dom/$confname";
 8071:     my ($fnamepath,$file,$fetchthumb);
 8072:     $file=$fname;
 8073:     if ($fname=~m|/|) {
 8074:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 8075:     }
 8076:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
 8077:     my $count;
 8078:     for ($count=5;$count<=$#parts;$count++) {
 8079:         $filepath.="/$parts[$count]";
 8080:         if ((-e $filepath)!=1) {
 8081:             mkdir($filepath,02770);
 8082:         }
 8083:     }
 8084:     # Check for bad extension and disallow upload
 8085:     if ($file=~/\.(\w+)$/ &&
 8086:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 8087:         $output = 
 8088:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
 8089:     } elsif ($file=~/\.(\w+)$/ &&
 8090:         !defined(&Apache::loncommon::fileembstyle($1))) {
 8091:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 8092:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
 8093:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 8094:     } elsif (-d "$filepath/$file") {
 8095:         $output = &mt('Filename is a directory name - rename the file and re-upload');
 8096:     } else {
 8097:         my $source = $filepath.'/'.$file;
 8098:         my $logfile;
 8099:         if (!open($logfile,">>",$source.'.log')) {
 8100:             return (&mt('No write permission to Authoring Space'));
 8101:         }
 8102:         print $logfile
 8103: "\n================= Publish ".localtime()." ================\n".
 8104: $env{'user.name'}.':'.$env{'user.domain'}."\n";
 8105: # Save the file
 8106:         if (!open(FH,">",$source)) {
 8107:             &Apache::lonnet::logthis('Failed to create '.$source);
 8108:             return (&mt('Failed to create file'));
 8109:         }
 8110:         if ($action eq 'upload') {
 8111:             if (!print FH ($env{'form.'.$formname})) {
 8112:                 &Apache::lonnet::logthis('Failed to write to '.$source);
 8113:                 return (&mt('Failed to write file'));
 8114:             }
 8115:         } else {
 8116:             my $original = &Apache::lonnet::filelocation('',$formname);
 8117:             if(!copy($original,$source)) {
 8118:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
 8119:                 return (&mt('Failed to write file'));
 8120:             }
 8121:         }
 8122:         close(FH);
 8123:         chmod(0660, $source); # Permissions to rw-rw---.
 8124: 
 8125:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
 8126:         my $copyfile=$targetdir.'/'.$file;
 8127: 
 8128:         my @parts=split(/\//,$targetdir);
 8129:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 8130:         for (my $count=5;$count<=$#parts;$count++) {
 8131:             $path.="/$parts[$count]";
 8132:             if (!-e $path) {
 8133:                 print $logfile "\nCreating directory ".$path;
 8134:                 mkdir($path,02770);
 8135:             }
 8136:         }
 8137:         my $versionresult;
 8138:         if (-e $copyfile) {
 8139:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
 8140:         } else {
 8141:             $versionresult = 'ok';
 8142:         }
 8143:         if ($versionresult eq 'ok') {
 8144:             if (copy($source,$copyfile)) {
 8145:                 print $logfile "\nCopied original source to ".$copyfile."\n";
 8146:                 $output = 'ok';
 8147:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
 8148:                 push(@{$modified_urls},[$copyfile,$source]);
 8149:                 my $metaoutput = 
 8150:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
 8151:                 unless ($registered_cleanup) {
 8152:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
 8153:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
 8154:                     $registered_cleanup=1;
 8155:                 }
 8156:             } else {
 8157:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
 8158:                 $output = &mt('Failed to copy file to RES space').", $!";
 8159:             }
 8160:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 8161:                 my $inputfile = $filepath.'/'.$file;
 8162:                 my $outfile = $filepath.'/'.'tn-'.$file;
 8163:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
 8164:                 if ($fullwidth ne '' && $fullheight ne '') { 
 8165:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
 8166:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 8167:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
 8168:                         system({$args[0]} @args);
 8169:                         chmod(0660, $filepath.'/tn-'.$file);
 8170:                         if (-e $outfile) {
 8171:                             my $copyfile=$targetdir.'/tn-'.$file;
 8172:                             if (copy($outfile,$copyfile)) {
 8173:                                 print $logfile "\nCopied source to ".$copyfile."\n";
 8174:                                 my $thumb_metaoutput = 
 8175:                                     &write_metadata($dom,$confname,$formname,
 8176:                                                     $targetdir,'tn-'.$file,$logfile);
 8177:                                 push(@{$modified_urls},[$copyfile,$outfile]);
 8178:                                 unless ($registered_cleanup) {
 8179:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
 8180:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
 8181:                                     $registered_cleanup=1;
 8182:                                 }
 8183:                             } else {
 8184:                                 print $logfile "\nUnable to write ".$copyfile.
 8185:                                                ':'.$!."\n";
 8186:                             }
 8187:                         }
 8188:                     }
 8189:                 }
 8190:             }
 8191:         } else {
 8192:             $output = $versionresult;
 8193:         }
 8194:     }
 8195:     return ($output,$logourl);
 8196: }
 8197: 
 8198: sub logo_versioning {
 8199:     my ($targetdir,$file,$logfile) = @_;
 8200:     my $target = $targetdir.'/'.$file;
 8201:     my ($maxversion,$fn,$extn,$output);
 8202:     $maxversion = 0;
 8203:     if ($file =~ /^(.+)\.(\w+)$/) {
 8204:         $fn=$1;
 8205:         $extn=$2;
 8206:     }
 8207:     opendir(DIR,$targetdir);
 8208:     while (my $filename=readdir(DIR)) {
 8209:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
 8210:             $maxversion=($1>$maxversion)?$1:$maxversion;
 8211:         }
 8212:     }
 8213:     $maxversion++;
 8214:     print $logfile "\nCreating old version ".$maxversion."\n";
 8215:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
 8216:     if (copy($target,$copyfile)) {
 8217:         print $logfile "Copied old target to ".$copyfile."\n";
 8218:         $copyfile=$copyfile.'.meta';
 8219:         if (copy($target.'.meta',$copyfile)) {
 8220:             print $logfile "Copied old target metadata to ".$copyfile."\n";
 8221:             $output = 'ok';
 8222:         } else {
 8223:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
 8224:             $output = &mt('Failed to copy old meta').", $!, ";
 8225:         }
 8226:     } else {
 8227:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
 8228:         $output = &mt('Failed to copy old target').", $!, ";
 8229:     }
 8230:     return $output;
 8231: }
 8232: 
 8233: sub write_metadata {
 8234:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
 8235:     my (%metadatafields,%metadatakeys,$output);
 8236:     $metadatafields{'title'}=$formname;
 8237:     $metadatafields{'creationdate'}=time;
 8238:     $metadatafields{'lastrevisiondate'}=time;
 8239:     $metadatafields{'copyright'}='public';
 8240:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
 8241:                                          $env{'user.domain'};
 8242:     $metadatafields{'authorspace'}=$confname.':'.$dom;
 8243:     $metadatafields{'domain'}=$dom;
 8244:     {
 8245:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
 8246:         my $mfh;
 8247:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
 8248:             foreach (sort(keys(%metadatafields))) {
 8249:                 unless ($_=~/\./) {
 8250:                     my $unikey=$_;
 8251:                     $unikey=~/^([A-Za-z]+)/;
 8252:                     my $tag=$1;
 8253:                     $tag=~tr/A-Z/a-z/;
 8254:                     print $mfh "\n\<$tag";
 8255:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
 8256:                         my $value=$metadatafields{$unikey.'.'.$_};
 8257:                         $value=~s/\"/\'\'/g;
 8258:                         print $mfh ' '.$_.'="'.$value.'"';
 8259:                     }
 8260:                     print $mfh '>'.
 8261:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
 8262:                             .'</'.$tag.'>';
 8263:                 }
 8264:             }
 8265:             $output = 'ok';
 8266:             print $logfile "\nWrote metadata";
 8267:             close($mfh);
 8268:         } else {
 8269:             print $logfile "\nFailed to open metadata file";
 8270:             $output = &mt('Could not write metadata');
 8271:         }
 8272:     }
 8273:     return $output;
 8274: }
 8275: 
 8276: sub notifysubscribed {
 8277:     foreach my $targetsource (@{$modified_urls}){
 8278:         next unless (ref($targetsource) eq 'ARRAY');
 8279:         my ($target,$source)=@{$targetsource};
 8280:         if ($source ne '') {
 8281:             if (open(my $logfh,">>",$source.'.log')) {
 8282:                 print $logfh "\nCleanup phase: Notifications\n";
 8283:                 my @subscribed=&subscribed_hosts($target);
 8284:                 foreach my $subhost (@subscribed) {
 8285:                     print $logfh "\nNotifying host ".$subhost.':';
 8286:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
 8287:                     print $logfh $reply;
 8288:                 }
 8289:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
 8290:                 foreach my $subhost (@subscribedmeta) {
 8291:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
 8292:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
 8293:                                                         $subhost);
 8294:                     print $logfh $reply;
 8295:                 }
 8296:                 print $logfh "\n============ Done ============\n";
 8297:                 close($logfh);
 8298:             }
 8299:         }
 8300:     }
 8301:     return OK;
 8302: }
 8303: 
 8304: sub subscribed_hosts {
 8305:     my ($target) = @_;
 8306:     my @subscribed;
 8307:     if (open(my $fh,"<","$target.subscription")) {
 8308:         while (my $subline=<$fh>) {
 8309:             if ($subline =~ /^($match_lonid):/) {
 8310:                 my $host = $1;
 8311:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
 8312:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
 8313:                         push(@subscribed,$host);
 8314:                     }
 8315:                 }
 8316:             }
 8317:         }
 8318:     }
 8319:     return @subscribed;
 8320: }
 8321: 
 8322: sub check_switchserver {
 8323:     my ($dom,$confname) = @_;
 8324:     my ($allowed,$switchserver);
 8325:     my $home = &Apache::lonnet::homeserver($confname,$dom);
 8326:     if ($home eq 'no_host') {
 8327:         $home = &Apache::lonnet::domain($dom,'primary');
 8328:     }
 8329:     my @ids=&Apache::lonnet::current_machine_ids();
 8330:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 8331:     if (!$allowed) {
 8332: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 8333:     }
 8334:     return $switchserver;
 8335: }
 8336: 
 8337: sub modify_quotas {
 8338:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
 8339:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
 8340:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
 8341:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
 8342:         $validationfieldsref);
 8343:     if ($action eq 'quotas') {
 8344:         $context = 'tools'; 
 8345:     } else {
 8346:         $context = $action;
 8347:     }
 8348:     if ($context eq 'requestcourses') {
 8349:         @usertools = ('official','unofficial','community','textbook');
 8350:         @options =('norequest','approval','validate','autolimit');
 8351:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 8352:         %titles = &courserequest_titles();
 8353:         $toolregexp = join('|',@usertools);
 8354:         %conditions = &courserequest_conditions();
 8355:         $confname = $dom.'-domainconfig';
 8356:         my $servadm = $r->dir_config('lonAdmEMail');
 8357:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 8358:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
 8359:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
 8360:     } elsif ($context eq 'requestauthor') {
 8361:         @usertools = ('author');
 8362:         %titles = &authorrequest_titles();
 8363:     } else {
 8364:         @usertools = ('aboutme','blog','webdav','portfolio');
 8365:         %titles = &tool_titles();
 8366:     }
 8367:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 8368:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 8369:     foreach my $key (keys(%env)) {
 8370:         if ($context eq 'requestcourses') {
 8371:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
 8372:                 my $item = $1;
 8373:                 my $type = $2;
 8374:                 if ($type =~ /^limit_(.+)/) {
 8375:                     $limithash{$item}{$1} = $env{$key};
 8376:                 } else {
 8377:                     $confhash{$item}{$type} = $env{$key};
 8378:                 }
 8379:             }
 8380:         } elsif ($context eq 'requestauthor') {
 8381:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
 8382:                 $confhash{$1} = $env{$key};
 8383:             }
 8384:         } else {
 8385:             if ($key =~ /^form\.quota_(.+)$/) {
 8386:                 $confhash{'defaultquota'}{$1} = $env{$key};
 8387:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
 8388:                 $confhash{'authorquota'}{$1} = $env{$key};
 8389:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
 8390:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
 8391:             }
 8392:         }
 8393:     }
 8394:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 8395:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
 8396:         @approvalnotify = sort(@approvalnotify);
 8397:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
 8398:         my @crstypes = ('official','unofficial','community','textbook');
 8399:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
 8400:         foreach my $type (@hasuniquecode) {
 8401:             if (grep(/^\Q$type\E$/,@crstypes)) {
 8402:                 $confhash{'uniquecode'}{$type} = 1;
 8403:             }
 8404:         }
 8405:         my (%newbook,%allpos);
 8406:         if ($context eq 'requestcourses') {
 8407:             foreach my $type ('textbooks','templates') {
 8408:                 @{$allpos{$type}} = (); 
 8409:                 my $invalid;
 8410:                 if ($type eq 'textbooks') {
 8411:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
 8412:                 } else {
 8413:                     $invalid = &mt('Invalid LON-CAPA course for template');
 8414:                 }
 8415:                 if ($env{'form.'.$type.'_addbook'}) {
 8416:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
 8417:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
 8418:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
 8419:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
 8420:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
 8421:                         } else {
 8422:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
 8423:                             my $position = $env{'form.'.$type.'_addbook_pos'};
 8424:                             $position =~ s/\D+//g;
 8425:                             if ($position ne '') {
 8426:                                 $allpos{$type}[$position] = $newbook{$type};
 8427:                             }
 8428:                         }
 8429:                     } else {
 8430:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
 8431:                     }
 8432:                 }
 8433:             } 
 8434:         }
 8435:         if (ref($domconfig{$action}) eq 'HASH') {
 8436:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
 8437:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
 8438:                     $changes{'notify'}{'approval'} = 1;
 8439:                 }
 8440:             } else {
 8441:                 if ($confhash{'notify'}{'approval'}) {
 8442:                     $changes{'notify'}{'approval'} = 1;
 8443:                 }
 8444:             }
 8445:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
 8446:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
 8447:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
 8448:                         unless ($confhash{'uniquecode'}{$crstype}) {
 8449:                             $changes{'uniquecode'} = 1;
 8450:                         }
 8451:                     }
 8452:                     unless ($changes{'uniquecode'}) {
 8453:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
 8454:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
 8455:                                 $changes{'uniquecode'} = 1;
 8456:                             }
 8457:                         }
 8458:                     }
 8459:                } else {
 8460:                    $changes{'uniquecode'} = 1;
 8461:                }
 8462:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
 8463:                 $changes{'uniquecode'} = 1;
 8464:             }
 8465:             if ($context eq 'requestcourses') {
 8466:                 foreach my $type ('textbooks','templates') {
 8467:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
 8468:                         my %deletions;
 8469:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
 8470:                         if (@todelete) {
 8471:                             map { $deletions{$_} = 1; } @todelete;
 8472:                         }
 8473:                         my %imgdeletions;
 8474:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
 8475:                         if (@todeleteimages) {
 8476:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
 8477:                         }
 8478:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
 8479:                         for (my $i=0; $i<=$maxnum; $i++) {
 8480:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
 8481:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
 8482:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
 8483:                                 if ($deletions{$key}) {
 8484:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
 8485:                                         #FIXME need to obsolete item in RES space
 8486:                                     }
 8487:                                     next;
 8488:                                 } else {
 8489:                                     my $newpos = $env{'form.'.$itemid};
 8490:                                     $newpos =~ s/\D+//g;
 8491:                                     foreach my $item ('subject','title','publisher','author') {
 8492:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
 8493:                                                  ($type eq 'templates'));
 8494:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
 8495:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
 8496:                                             $changes{$type}{$key} = 1;
 8497:                                         }
 8498:                                     }
 8499:                                     $allpos{$type}[$newpos] = $key;
 8500:                                 }
 8501:                                 if ($imgdeletions{$key}) {
 8502:                                     $changes{$type}{$key} = 1;
 8503:                                     #FIXME need to obsolete item in RES space
 8504:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
 8505:                                     my ($cdom,$cnum) = split(/_/,$key);
 8506:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
 8507:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
 8508:                                     } else {
 8509:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
 8510:                                                                                       $cdom,$cnum,$type,$configuserok,
 8511:                                                                                       $switchserver,$author_ok);
 8512:                                         if ($imgurl) {
 8513:                                             $confhash{$type}{$key}{'image'} = $imgurl;
 8514:                                             $changes{$type}{$key} = 1; 
 8515:                                         }
 8516:                                         if ($error) {
 8517:                                             &Apache::lonnet::logthis($error);
 8518:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 8519:                                         }
 8520:                                     } 
 8521:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
 8522:                                     $confhash{$type}{$key}{'image'} = 
 8523:                                         $domconfig{$action}{$type}{$key}{'image'};
 8524:                                 }
 8525:                             }
 8526:                         }
 8527:                     }
 8528:                 }
 8529:             }
 8530:         } else {
 8531:             if ($confhash{'notify'}{'approval'}) {
 8532:                 $changes{'notify'}{'approval'} = 1;
 8533:             }
 8534:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
 8535:                 $changes{'uniquecode'} = 1;
 8536:             }
 8537:         }
 8538:         if ($context eq 'requestcourses') {
 8539:             foreach my $type ('textbooks','templates') {
 8540:                 if ($newbook{$type}) {
 8541:                     $changes{$type}{$newbook{$type}} = 1;
 8542:                     foreach my $item ('subject','title','publisher','author') {
 8543:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
 8544:                                  ($type eq 'template'));
 8545:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
 8546:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
 8547:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
 8548:                         }
 8549:                     }
 8550:                     if ($type eq 'textbooks') {
 8551:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
 8552:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
 8553:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
 8554:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
 8555:                             } else {
 8556:                                 my ($imageurl,$error) =
 8557:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
 8558:                                                             $configuserok,$switchserver,$author_ok);
 8559:                                 if ($imageurl) {
 8560:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
 8561:                                 }
 8562:                                 if ($error) {
 8563:                                     &Apache::lonnet::logthis($error);
 8564:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 8565:                                 }
 8566:                             }
 8567:                         }
 8568:                     }
 8569:                 }
 8570:                 if (@{$allpos{$type}} > 0) {
 8571:                     my $idx = 0;
 8572:                     foreach my $item (@{$allpos{$type}}) {
 8573:                         if ($item ne '') {
 8574:                             $confhash{$type}{$item}{'order'} = $idx;
 8575:                             if (ref($domconfig{$action}) eq 'HASH') {
 8576:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
 8577:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
 8578:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
 8579:                                             $changes{$type}{$item} = 1;
 8580:                                         }
 8581:                                     }
 8582:                                 }
 8583:                             }
 8584:                             $idx ++;
 8585:                         }
 8586:                     }
 8587:                 }
 8588:             }
 8589:             if (ref($validationitemsref) eq 'ARRAY') {
 8590:                 foreach my $item (@{$validationitemsref}) {
 8591:                     if ($item eq 'fields') {
 8592:                         my @changed;
 8593:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
 8594:                         if (@{$confhash{'validation'}{$item}} > 0) {
 8595:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
 8596:                         }
 8597:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 8598:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 8599:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
 8600:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
 8601:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
 8602:                                 } else {
 8603:                                     @changed = @{$confhash{'validation'}{$item}};
 8604:                                 }
 8605:                             } else {
 8606:                                 @changed = @{$confhash{'validation'}{$item}};
 8607:                             }
 8608:                         } else {
 8609:                             @changed = @{$confhash{'validation'}{$item}};
 8610:                         }
 8611:                         if (@changed) {
 8612:                             if ($confhash{'validation'}{$item}) {
 8613:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
 8614:                             } else {
 8615:                                 $changes{'validation'}{$item} = &mt('None');
 8616:                             }
 8617:                         }
 8618:                     } else {
 8619:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
 8620:                         if ($item eq 'markup') {
 8621:                             if ($env{'form.requestcourses_validation_'.$item}) {
 8622:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
 8623:                             }
 8624:                         }
 8625:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 8626:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 8627:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
 8628:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
 8629:                                 }
 8630:                             } else {
 8631:                                 if ($confhash{'validation'}{$item} ne '') {
 8632:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
 8633:                                 }
 8634:                             }
 8635:                         } else {
 8636:                             if ($confhash{'validation'}{$item} ne '') {
 8637:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
 8638:                             }
 8639:                         }
 8640:                     }
 8641:                 }
 8642:             }
 8643:             if ($env{'form.validationdc'}) {
 8644:                 my $newval = $env{'form.validationdc'};
 8645:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
 8646:                 if (exists($domcoords{$newval})) {
 8647:                     $confhash{'validation'}{'dc'} = $newval;
 8648:                 }
 8649:             }
 8650:             if (ref($confhash{'validation'}) eq 'HASH') {
 8651:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 8652:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 8653:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
 8654:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
 8655:                                 if ($confhash{'validation'}{'dc'} eq '') {
 8656:                                     $changes{'validation'}{'dc'} = &mt('None');
 8657:                                 } else {
 8658:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 8659:                                 }
 8660:                             }
 8661:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
 8662:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 8663:                         }
 8664:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
 8665:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 8666:                     }
 8667:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
 8668:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 8669:                 }
 8670:             } else {
 8671:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 8672:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 8673:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
 8674:                             $changes{'validation'}{'dc'} = &mt('None');
 8675:                         }
 8676:                     }
 8677:                 }
 8678:             }
 8679:         }
 8680:     } else {
 8681:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
 8682:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
 8683:     }
 8684:     foreach my $item (@usertools) {
 8685:         foreach my $type (@{$types},'default','_LC_adv') {
 8686:             my $unset; 
 8687:             if ($context eq 'requestcourses') {
 8688:                 $unset = '0';
 8689:                 if ($type eq '_LC_adv') {
 8690:                     $unset = '';
 8691:                 }
 8692:                 if ($confhash{$item}{$type} eq 'autolimit') {
 8693:                     $confhash{$item}{$type} .= '=';
 8694:                     unless ($limithash{$item}{$type} =~ /\D/) {
 8695:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
 8696:                     }
 8697:                 }
 8698:             } elsif ($context eq 'requestauthor') {
 8699:                 $unset = '0';
 8700:                 if ($type eq '_LC_adv') {
 8701:                     $unset = '';
 8702:                 }
 8703:             } else {
 8704:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
 8705:                     $confhash{$item}{$type} = 1;
 8706:                 } else {
 8707:                     $confhash{$item}{$type} = 0;
 8708:                 }
 8709:             }
 8710:             if (ref($domconfig{$action}) eq 'HASH') {
 8711:                 if ($action eq 'requestauthor') {
 8712:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
 8713:                         $changes{$type} = 1;
 8714:                     }
 8715:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
 8716:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
 8717:                         $changes{$item}{$type} = 1;
 8718:                     }
 8719:                 } else {
 8720:                     if ($context eq 'requestcourses') {
 8721:                         if ($confhash{$item}{$type} ne $unset) {
 8722:                             $changes{$item}{$type} = 1;
 8723:                         }
 8724:                     } else {
 8725:                         if (!$confhash{$item}{$type}) {
 8726:                             $changes{$item}{$type} = 1;
 8727:                         }
 8728:                     }
 8729:                 }
 8730:             } else {
 8731:                 if ($context eq 'requestcourses') {
 8732:                     if ($confhash{$item}{$type} ne $unset) {
 8733:                         $changes{$item}{$type} = 1;
 8734:                     }
 8735:                 } elsif ($context eq 'requestauthor') {
 8736:                     if ($confhash{$type} ne $unset) {
 8737:                         $changes{$type} = 1;
 8738:                     }
 8739:                 } else {
 8740:                     if (!$confhash{$item}{$type}) {
 8741:                         $changes{$item}{$type} = 1;
 8742:                     }
 8743:                 }
 8744:             }
 8745:         }
 8746:     }
 8747:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 8748:         if (ref($domconfig{'quotas'}) eq 'HASH') {
 8749:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 8750:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
 8751:                     if (exists($confhash{'defaultquota'}{$key})) {
 8752:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
 8753:                             $changes{'defaultquota'}{$key} = 1;
 8754:                         }
 8755:                     } else {
 8756:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
 8757:                     }
 8758:                 }
 8759:             } else {
 8760:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
 8761:                     if (exists($confhash{'defaultquota'}{$key})) {
 8762:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
 8763:                             $changes{'defaultquota'}{$key} = 1;
 8764:                         }
 8765:                     } else {
 8766:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
 8767:                     }
 8768:                 }
 8769:             }
 8770:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 8771:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
 8772:                     if (exists($confhash{'authorquota'}{$key})) {
 8773:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
 8774:                             $changes{'authorquota'}{$key} = 1;
 8775:                         }
 8776:                     } else {
 8777:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
 8778:                     }
 8779:                 }
 8780:             }
 8781:         }
 8782:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
 8783:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
 8784:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
 8785:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 8786:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
 8787:                             $changes{'defaultquota'}{$key} = 1;
 8788:                         }
 8789:                     } else {
 8790:                         if (!exists($domconfig{'quotas'}{$key})) {
 8791:                             $changes{'defaultquota'}{$key} = 1;
 8792:                         }
 8793:                     }
 8794:                 } else {
 8795:                     $changes{'defaultquota'}{$key} = 1;
 8796:                 }
 8797:             }
 8798:         }
 8799:         if (ref($confhash{'authorquota'}) eq 'HASH') {
 8800:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
 8801:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
 8802:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 8803:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
 8804:                             $changes{'authorquota'}{$key} = 1;
 8805:                         }
 8806:                     } else {
 8807:                         $changes{'authorquota'}{$key} = 1;
 8808:                     }
 8809:                 } else {
 8810:                     $changes{'authorquota'}{$key} = 1;
 8811:                 }
 8812:             }
 8813:         }
 8814:     }
 8815: 
 8816:     if ($context eq 'requestauthor') {
 8817:         $domdefaults{'requestauthor'} = \%confhash;
 8818:     } else {
 8819:         foreach my $key (keys(%confhash)) {
 8820:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
 8821:                 $domdefaults{$key} = $confhash{$key};
 8822:             }
 8823:         }
 8824:     }
 8825: 
 8826:     my %quotahash = (
 8827:                       $action => { %confhash }
 8828:                     );
 8829:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
 8830:                                              $dom);
 8831:     if ($putresult eq 'ok') {
 8832:         if (keys(%changes) > 0) {
 8833:             my $cachetime = 24*60*60;
 8834:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
 8835:             if (ref($lastactref) eq 'HASH') {
 8836:                 $lastactref->{'domdefaults'} = 1;
 8837:             }
 8838:             $resulttext = &mt('Changes made:').'<ul>';
 8839:             unless (($context eq 'requestcourses') ||
 8840:                     ($context eq 'requestauthor')) {
 8841:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
 8842:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
 8843:                     foreach my $type (@{$types},'default') {
 8844:                         if (defined($changes{'defaultquota'}{$type})) {
 8845:                             my $typetitle = $usertypes->{$type};
 8846:                             if ($type eq 'default') {
 8847:                                 $typetitle = $othertitle;
 8848:                             }
 8849:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
 8850:                         }
 8851:                     }
 8852:                     $resulttext .= '</ul></li>';
 8853:                 }
 8854:                 if (ref($changes{'authorquota'}) eq 'HASH') {
 8855:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
 8856:                     foreach my $type (@{$types},'default') {
 8857:                         if (defined($changes{'authorquota'}{$type})) {
 8858:                             my $typetitle = $usertypes->{$type};
 8859:                             if ($type eq 'default') {
 8860:                                 $typetitle = $othertitle;
 8861:                             }
 8862:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
 8863:                         }
 8864:                     }
 8865:                     $resulttext .= '</ul></li>';
 8866:                 }
 8867:             }
 8868:             my %newenv;
 8869:             foreach my $item (@usertools) {
 8870:                 my (%haschgs,%inconf);
 8871:                 if ($context eq 'requestauthor') {
 8872:                     %haschgs = %changes;
 8873:                     %inconf = %confhash;
 8874:                 } else {
 8875:                     if (ref($changes{$item}) eq 'HASH') {
 8876:                         %haschgs = %{$changes{$item}};
 8877:                     }
 8878:                     if (ref($confhash{$item}) eq 'HASH') {
 8879:                         %inconf = %{$confhash{$item}};
 8880:                     }
 8881:                 }
 8882:                 if (keys(%haschgs) > 0) {
 8883:                     my $newacc = 
 8884:                         &Apache::lonnet::usertools_access($env{'user.name'},
 8885:                                                           $env{'user.domain'},
 8886:                                                           $item,'reload',$context);
 8887:                     if (($context eq 'requestcourses') ||
 8888:                         ($context eq 'requestauthor')) {
 8889:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
 8890:                             $newenv{'environment.canrequest.'.$item} = $newacc;
 8891:                         }
 8892:                     } else {
 8893:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
 8894:                             $newenv{'environment.availabletools.'.$item} = $newacc;
 8895:                         }
 8896:                     }
 8897:                     unless ($context eq 'requestauthor') {
 8898:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
 8899:                     }
 8900:                     foreach my $type (@{$types},'default','_LC_adv') {
 8901:                         if ($haschgs{$type}) {
 8902:                             my $typetitle = $usertypes->{$type};
 8903:                             if ($type eq 'default') {
 8904:                                 $typetitle = $othertitle;
 8905:                             } elsif ($type eq '_LC_adv') {
 8906:                                 $typetitle = 'LON-CAPA Advanced Users'; 
 8907:                             }
 8908:                             if ($inconf{$type}) {
 8909:                                 if ($context eq 'requestcourses') {
 8910:                                     my $cond;
 8911:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
 8912:                                         if ($1 eq '') {
 8913:                                             $cond = &mt('(Automatic processing of any request).');
 8914:                                         } else {
 8915:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
 8916:                                         }
 8917:                                     } else { 
 8918:                                         $cond = $conditions{$inconf{$type}};
 8919:                                     }
 8920:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
 8921:                                 } elsif ($context eq 'requestauthor') {
 8922:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
 8923:                                                              $titles{$inconf{$type}},$typetitle);
 8924: 
 8925:                                 } else {
 8926:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
 8927:                                 }
 8928:                             } else {
 8929:                                 if ($type eq '_LC_adv') {
 8930:                                     if ($inconf{$type} eq '0') {
 8931:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
 8932:                                     } else { 
 8933:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
 8934:                                     }
 8935:                                 } else {
 8936:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
 8937:                                 }
 8938:                             }
 8939:                         }
 8940:                     }
 8941:                     unless ($context eq 'requestauthor') {
 8942:                         $resulttext .= '</ul></li>';
 8943:                     }
 8944:                 }
 8945:             }
 8946:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
 8947:                 if (ref($changes{'notify'}) eq 'HASH') {
 8948:                     if ($changes{'notify'}{'approval'}) {
 8949:                         if (ref($confhash{'notify'}) eq 'HASH') {
 8950:                             if ($confhash{'notify'}{'approval'}) {
 8951:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
 8952:                             } else {
 8953:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
 8954:                             }
 8955:                         }
 8956:                     }
 8957:                 }
 8958:             }
 8959:             if ($action eq 'requestcourses') {
 8960:                 my @offon = ('off','on');
 8961:                 if ($changes{'uniquecode'}) {
 8962:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
 8963:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
 8964:                         $resulttext .= '<li>'.
 8965:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
 8966:                                        '</li>';
 8967:                     } else {
 8968:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
 8969:                                        '</li>';
 8970:                     }
 8971:                 }
 8972:                 foreach my $type ('textbooks','templates') {
 8973:                     if (ref($changes{$type}) eq 'HASH') {
 8974:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
 8975:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
 8976:                             my %coursehash = &Apache::lonnet::coursedescription($key);
 8977:                             my $coursetitle = $coursehash{'description'};
 8978:                             my $position = $confhash{$type}{$key}{'order'} + 1;
 8979:                             $resulttext .= '<li>';
 8980:                             foreach my $item ('subject','title','publisher','author') {
 8981:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
 8982:                                          ($type eq 'templates'));
 8983:                                 my $name = $item.':';
 8984:                                 $name =~ s/^(\w)/\U$1/;
 8985:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
 8986:                             }
 8987:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
 8988:                             if ($type eq 'textbooks') {
 8989:                                 if ($confhash{$type}{$key}{'image'}) {
 8990:                                     $resulttext .= ' '.&mt('Image: [_1]',
 8991:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
 8992:                                                    ' alt="Textbook cover" />').'<br />';
 8993:                                 }
 8994:                             }
 8995:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
 8996:                         }
 8997:                         $resulttext .= '</ul></li>';
 8998:                     }
 8999:                 }
 9000:                 if (ref($changes{'validation'}) eq 'HASH') {
 9001:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
 9002:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
 9003:                         foreach my $item (@{$validationitemsref}) {
 9004:                             if (exists($changes{'validation'}{$item})) {
 9005:                                 if ($item eq 'markup') {
 9006:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
 9007:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
 9008:                                 } else {
 9009:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
 9010:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
 9011:                                 }
 9012:                             }
 9013:                         }
 9014:                         if (exists($changes{'validation'}{'dc'})) {
 9015:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
 9016:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
 9017:                         }
 9018:                     }
 9019:                 }
 9020:             }
 9021:             $resulttext .= '</ul>';
 9022:             if (keys(%newenv)) {
 9023:                 &Apache::lonnet::appenv(\%newenv);
 9024:             }
 9025:         } else {
 9026:             if ($context eq 'requestcourses') {
 9027:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
 9028:             } elsif ($context eq 'requestauthor') {
 9029:                 $resulttext = &mt('No changes made to rights to request author space.');
 9030:             } else {
 9031:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
 9032:             }
 9033:         }
 9034:     } else {
 9035:         $resulttext = '<span class="LC_error">'.
 9036: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 9037:     }
 9038:     if ($errors) {
 9039:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
 9040:                        '<ul>'.$errors.'</ul></p>';
 9041:     }
 9042:     return $resulttext;
 9043: }
 9044: 
 9045: sub process_textbook_image {
 9046:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
 9047:     my $filename = $env{'form.'.$caller.'.filename'};
 9048:     my ($error,$url);
 9049:     my ($width,$height) = (50,50);
 9050:     if ($configuserok eq 'ok') {
 9051:         if ($switchserver) {
 9052:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
 9053:                          $switchserver);
 9054:         } elsif ($author_ok eq 'ok') {
 9055:             my ($result,$imageurl) =
 9056:                 &publishlogo($r,'upload',$caller,$dom,$confname,
 9057:                              "$type/$cdom/$cnum/cover",$width,$height);
 9058:             if ($result eq 'ok') {
 9059:                 $url = $imageurl;
 9060:             } else {
 9061:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
 9062:             }
 9063:         } else {
 9064:             $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);
 9065:         }
 9066:     } else {
 9067:         $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);
 9068:     }
 9069:     return ($url,$error);
 9070: }
 9071: 
 9072: sub modify_autoenroll {
 9073:     my ($dom,$lastactref,%domconfig) = @_;
 9074:     my ($resulttext,%changes);
 9075:     my %currautoenroll;
 9076:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9077:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
 9078:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
 9079:         }
 9080:     }
 9081:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 9082:     my %title = ( run => 'Auto-enrollment active',
 9083:                   sender => 'Sender for notification messages',
 9084:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
 9085:                   failsafe => 'Failsafe for no drops if institutional data missing for a section');
 9086:     my @offon = ('off','on');
 9087:     my $sender_uname = $env{'form.sender_uname'};
 9088:     my $sender_domain = $env{'form.sender_domain'};
 9089:     if ($sender_domain eq '') {
 9090:         $sender_uname = '';
 9091:     } elsif ($sender_uname eq '') {
 9092:         $sender_domain = '';
 9093:     }
 9094:     my $coowners = $env{'form.autoassign_coowners'};
 9095:     my $failsafe = $env{'form.autoenroll_failsafe'};
 9096:     $failsafe =~ s{^\s+|\s+$}{}g;
 9097:     if ($failsafe =~ /\D/) {
 9098:         undef($failsafe);
 9099:     }
 9100:     my %autoenrollhash =  (
 9101:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
 9102:                                        'sender_uname' => $sender_uname,
 9103:                                        'sender_domain' => $sender_domain,
 9104:                                        'co-owners' => $coowners,
 9105:                                        'autofailsafe' => $failsafe,
 9106:                                 }
 9107:                      );
 9108:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
 9109:                                              $dom);
 9110:     if ($putresult eq 'ok') {
 9111:         if (exists($currautoenroll{'run'})) {
 9112:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
 9113:                  $changes{'run'} = 1;
 9114:              }
 9115:         } elsif ($autorun) {
 9116:             if ($env{'form.autoenroll_run'} ne '1') {
 9117:                  $changes{'run'} = 1;
 9118:             }
 9119:         }
 9120:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
 9121:             $changes{'sender'} = 1;
 9122:         }
 9123:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
 9124:             $changes{'sender'} = 1;
 9125:         }
 9126:         if ($currautoenroll{'co-owners'} ne '') {
 9127:             if ($currautoenroll{'co-owners'} ne $coowners) {
 9128:                 $changes{'coowners'} = 1;
 9129:             }
 9130:         } elsif ($coowners) {
 9131:             $changes{'coowners'} = 1;
 9132:         }
 9133:         if ($currautoenroll{'autofailsafe'} ne $failsafe) {
 9134:             $changes{'autofailsafe'} = 1;
 9135:         }
 9136:         if (keys(%changes) > 0) {
 9137:             $resulttext = &mt('Changes made:').'<ul>';
 9138:             if ($changes{'run'}) {
 9139:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
 9140:             }
 9141:             if ($changes{'sender'}) {
 9142:                 if ($sender_uname eq '' || $sender_domain eq '') {
 9143:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
 9144:                 } else {
 9145:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
 9146:                 }
 9147:             }
 9148:             if ($changes{'coowners'}) {
 9149:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
 9150:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
 9151:                 if (ref($lastactref) eq 'HASH') {
 9152:                     $lastactref->{'domainconfig'} = 1;
 9153:                 }
 9154:             }
 9155:             if ($changes{'autofailsafe'}) {
 9156:                 if ($failsafe ne '') {
 9157:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$failsafe).'</li>';
 9158:                 } else {
 9159:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section: deleted');
 9160:                 }
 9161:                 &Apache::lonnet::get_domain_defaults($dom,1);
 9162:                 if (ref($lastactref) eq 'HASH') {
 9163:                     $lastactref->{'domdefaults'} = 1;
 9164:                 }
 9165:             }
 9166:             $resulttext .= '</ul>';
 9167:         } else {
 9168:             $resulttext = &mt('No changes made to auto-enrollment settings');
 9169:         }
 9170:     } else {
 9171:         $resulttext = '<span class="LC_error">'.
 9172: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 9173:     }
 9174:     return $resulttext;
 9175: }
 9176: 
 9177: sub modify_autoupdate {
 9178:     my ($dom,%domconfig) = @_;
 9179:     my ($resulttext,%currautoupdate,%fields,%changes);
 9180:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
 9181:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
 9182:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
 9183:         }
 9184:     }
 9185:     my @offon = ('off','on');
 9186:     my %title = &Apache::lonlocal::texthash (
 9187:                    run => 'Auto-update:',
 9188:                    classlists => 'Updates to user information in classlists?'
 9189:                 );
 9190:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 9191:     my %fieldtitles = &Apache::lonlocal::texthash (
 9192:                         id => 'Student/Employee ID',
 9193:                         permanentemail => 'E-mail address',
 9194:                         lastname => 'Last Name',
 9195:                         firstname => 'First Name',
 9196:                         middlename => 'Middle Name',
 9197:                         generation => 'Generation',
 9198:                       );
 9199:     $othertitle = &mt('All users');
 9200:     if (keys(%{$usertypes}) >  0) {
 9201:         $othertitle = &mt('Other users');
 9202:     }
 9203:     foreach my $key (keys(%env)) {
 9204:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
 9205:             my ($usertype,$item) = ($1,$2);
 9206:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
 9207:                 if ($usertype eq 'default') {   
 9208:                     push(@{$fields{$1}},$2);
 9209:                 } elsif (ref($types) eq 'ARRAY') {
 9210:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
 9211:                         push(@{$fields{$1}},$2);
 9212:                     }
 9213:                 }
 9214:             }
 9215:         }
 9216:     }
 9217:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
 9218:     @lockablenames = sort(@lockablenames);
 9219:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
 9220:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
 9221:         if (@changed) {
 9222:             $changes{'lockablenames'} = 1;
 9223:         }
 9224:     } else {
 9225:         if (@lockablenames) {
 9226:             $changes{'lockablenames'} = 1;
 9227:         }
 9228:     }
 9229:     my %updatehash = (
 9230:                       autoupdate => { run => $env{'form.autoupdate_run'},
 9231:                                       classlists => $env{'form.classlists'},
 9232:                                       fields => {%fields},
 9233:                                       lockablenames => \@lockablenames,
 9234:                                     }
 9235:                      );
 9236:     foreach my $key (keys(%currautoupdate)) {
 9237:         if (($key eq 'run') || ($key eq 'classlists')) {
 9238:             if (exists($updatehash{autoupdate}{$key})) {
 9239:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
 9240:                     $changes{$key} = 1;
 9241:                 }
 9242:             }
 9243:         } elsif ($key eq 'fields') {
 9244:             if (ref($currautoupdate{$key}) eq 'HASH') {
 9245:                 foreach my $item (@{$types},'default') {
 9246:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
 9247:                         my $change = 0;
 9248:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
 9249:                             if (!exists($fields{$item})) {
 9250:                                 $change = 1;
 9251:                                 last;
 9252:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
 9253:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
 9254:                                     $change = 1;
 9255:                                     last;
 9256:                                 }
 9257:                             }
 9258:                         }
 9259:                         if ($change) {
 9260:                             push(@{$changes{$key}},$item);
 9261:                         }
 9262:                     } 
 9263:                 }
 9264:             }
 9265:         } elsif ($key eq 'lockablenames') {
 9266:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
 9267:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
 9268:                 if (@changed) {
 9269:                     $changes{'lockablenames'} = 1;
 9270:                 }
 9271:             } else {
 9272:                 if (@lockablenames) {
 9273:                     $changes{'lockablenames'} = 1;
 9274:                 }
 9275:             }
 9276:         }
 9277:     }
 9278:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
 9279:         if (@lockablenames) {
 9280:             $changes{'lockablenames'} = 1;
 9281:         }
 9282:     }
 9283:     foreach my $item (@{$types},'default') {
 9284:         if (defined($fields{$item})) {
 9285:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
 9286:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
 9287:                     my $change = 0;
 9288:                     if (ref($fields{$item}) eq 'ARRAY') {
 9289:                         foreach my $type (@{$fields{$item}}) {
 9290:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
 9291:                                 $change = 1;
 9292:                                 last;
 9293:                             }
 9294:                         }
 9295:                     }
 9296:                     if ($change) {
 9297:                         push(@{$changes{'fields'}},$item);
 9298:                     }
 9299:                 } else {
 9300:                     push(@{$changes{'fields'}},$item);
 9301:                 }
 9302:             } else {
 9303:                 push(@{$changes{'fields'}},$item);
 9304:             }
 9305:         }
 9306:     }
 9307:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
 9308:                                              $dom);
 9309:     if ($putresult eq 'ok') {
 9310:         if (keys(%changes) > 0) {
 9311:             $resulttext = &mt('Changes made:').'<ul>';
 9312:             foreach my $key (sort(keys(%changes))) {
 9313:                 if ($key eq 'lockablenames') {
 9314:                     $resulttext .= '<li>';
 9315:                     if (@lockablenames) {
 9316:                         $usertypes->{'default'} = $othertitle;
 9317:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
 9318:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
 9319:                     } else {
 9320:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
 9321:                     }
 9322:                     $resulttext .= '</li>';
 9323:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
 9324:                     foreach my $item (@{$changes{$key}}) {
 9325:                         my @newvalues;
 9326:                         foreach my $type (@{$fields{$item}}) {
 9327:                             push(@newvalues,$fieldtitles{$type});
 9328:                         }
 9329:                         my $newvaluestr;
 9330:                         if (@newvalues > 0) {
 9331:                             $newvaluestr = join(', ',@newvalues);
 9332:                         } else {
 9333:                             $newvaluestr = &mt('none');
 9334:                         }
 9335:                         if ($item eq 'default') {
 9336:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
 9337:                         } else {
 9338:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
 9339:                         }
 9340:                     }
 9341:                 } else {
 9342:                     my $newvalue;
 9343:                     if ($key eq 'run') {
 9344:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
 9345:                     } else {
 9346:                         $newvalue = $offon[$env{'form.'.$key}];
 9347:                     }
 9348:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
 9349:                 }
 9350:             }
 9351:             $resulttext .= '</ul>';
 9352:         } else {
 9353:             $resulttext = &mt('No changes made to autoupdates');
 9354:         }
 9355:     } else {
 9356:         $resulttext = '<span class="LC_error">'.
 9357: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 9358:     }
 9359:     return $resulttext;
 9360: }
 9361: 
 9362: sub modify_autocreate {
 9363:     my ($dom,%domconfig) = @_;
 9364:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
 9365:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
 9366:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
 9367:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
 9368:         }
 9369:     }
 9370:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
 9371:                  req => 'Auto-creation of validated requests for official courses',
 9372:                  xmldc => 'Identity of course creator of courses from XML files',
 9373:                );
 9374:     my @types = ('xml','req');
 9375:     foreach my $item (@types) {
 9376:         $newvals{$item} = $env{'form.autocreate_'.$item};
 9377:         $newvals{$item} =~ s/\D//g;
 9378:         $newvals{$item} = 0 if ($newvals{$item} eq '');
 9379:     }
 9380:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
 9381:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
 9382:     unless (exists($domcoords{$newvals{'xmldc'}})) {
 9383:         $newvals{'xmldc'} = '';
 9384:     } 
 9385:     %autocreatehash =  (
 9386:                         autocreate => { xml => $newvals{'xml'},
 9387:                                         req => $newvals{'req'},
 9388:                                       }
 9389:                        );
 9390:     if ($newvals{'xmldc'} ne '') {
 9391:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
 9392:     }
 9393:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
 9394:                                              $dom);
 9395:     if ($putresult eq 'ok') {
 9396:         my @items = @types;
 9397:         if ($newvals{'xml'}) {
 9398:             push(@items,'xmldc');
 9399:         }
 9400:         foreach my $item (@items) {
 9401:             if (exists($currautocreate{$item})) {
 9402:                 if ($currautocreate{$item} ne $newvals{$item}) {
 9403:                     $changes{$item} = 1;
 9404:                 }
 9405:             } elsif ($newvals{$item}) {
 9406:                 $changes{$item} = 1;
 9407:             }
 9408:         }
 9409:         if (keys(%changes) > 0) {
 9410:             my @offon = ('off','on'); 
 9411:             $resulttext = &mt('Changes made:').'<ul>';
 9412:             foreach my $item (@types) {
 9413:                 if ($changes{$item}) {
 9414:                     my $newtxt = $offon[$newvals{$item}];
 9415:                     $resulttext .= '<li>'.
 9416:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
 9417:                                        '<b>','</b>').
 9418:                                    '</li>';
 9419:                 }
 9420:             }
 9421:             if ($changes{'xmldc'}) {
 9422:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
 9423:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
 9424:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
 9425:             }
 9426:             $resulttext .= '</ul>';
 9427:         } else {
 9428:             $resulttext = &mt('No changes made to auto-creation settings');
 9429:         }
 9430:     } else {
 9431:         $resulttext = '<span class="LC_error">'.
 9432:             &mt('An error occurred: [_1]',$putresult).'</span>';
 9433:     }
 9434:     return $resulttext;
 9435: }
 9436: 
 9437: sub modify_directorysrch {
 9438:     my ($dom,$lastactref,%domconfig) = @_;
 9439:     my ($resulttext,%changes);
 9440:     my %currdirsrch;
 9441:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 9442:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
 9443:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
 9444:         }
 9445:     }
 9446:     my %title = ( available => 'Institutional directory search available',
 9447:                   localonly => 'Other domains can search institution',
 9448:                   lcavailable => 'LON-CAPA directory search available',
 9449:                   lclocalonly => 'Other domains can search LON-CAPA domain',
 9450:                   searchby => 'Search types',
 9451:                   searchtypes => 'Search latitude');
 9452:     my @offon = ('off','on');
 9453:     my @otherdoms = ('Yes','No');
 9454: 
 9455:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
 9456:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
 9457:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
 9458: 
 9459:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 9460:     if (keys(%{$usertypes}) == 0) {
 9461:         @cansearch = ('default');
 9462:     } else {
 9463:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
 9464:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
 9465:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
 9466:                     push(@{$changes{'cansearch'}},$type);
 9467:                 }
 9468:             }
 9469:             foreach my $type (@cansearch) {
 9470:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
 9471:                     push(@{$changes{'cansearch'}},$type);
 9472:                 }
 9473:             }
 9474:         } else {
 9475:             push(@{$changes{'cansearch'}},@cansearch);
 9476:         }
 9477:     }
 9478: 
 9479:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
 9480:         foreach my $by (@{$currdirsrch{'searchby'}}) {
 9481:             if (!grep(/^\Q$by\E$/,@searchby)) {
 9482:                 push(@{$changes{'searchby'}},$by);
 9483:             }
 9484:         }
 9485:         foreach my $by (@searchby) {
 9486:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
 9487:                 push(@{$changes{'searchby'}},$by);
 9488:             }
 9489:         }
 9490:     } else {
 9491:         push(@{$changes{'searchby'}},@searchby);
 9492:     }
 9493: 
 9494:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
 9495:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
 9496:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
 9497:                 push(@{$changes{'searchtypes'}},$type);
 9498:             }
 9499:         }
 9500:         foreach my $type (@searchtypes) {
 9501:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
 9502:                 push(@{$changes{'searchtypes'}},$type);
 9503:             }
 9504:         }
 9505:     } else {
 9506:         if (exists($currdirsrch{'searchtypes'})) {
 9507:             foreach my $type (@searchtypes) {  
 9508:                 if ($type ne $currdirsrch{'searchtypes'}) { 
 9509:                     push(@{$changes{'searchtypes'}},$type);
 9510:                 }
 9511:             }
 9512:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
 9513:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
 9514:             }   
 9515:         } else {
 9516:             push(@{$changes{'searchtypes'}},@searchtypes); 
 9517:         }
 9518:     }
 9519: 
 9520:     my %dirsrch_hash =  (
 9521:             directorysrch => { available => $env{'form.dirsrch_available'},
 9522:                                cansearch => \@cansearch,
 9523:                                localonly => $env{'form.dirsrch_instlocalonly'},
 9524:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
 9525:                                lcavailable => $env{'form.dirsrch_domavailable'},
 9526:                                searchby => \@searchby,
 9527:                                searchtypes => \@searchtypes,
 9528:                              }
 9529:             );
 9530:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
 9531:                                              $dom);
 9532:     if ($putresult eq 'ok') {
 9533:         if (exists($currdirsrch{'available'})) {
 9534:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
 9535:                  $changes{'available'} = 1;
 9536:              }
 9537:         } else {
 9538:             if ($env{'form.dirsrch_available'} eq '1') {
 9539:                 $changes{'available'} = 1;
 9540:             }
 9541:         }
 9542:         if (exists($currdirsrch{'lcavailable'})) {
 9543:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
 9544:                 $changes{'lcavailable'} = 1;
 9545:             }
 9546:         } else {
 9547:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
 9548:                 $changes{'lcavailable'} = 1;
 9549:             }
 9550:         }
 9551:         if (exists($currdirsrch{'localonly'})) {
 9552:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
 9553:                 $changes{'localonly'} = 1;
 9554:             }
 9555:         } else {
 9556:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
 9557:                 $changes{'localonly'} = 1;
 9558:             }
 9559:         }
 9560:         if (exists($currdirsrch{'lclocalonly'})) {
 9561:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
 9562:                 $changes{'lclocalonly'} = 1;
 9563:             }
 9564:         } else {
 9565:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
 9566:                 $changes{'lclocalonly'} = 1;
 9567:             }
 9568:         }
 9569:         if (keys(%changes) > 0) {
 9570:             $resulttext = &mt('Changes made:').'<ul>';
 9571:             if ($changes{'available'}) {
 9572:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
 9573:             }
 9574:             if ($changes{'lcavailable'}) {
 9575:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
 9576:             }
 9577:             if ($changes{'localonly'}) {
 9578:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
 9579:             }
 9580:             if ($changes{'lclocalonly'}) {
 9581:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
 9582:             }
 9583:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
 9584:                 my $chgtext;
 9585:                 if (ref($usertypes) eq 'HASH') {
 9586:                     if (keys(%{$usertypes}) > 0) {
 9587:                         foreach my $type (@{$types}) {
 9588:                             if (grep(/^\Q$type\E$/,@cansearch)) {
 9589:                                 $chgtext .= $usertypes->{$type}.'; ';
 9590:                             }
 9591:                         }
 9592:                         if (grep(/^default$/,@cansearch)) {
 9593:                             $chgtext .= $othertitle;
 9594:                         } else {
 9595:                             $chgtext =~ s/\; $//;
 9596:                         }
 9597:                         $resulttext .=
 9598:                             '<li>'.
 9599:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
 9600:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
 9601:                             '</li>';
 9602:                     }
 9603:                 }
 9604:             }
 9605:             if (ref($changes{'searchby'}) eq 'ARRAY') {
 9606:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
 9607:                 my $chgtext;
 9608:                 foreach my $type (@{$titleorder}) {
 9609:                     if (grep(/^\Q$type\E$/,@searchby)) {
 9610:                         if (defined($searchtitles->{$type})) {
 9611:                             $chgtext .= $searchtitles->{$type}.'; ';
 9612:                         }
 9613:                     }
 9614:                 }
 9615:                 $chgtext =~ s/\; $//;
 9616:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
 9617:             }
 9618:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
 9619:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
 9620:                 my $chgtext;
 9621:                 foreach my $type (@{$srchtypeorder}) {
 9622:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
 9623:                         if (defined($srchtypes_desc->{$type})) {
 9624:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
 9625:                         }
 9626:                     }
 9627:                 }
 9628:                 $chgtext =~ s/\; $//;
 9629:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
 9630:             }
 9631:             $resulttext .= '</ul>';
 9632:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
 9633:             if (ref($lastactref) eq 'HASH') {
 9634:                 $lastactref->{'directorysrch'} = 1;
 9635:             }
 9636:         } else {
 9637:             $resulttext = &mt('No changes made to directory search settings');
 9638:         }
 9639:     } else {
 9640:         $resulttext = '<span class="LC_error">'.
 9641:                       &mt('An error occurred: [_1]',$putresult).'</span>';
 9642:     }
 9643:     return $resulttext;
 9644: }
 9645: 
 9646: sub modify_contacts {
 9647:     my ($dom,$lastactref,%domconfig) = @_;
 9648:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
 9649:     if (ref($domconfig{'contacts'}) eq 'HASH') {
 9650:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
 9651:             $currsetting{$key} = $domconfig{'contacts'}{$key};
 9652:         }
 9653:     }
 9654:     my (%others,%to,%bcc,%includestr,%includeloc);
 9655:     my @contacts = ('supportemail','adminemail');
 9656:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
 9657:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail',hostipmail');
 9658:     my @toggles = ('reporterrors','reportupdates');
 9659:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 9660:     foreach my $type (@mailings) {
 9661:         @{$newsetting{$type}} = 
 9662:             &Apache::loncommon::get_env_multiple('form.'.$type);
 9663:         foreach my $item (@contacts) {
 9664:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
 9665:                 $contacts_hash{contacts}{$type}{$item} = 1;
 9666:             } else {
 9667:                 $contacts_hash{contacts}{$type}{$item} = 0;
 9668:             }
 9669:         }
 9670:         $others{$type} = $env{'form.'.$type.'_others'};
 9671:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
 9672:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 9673:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
 9674:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
 9675:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
 9676:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
 9677:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
 9678:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
 9679:             }
 9680:         }
 9681:     }
 9682:     foreach my $item (@contacts) {
 9683:         $to{$item} = $env{'form.'.$item};
 9684:         $contacts_hash{'contacts'}{$item} = $to{$item};
 9685:     }
 9686:     foreach my $item (@toggles) {
 9687:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
 9688:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
 9689:         }
 9690:     }
 9691:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
 9692:         foreach my $field (@{$fields}) {
 9693:             if (ref($possoptions->{$field}) eq 'ARRAY') {
 9694:                 my $value = $env{'form.helpform_'.$field};
 9695:                 $value =~ s/^\s+|\s+$//g;
 9696:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
 9697:                     $contacts_hash{contacts}{'helpform'}{$field} = $value;
 9698:                     if ($field eq 'screenshot') {
 9699:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
 9700:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
 9701:                             $contacts_hash{contacts}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
 9702:                         }
 9703:                     }
 9704:                 }
 9705:             }
 9706:         }
 9707:     }
 9708:     if (keys(%currsetting) > 0) {
 9709:         foreach my $item (@contacts) {
 9710:             if ($to{$item} ne $currsetting{$item}) {
 9711:                 $changes{$item} = 1;
 9712:             }
 9713:         }
 9714:         foreach my $type (@mailings) {
 9715:             foreach my $item (@contacts) {
 9716:                 if (ref($currsetting{$type}) eq 'HASH') {
 9717:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
 9718:                         push(@{$changes{$type}},$item);
 9719:                     }
 9720:                 } else {
 9721:                     push(@{$changes{$type}},@{$newsetting{$type}});
 9722:                 }
 9723:             }
 9724:             if ($others{$type} ne $currsetting{$type}{'others'}) {
 9725:                 push(@{$changes{$type}},'others');
 9726:             }
 9727:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 9728:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
 9729:                     push(@{$changes{$type}},'bcc'); 
 9730:                 }
 9731:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
 9732:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
 9733:                     push(@{$changes{$type}},'include');
 9734:                 }
 9735:             }
 9736:         }
 9737:         if (ref($fields) eq 'ARRAY') {
 9738:             if (ref($currsetting{'helpform'}) eq 'HASH') {
 9739:                 foreach my $field (@{$fields}) {
 9740:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
 9741:                         push(@{$changes{'helpform'}},$field);
 9742:                     }
 9743:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
 9744:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
 9745:                             push(@{$changes{'helpform'}},'maxsize');
 9746:                         }
 9747:                     }
 9748:                 }
 9749:             } else {
 9750:                 foreach my $field (@{$fields}) {
 9751:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
 9752:                         push(@{$changes{'helpform'}},$field);
 9753:                     }
 9754:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
 9755:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
 9756:                             push(@{$changes{'helpform'}},'maxsize');
 9757:                         }
 9758:                     }
 9759:                 }
 9760:             }
 9761:         }
 9762:     } else {
 9763:         my %default;
 9764:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 9765:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 9766:         $default{'errormail'} = 'adminemail';
 9767:         $default{'packagesmail'} = 'adminemail';
 9768:         $default{'helpdeskmail'} = 'supportemail';
 9769:         $default{'otherdomsmail'} = 'supportemail';
 9770:         $default{'lonstatusmail'} = 'adminemail';
 9771:         $default{'requestsmail'} = 'adminemail';
 9772:         $default{'updatesmail'} = 'adminemail';
 9773:         $default{'hostipmail'} = 'adminemail';
 9774:         foreach my $item (@contacts) {
 9775:            if ($to{$item} ne $default{$item}) {
 9776:                $changes{$item} = 1;
 9777:            }
 9778:         }
 9779:         foreach my $type (@mailings) {
 9780:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
 9781:                 push(@{$changes{$type}},@{$newsetting{$type}});
 9782:             }
 9783:             if ($others{$type} ne '') {
 9784:                 push(@{$changes{$type}},'others');
 9785:             }
 9786:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 9787:                 if ($bcc{$type} ne '') {
 9788:                     push(@{$changes{$type}},'bcc');
 9789:                 }
 9790:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
 9791:                     push(@{$changes{$type}},'include');
 9792:                 }
 9793:             }
 9794:         }
 9795:         if (ref($fields) eq 'ARRAY') {
 9796:             foreach my $field (@{$fields}) {
 9797:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
 9798:                     push(@{$changes{'helpform'}},$field);
 9799:                 }
 9800:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
 9801:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
 9802:                         push(@{$changes{'helpform'}},'maxsize');
 9803:                     }
 9804:                 }
 9805:             }
 9806:         }
 9807:     }
 9808:     foreach my $item (@toggles) {
 9809:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
 9810:             $changes{$item} = 1;
 9811:         } elsif ((!$env{'form.'.$item}) &&
 9812:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
 9813:             $changes{$item} = 1;
 9814:         }
 9815:     }
 9816:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
 9817:                                              $dom);
 9818:     if ($putresult eq 'ok') {
 9819:         if (keys(%changes) > 0) {
 9820:             &Apache::loncommon::devalidate_domconfig_cache($dom);
 9821:             if (ref($lastactref) eq 'HASH') {
 9822:                 $lastactref->{'domainconfig'} = 1;
 9823:             }
 9824:             my ($titles,$short_titles)  = &contact_titles();
 9825:             $resulttext = &mt('Changes made:').'<ul>';
 9826:             foreach my $item (@contacts) {
 9827:                 if ($changes{$item}) {
 9828:                     $resulttext .= '<li>'.$titles->{$item}.
 9829:                                     &mt(' set to: ').
 9830:                                     '<span class="LC_cusr_emph">'.
 9831:                                     $to{$item}.'</span></li>';
 9832:                 }
 9833:             }
 9834:             foreach my $type (@mailings) {
 9835:                 if (ref($changes{$type}) eq 'ARRAY') {
 9836:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 9837:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
 9838:                     } else {
 9839:                         $resulttext .= '<li>'.$titles->{$type}.': ';
 9840:                     }
 9841:                     my @text;
 9842:                     foreach my $item (@{$newsetting{$type}}) {
 9843:                         push(@text,$short_titles->{$item});
 9844:                     }
 9845:                     if ($others{$type} ne '') {
 9846:                         push(@text,$others{$type});
 9847:                     }
 9848:                     if (@text) {
 9849:                         $resulttext .= '<span class="LC_cusr_emph">'.
 9850:                                        join(', ',@text).'</span>';
 9851:                     }
 9852:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 9853:                         if ($bcc{$type} ne '') {
 9854:                             my $bcctext;
 9855:                             if (@text) {
 9856:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
 9857:                             } else {
 9858:                                 $bcctext = '(Bcc)';
 9859:                             }
 9860:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
 9861:                         } elsif (!@text) {
 9862:                             $resulttext .= &mt('No one');
 9863:                         }
 9864:                         if ($includestr{$type} ne '') {
 9865:                             if ($includeloc{$type} eq 'b') {
 9866:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
 9867:                             } elsif ($includeloc{$type} eq 's') {
 9868:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
 9869:                             }
 9870:                         }
 9871:                     } elsif (!@text) {
 9872:                         $resulttext .= &mt('No recipients');
 9873:                     }
 9874:                     $resulttext .= '</li>';
 9875:                 }
 9876:             }
 9877:             my @offon = ('off','on');
 9878:             if ($changes{'reporterrors'}) {
 9879:                 $resulttext .= '<li>'.
 9880:                                &mt('E-mail error reports to [_1] set to "'.
 9881:                                    $offon[$env{'form.reporterrors'}].'".',
 9882:                                    &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 9883:                                        &mt('LON-CAPA core group - MSU'),600,500)).
 9884:                                '</li>';
 9885:             }
 9886:             if ($changes{'reportupdates'}) {
 9887:                 $resulttext .= '<li>'.
 9888:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
 9889:                                     $offon[$env{'form.reportupdates'}].'".',
 9890:                                     &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 9891:                                         &mt('LON-CAPA core group - MSU'),600,500)).
 9892:                                 '</li>';
 9893:             }
 9894:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
 9895:                 my (@optional,@required,@unused,$maxsizechg);
 9896:                 foreach my $field (@{$changes{'helpform'}}) {
 9897:                     if ($field eq 'maxsize') {
 9898:                         $maxsizechg = 1;
 9899:                         next;
 9900:                     }
 9901:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
 9902:                         push(@optional,$field);
 9903:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
 9904:                         push(@unused,$field);
 9905:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
 9906:                         push(@required,$field);
 9907:                     }
 9908:                 }
 9909:                 if (@optional) {
 9910:                     $resulttext .= '<li>'.
 9911:                                    &mt('Help form fields changed to "Optional": [_1].',
 9912:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
 9913:                                    '</li>';
 9914:                 }
 9915:                 if (@required) {
 9916:                     $resulttext .= '<li>'.
 9917:                                    &mt('Help form fields changed to "Required": [_1].',
 9918:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
 9919:                                    '</li>';
 9920:                 }
 9921:                 if (@unused) {
 9922:                     $resulttext .= '<li>'.
 9923:                                    &mt('Help form fields changed to "Not shown": [_1].',
 9924:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
 9925:                                    '</li>';
 9926:                 }
 9927:                 if ($maxsizechg) {
 9928:                     $resulttext .= '<li>'.
 9929:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
 9930:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
 9931:                                    '</li>';
 9932: 
 9933:                 }
 9934:             }
 9935:             $resulttext .= '</ul>';
 9936:         } else {
 9937:             $resulttext = &mt('No changes made to contacts and form settings');
 9938:         }
 9939:     } else {
 9940:         $resulttext = '<span class="LC_error">'.
 9941:             &mt('An error occurred: [_1].',$putresult).'</span>';
 9942:     }
 9943:     return $resulttext;
 9944: }
 9945: 
 9946: sub modify_usercreation {
 9947:     my ($dom,%domconfig) = @_;
 9948:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
 9949:     my $warningmsg;
 9950:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9951:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
 9952:             if ($key eq 'cancreate') {
 9953:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
 9954:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
 9955:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
 9956:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
 9957:                         } else {
 9958:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
 9959:                         }
 9960:                     }
 9961:                 }
 9962:             } elsif ($key eq 'email_rule') {
 9963:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
 9964:             } else {
 9965:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
 9966:             }
 9967:         }
 9968:     }
 9969:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
 9970:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
 9971:     my @contexts = ('author','course','requestcrs');
 9972:     foreach my $item(@contexts) {
 9973:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
 9974:     }
 9975:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
 9976:         foreach my $item (@contexts) {
 9977:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
 9978:                 push(@{$changes{'cancreate'}},$item);
 9979:             }
 9980:         }
 9981:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
 9982:         foreach my $item (@contexts) {
 9983:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
 9984:                 if ($cancreate{$item} ne 'any') {
 9985:                     push(@{$changes{'cancreate'}},$item);
 9986:                 }
 9987:             } else {
 9988:                 if ($cancreate{$item} ne 'none') {
 9989:                     push(@{$changes{'cancreate'}},$item);
 9990:                 }
 9991:             }
 9992:         }
 9993:     } else {
 9994:         foreach my $item (@contexts)  {
 9995:             push(@{$changes{'cancreate'}},$item);
 9996:         }
 9997:     }
 9998: 
 9999:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
10000:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
10001:             if (!grep(/^\Q$type\E$/,@username_rule)) {
10002:                 push(@{$changes{'username_rule'}},$type);
10003:             }
10004:         }
10005:         foreach my $type (@username_rule) {
10006:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
10007:                 push(@{$changes{'username_rule'}},$type);
10008:             }
10009:         }
10010:     } else {
10011:         push(@{$changes{'username_rule'}},@username_rule);
10012:     }
10013: 
10014:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
10015:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
10016:             if (!grep(/^\Q$type\E$/,@id_rule)) {
10017:                 push(@{$changes{'id_rule'}},$type);
10018:             }
10019:         }
10020:         foreach my $type (@id_rule) {
10021:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
10022:                 push(@{$changes{'id_rule'}},$type);
10023:             }
10024:         }
10025:     } else {
10026:         push(@{$changes{'id_rule'}},@id_rule);
10027:     }
10028: 
10029:     my @authen_contexts = ('author','course','domain');
10030:     my @authtypes = ('int','krb4','krb5','loc');
10031:     my %authhash;
10032:     foreach my $item (@authen_contexts) {
10033:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
10034:         foreach my $auth (@authtypes) {
10035:             if (grep(/^\Q$auth\E$/,@authallowed)) {
10036:                 $authhash{$item}{$auth} = 1;
10037:             } else {
10038:                 $authhash{$item}{$auth} = 0;
10039:             }
10040:         }
10041:     }
10042:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
10043:         foreach my $item (@authen_contexts) {
10044:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
10045:                 foreach my $auth (@authtypes) {
10046:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
10047:                         push(@{$changes{'authtypes'}},$item);
10048:                         last;
10049:                     }
10050:                 }
10051:             }
10052:         }
10053:     } else {
10054:         foreach my $item (@authen_contexts) {
10055:             push(@{$changes{'authtypes'}},$item);
10056:         }
10057:     }
10058: 
10059:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
10060:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
10061:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
10062:     $save_usercreate{'id_rule'} = \@id_rule;
10063:     $save_usercreate{'username_rule'} = \@username_rule,
10064:     $save_usercreate{'authtypes'} = \%authhash;
10065: 
10066:     my %usercreation_hash =  (
10067:         usercreation     => \%save_usercreate,
10068:     );
10069: 
10070:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
10071:                                              $dom);
10072: 
10073:     if ($putresult eq 'ok') {
10074:         if (keys(%changes) > 0) {
10075:             $resulttext = &mt('Changes made:').'<ul>';
10076:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
10077:                 my %lt = &usercreation_types();
10078:                 foreach my $type (@{$changes{'cancreate'}}) {
10079:                     my $chgtext = $lt{$type}.', ';
10080:                     if ($cancreate{$type} eq 'none') {
10081:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
10082:                     } elsif ($cancreate{$type} eq 'any') {
10083:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
10084:                     } elsif ($cancreate{$type} eq 'official') {
10085:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
10086:                     } elsif ($cancreate{$type} eq 'unofficial') {
10087:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
10088:                     }
10089:                     $resulttext .= '<li>'.$chgtext.'</li>';
10090:                 }
10091:             }
10092:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
10093:                 my ($rules,$ruleorder) = 
10094:                     &Apache::lonnet::inst_userrules($dom,'username');
10095:                 my $chgtext = '<ul>';
10096:                 foreach my $type (@username_rule) {
10097:                     if (ref($rules->{$type}) eq 'HASH') {
10098:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
10099:                     }
10100:                 }
10101:                 $chgtext .= '</ul>';
10102:                 if (@username_rule > 0) {
10103:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
10104:                 } else {
10105:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
10106:                 }
10107:             }
10108:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
10109:                 my ($idrules,$idruleorder) = 
10110:                     &Apache::lonnet::inst_userrules($dom,'id');
10111:                 my $chgtext = '<ul>';
10112:                 foreach my $type (@id_rule) {
10113:                     if (ref($idrules->{$type}) eq 'HASH') {
10114:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
10115:                     }
10116:                 }
10117:                 $chgtext .= '</ul>';
10118:                 if (@id_rule > 0) {
10119:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
10120:                 } else {
10121:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
10122:                 }
10123:             }
10124:             my %authname = &authtype_names();
10125:             my %context_title = &context_names();
10126:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
10127:                 my $chgtext = '<ul>';
10128:                 foreach my $type (@{$changes{'authtypes'}}) {
10129:                     my @allowed;
10130:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
10131:                     foreach my $auth (@authtypes) {
10132:                         if ($authhash{$type}{$auth}) {
10133:                             push(@allowed,$authname{$auth});
10134:                         }
10135:                     }
10136:                     if (@allowed > 0) {
10137:                         $chgtext .= join(', ',@allowed).'</li>';
10138:                     } else {
10139:                         $chgtext .= &mt('none').'</li>';
10140:                     }
10141:                 }
10142:                 $chgtext .= '</ul>';
10143:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
10144:                 $resulttext .= '</li>';
10145:             }
10146:             $resulttext .= '</ul>';
10147:         } else {
10148:             $resulttext = &mt('No changes made to user creation settings');
10149:         }
10150:     } else {
10151:         $resulttext = '<span class="LC_error">'.
10152:             &mt('An error occurred: [_1]',$putresult).'</span>';
10153:     }
10154:     if ($warningmsg ne '') {
10155:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
10156:     }
10157:     return $resulttext;
10158: }
10159: 
10160: sub modify_selfcreation {
10161:     my ($dom,$lastactref,%domconfig) = @_;
10162:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
10163:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
10164:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
10165:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
10166:     if (ref($typesref) eq 'ARRAY') {
10167:         @types = @{$typesref};
10168:     }
10169:     if (ref($usertypesref) eq 'HASH') {
10170:         %usertypes = %{$usertypesref};
10171:     }
10172:     $usertypes{'default'} = $othertitle;
10173: #
10174: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
10175: #
10176:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
10177:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
10178:             if ($key eq 'cancreate') {
10179:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
10180:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
10181:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
10182:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
10183:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
10184:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
10185:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
10186:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
10187:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
10188:                         } else {
10189:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
10190:                         }
10191:                     }
10192:                 }
10193:             } elsif ($key eq 'email_rule') {
10194:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
10195:             } else {
10196:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
10197:             }
10198:         }
10199:     }
10200: #
10201: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
10202: #
10203:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
10204:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
10205:             if ($key eq 'selfcreate') {
10206:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
10207:             } else {
10208:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
10209:             }
10210:         }
10211:     }
10212: #
10213: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
10214: #
10215:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
10216:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
10217:             if ($key eq 'inststatusguest') {
10218:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
10219:             } else {
10220:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
10221:             }
10222:         }
10223:     }
10224: 
10225:     my @contexts = ('selfcreate');
10226:     @{$cancreate{'selfcreate'}} = ();
10227:     %{$cancreate{'emailusername'}} = ();
10228:     if (@types) {
10229:         @{$cancreate{'statustocreate'}} = ();
10230:     }
10231:     %{$cancreate{'selfcreateprocessing'}} = ();
10232:     %{$cancreate{'shibenv'}} = ();
10233:     %{$cancreate{'emailverified'}} = ();
10234:     %{$cancreate{'emailoptions'}} = ();
10235:     %{$cancreate{'emaildomain'}} = ();
10236:     my %selfcreatetypes = (
10237:                              sso   => 'users authenticated by institutional single sign on',
10238:                              login => 'users authenticated by institutional log-in',
10239:                              email => 'users verified by e-mail',
10240:                           );
10241: #
10242: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
10243: # is permitted.
10244: #
10245: 
10246:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
10247: 
10248:     my (@statuses,%email_rule);
10249:     foreach my $item ('login','sso','email') {
10250:         if ($item eq 'email') {
10251:             if ($env{'form.cancreate_email'}) {
10252:                 if (@types) {
10253:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
10254:                     foreach my $status (@poss_statuses) {
10255:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
10256:                             push(@statuses,$status);
10257:                         }
10258:                     }
10259:                     $save_inststatus{'inststatusguest'} = \@statuses;
10260:                 } else {
10261:                     push(@statuses,'default');
10262:                 }
10263:                 if (@statuses) {
10264:                     my %curr_rule;
10265:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
10266:                         foreach my $type (@statuses) {
10267:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
10268:                         }
10269:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
10270:                         foreach my $type (@statuses) {
10271:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
10272:                         }
10273:                     }
10274:                     push(@{$cancreate{'selfcreate'}},'email');
10275:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
10276:                     my %curremaildom;
10277:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
10278:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
10279:                     }
10280:                     foreach my $type (@statuses) {
10281:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
10282:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
10283:                         }
10284:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
10285:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
10286:                         }
10287:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
10288: #
10289: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
10290: #
10291:                             my $chosen = $1;
10292:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
10293:                                 my $emaildom;
10294:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
10295:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type};
10296:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
10297:                                     if (ref($curremaildom{$type}) eq 'HASH') {
10298:                                         if (exists($curremaildom{$type}{$chosen})) {
10299:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
10300:                                                 push(@{$changes{'cancreate'}},'emaildomain');
10301:                                             }
10302:                                         } elsif ($emaildom ne '') {
10303:                                             push(@{$changes{'cancreate'}},'emaildomain');
10304:                                         }
10305:                                     } elsif ($emaildom ne '') {
10306:                                         push(@{$changes{'cancreate'}},'emaildomain');
10307:                                     }
10308:                                 }
10309:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
10310:                             } elsif ($chosen eq 'custom') {
10311:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
10312:                                 $email_rule{$type} = [];
10313:                                 if (ref($emailrules) eq 'HASH') {
10314:                                     foreach my $rule (@possemail_rules) {
10315:                                         if (exists($emailrules->{$rule})) {
10316:                                             push(@{$email_rule{$type}},$rule);
10317:                                         }
10318:                                     }
10319:                                 }
10320:                                 if (@{$email_rule{$type}}) {
10321:                                     $cancreate{'emailoptions'}{$type} = 'custom';
10322:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
10323:                                         if (@{$curr_rule{$type}} > 0) {
10324:                                             foreach my $rule (@{$curr_rule{$type}}) {
10325:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
10326:                                                     push(@{$changes{'email_rule'}},$type);
10327:                                                 }
10328:                                             }
10329:                                         }
10330:                                         foreach my $type (@{$email_rule{$type}}) {
10331:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
10332:                                                 push(@{$changes{'email_rule'}},$type);
10333:                                             }
10334:                                         }
10335:                                     } else {
10336:                                         push(@{$changes{'email_rule'}},$type);
10337:                                     }
10338:                                 }
10339:                             } else {
10340:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
10341:                             }
10342:                         }
10343:                     }
10344:                     if (@types) {
10345:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
10346:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
10347:                             if (@changed) {
10348:                                 push(@{$changes{'inststatus'}},'inststatusguest');
10349:                             }
10350:                         } else {
10351:                             push(@{$changes{'inststatus'}},'inststatusguest');
10352:                         }
10353:                     }
10354:                 } else {
10355:                     delete($env{'form.cancreate_email'});
10356:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
10357:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
10358:                             push(@{$changes{'inststatus'}},'inststatusguest');
10359:                         }
10360:                     }
10361:                 }
10362:             } else {
10363:                 $save_inststatus{'inststatusguest'} = [];
10364:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
10365:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
10366:                         push(@{$changes{'inststatus'}},'inststatusguest');
10367:                     }
10368:                 }
10369:             }
10370:         } else {
10371:             if ($env{'form.cancreate_'.$item}) {
10372:                 push(@{$cancreate{'selfcreate'}},$item);
10373:             }
10374:         }
10375:     }
10376:     my (%userinfo,%savecaptcha);
10377:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
10378: #
10379: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
10380: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
10381: #
10382: 
10383:     if ($env{'form.cancreate_email'}) {
10384:         push(@contexts,'emailusername');
10385:         if (@statuses) {
10386:             foreach my $type (@statuses) {
10387:                 if (ref($infofields) eq 'ARRAY') {
10388:                     foreach my $field (@{$infofields}) {
10389:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
10390:                             $cancreate{'emailusername'}{$type}{$field} = $1;
10391:                         }
10392:                     }
10393:                 }
10394:             }
10395:         }
10396: #
10397: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
10398: # queued requests for self-creation of account verified by e-mail.
10399: #
10400: 
10401:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
10402:         @approvalnotify = sort(@approvalnotify);
10403:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
10404:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
10405:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
10406:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
10407:                     push(@{$changes{'cancreate'}},'notify');
10408:                 }
10409:             } else {
10410:                 if ($cancreate{'notify'}{'approval'}) {
10411:                     push(@{$changes{'cancreate'}},'notify');
10412:                 }
10413:             }
10414:         } elsif ($cancreate{'notify'}{'approval'}) {
10415:             push(@{$changes{'cancreate'}},'notify');
10416:         }
10417: 
10418:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
10419:     }
10420: #  
10421: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
10422: # institutional log-in.
10423: #
10424:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
10425:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
10426:                ($domdefaults{'auth_def'} eq 'localauth'))) {
10427:             $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.').' '.
10428:                           &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.');
10429:         }
10430:     }
10431:     my @fields = ('lastname','firstname','middlename','generation',
10432:                   'permanentemail','id');
10433:     my @shibfields = (@fields,'inststatus');
10434:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
10435: #
10436: # Where usernames may created for institutional log-in and/or institutional single sign on:
10437: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
10438: # may self-create accounts 
10439: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
10440: # which the user may supply, if institutional data is unavailable.
10441: #
10442:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
10443:         if (@types) {
10444:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
10445:             push(@contexts,'statustocreate');
10446:             foreach my $type (@types) {
10447:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
10448:                 foreach my $field (@fields) {
10449:                     if (grep(/^\Q$field\E$/,@modifiable)) {
10450:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
10451:                     } else {
10452:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
10453:                     }
10454:                 }
10455:             }
10456:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
10457:                 foreach my $type (@types) {
10458:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
10459:                         foreach my $field (@fields) {
10460:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
10461:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
10462:                                 push(@{$changes{'selfcreate'}},$type);
10463:                                 last;
10464:                             }
10465:                         }
10466:                     }
10467:                 }
10468:             } else {
10469:                 foreach my $type (@types) {
10470:                     push(@{$changes{'selfcreate'}},$type);
10471:                 }
10472:             }
10473:         }
10474:         foreach my $field (@shibfields) {
10475:             if ($env{'form.shibenv_'.$field} ne '') {
10476:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
10477:             }
10478:         }
10479:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
10480:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
10481:                 foreach my $field (@shibfields) {
10482:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
10483:                         push(@{$changes{'cancreate'}},'shibenv');
10484:                     }
10485:                 }
10486:             } else {
10487:                 foreach my $field (@shibfields) {
10488:                     if ($env{'form.shibenv_'.$field}) {
10489:                         push(@{$changes{'cancreate'}},'shibenv');
10490:                         last;
10491:                     }
10492:                 }
10493:             }
10494:         }
10495:     }
10496:     foreach my $item (@contexts) {
10497:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
10498:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
10499:                 if (ref($cancreate{$item}) eq 'ARRAY') {
10500:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
10501:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10502:                             push(@{$changes{'cancreate'}},$item);
10503:                         }
10504:                     }
10505:                 }
10506:             }
10507:             if (ref($cancreate{$item}) eq 'ARRAY') {
10508:                 foreach my $type (@{$cancreate{$item}}) {
10509:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
10510:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10511:                             push(@{$changes{'cancreate'}},$item);
10512:                         }
10513:                     }
10514:                 }
10515:             }
10516:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
10517:             if (ref($cancreate{$item}) eq 'HASH') {
10518:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
10519:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
10520:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
10521:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
10522:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10523:                                     push(@{$changes{'cancreate'}},$item);
10524:                                 }
10525:                             }
10526:                         }
10527:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
10528:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
10529:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10530:                                 push(@{$changes{'cancreate'}},$item);
10531:                             }
10532:                         }
10533:                     }
10534:                 }
10535:                 foreach my $type (keys(%{$cancreate{$item}})) {
10536:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
10537:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
10538:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
10539:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
10540:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10541:                                         push(@{$changes{'cancreate'}},$item);
10542:                                     }
10543:                                 }
10544:                             } else {
10545:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10546:                                     push(@{$changes{'cancreate'}},$item);
10547:                                 }
10548:                             }
10549:                         }
10550:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
10551:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
10552:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10553:                                 push(@{$changes{'cancreate'}},$item);
10554:                             }
10555:                         }
10556:                     }
10557:                 }
10558:             }
10559:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
10560:             if (ref($cancreate{$item}) eq 'ARRAY') {
10561:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
10562:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10563:                         push(@{$changes{'cancreate'}},$item);
10564:                     }
10565:                 }
10566:             }
10567:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
10568:             if (ref($cancreate{$item}) eq 'HASH') {
10569:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10570:                     push(@{$changes{'cancreate'}},$item);
10571:                 }
10572:             }
10573:         } elsif ($item eq 'emailusername') {
10574:             if (ref($cancreate{$item}) eq 'HASH') {
10575:                 foreach my $type (keys(%{$cancreate{$item}})) {
10576:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
10577:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
10578:                             if ($cancreate{$item}{$type}{$field}) {
10579:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
10580:                                     push(@{$changes{'cancreate'}},$item);
10581:                                 }
10582:                                 last;
10583:                             }
10584:                         }
10585:                     }
10586:                 }
10587:             }
10588:         }
10589:     }
10590: #
10591: # Populate %save_usercreate hash with updates to self-creation configuration.
10592: #
10593:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
10594:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
10595:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
10596:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
10597:     if (ref($cancreate{'notify'}) eq 'HASH') {
10598:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
10599:     }
10600:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
10601:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
10602:     }
10603:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
10604:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
10605:     }
10606:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
10607:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
10608:     }
10609:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
10610:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
10611:     }
10612:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
10613:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
10614:     }
10615:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
10616:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
10617:     }
10618:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
10619:     $save_usercreate{'email_rule'} = \%email_rule;
10620: 
10621:     my %userconfig_hash = (
10622:             usercreation     => \%save_usercreate,
10623:             usermodification => \%save_usermodify,
10624:             inststatus       => \%save_inststatus,
10625:     );
10626: 
10627:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
10628:                                              $dom);
10629: #
10630: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
10631: #
10632:     if ($putresult eq 'ok') {
10633:         if (keys(%changes) > 0) {
10634:             $resulttext = &mt('Changes made:').'<ul>';
10635:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
10636:                 my %lt = &selfcreation_types();
10637:                 foreach my $type (@{$changes{'cancreate'}}) {
10638:                     my $chgtext = '';
10639:                     if ($type eq 'selfcreate') {
10640:                         if (@{$cancreate{$type}} == 0) {
10641:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
10642:                         } else {
10643:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
10644:                                         '<ul>';
10645:                             foreach my $case (@{$cancreate{$type}}) {
10646:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
10647:                             }
10648:                             $chgtext .= '</ul>';
10649:                             if (ref($cancreate{$type}) eq 'ARRAY') {
10650:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
10651:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
10652:                                         if (@{$cancreate{'statustocreate'}} == 0) {
10653:                                             $chgtext .= '<span class="LC_warning">'.
10654:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
10655:                                                         '</span><br />';
10656:                                         }
10657:                                     }
10658:                                 }
10659:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
10660:                                     if (!@statuses) {
10661:                                         $chgtext .= '<span class="LC_warning">'.
10662:                                                     &mt("However, e-mail verification is currently set to 'unavailable' for all user types (including 'other'), so self-creation of accounts is not possible for non-institutional log-in.").
10663:                                                     '</span><br />';
10664: 
10665:                                     }
10666:                                 }
10667:                             }
10668:                         }
10669:                     } elsif ($type eq 'shibenv') {
10670:                         if (keys(%{$cancreate{$type}}) == 0) {
10671:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
10672:                         } else {
10673:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
10674:                                         '<ul>';
10675:                             foreach my $field (@shibfields) {
10676:                                 next if ($cancreate{$type}{$field} eq '');
10677:                                 if ($field eq 'inststatus') {
10678:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
10679:                                 } else {
10680:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
10681:                                 }
10682:                             }
10683:                             $chgtext .= '</ul>';
10684:                         }
10685:                     } elsif ($type eq 'statustocreate') {
10686:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
10687:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
10688:                             if (@{$cancreate{'selfcreate'}} > 0) {
10689:                                 if (@{$cancreate{'statustocreate'}} == 0) {
10690:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
10691:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
10692:                                         $chgtext .= '<br />'.
10693:                                                     '<span class="LC_warning">'.
10694:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
10695:                                                     '</span>';
10696:                                     }
10697:                                 } elsif (keys(%usertypes) > 0) {
10698:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
10699:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
10700:                                     } else {
10701:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
10702:                                     }
10703:                                     $chgtext .= '<ul>';
10704:                                     foreach my $case (@{$cancreate{$type}}) {
10705:                                         if ($case eq 'default') {
10706:                                             $chgtext .= '<li>'.$othertitle.'</li>';
10707:                                         } else {
10708:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
10709:                                         }
10710:                                     }
10711:                                     $chgtext .= '</ul>';
10712:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
10713:                                         $chgtext .= '<span class="LC_warning">'.
10714:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
10715:                                                     '</span>';
10716:                                     }
10717:                                 }
10718:                             } else {
10719:                                 if (@{$cancreate{$type}} == 0) {
10720:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
10721:                                 } else {
10722:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
10723:                                 }
10724:                             }
10725:                             $chgtext .= '<br />';
10726:                         }
10727:                     } elsif ($type eq 'selfcreateprocessing') {
10728:                         my %choices = &Apache::lonlocal::texthash (
10729:                                                                     automatic => 'Automatic approval',
10730:                                                                     approval  => 'Queued for approval',
10731:                                                                   );
10732:                         if (@types) {
10733:                             if (@statuses) {
10734:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:').
10735:                                             '<ul>';
10736:                                 foreach my $status (@statuses) {
10737:                                     if ($status eq 'default') {
10738:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
10739:                                     } else {
10740:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
10741:                                     }
10742:                                 }
10743:                                 $chgtext .= '</ul>';
10744:                             }
10745:                         } else {
10746:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
10747:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
10748:                         }
10749:                     } elsif ($type eq 'emailverified') {
10750:                         my %options = &Apache::lonlocal::texthash (
10751:                                                                     all   => 'Same as e-mail',
10752:                                                                     first => 'Omit @domain',
10753:                                                                     free  => 'Free to choose',
10754:                                                                   );
10755:                         if (@types) {
10756:                             if (@statuses) {
10757:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
10758:                                             '<ul>';
10759:                                 foreach my $status (@statuses) {
10760:                                     if ($status eq 'default') {
10761:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
10762:                                     } else {
10763:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
10764:                                     }
10765:                                 }
10766:                                 $chgtext .= '</ul>';
10767:                             }
10768:                         } else {
10769:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
10770:                                             $options{$cancreate{'emailverified'}{'default'}});
10771:                         }
10772:                     } elsif ($type eq 'emailoptions') {
10773:                         my %options = &Apache::lonlocal::texthash (
10774:                                                                     any     => 'Any e-mail',
10775:                                                                     inst    => 'Institutional only',
10776:                                                                     noninst => 'Non-institutional only',
10777:                                                                     custom  => 'Custom restrictions',
10778:                                                                   );
10779:                         if (@types) {
10780:                             if (@statuses) {
10781:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
10782:                                             '<ul>';
10783:                                 foreach my $status (@statuses) {
10784:                                     if ($type eq 'default') {
10785:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
10786:                                     } else {
10787:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
10788:                                     }
10789:                                 }
10790:                                 $chgtext .= '</ul>';
10791:                             }
10792:                         } else {
10793:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
10794:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
10795:                             } else {
10796:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
10797:                                                 $options{$cancreate{'emailoptions'}{'default'}});
10798:                             }
10799:                         }
10800:                     } elsif ($type eq 'emaildomain') {
10801:                         my $output;
10802:                         if (@statuses) {
10803:                             foreach my $type (@statuses) {
10804:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
10805:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
10806:                                         if ($type eq 'default') {
10807:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
10808:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
10809:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
10810:                                             } else {
10811:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
10812:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
10813:                                             }
10814:                                         } else {
10815:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
10816:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
10817:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
10818:                                             } else {
10819:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
10820:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
10821:                                             }
10822:                                         }
10823:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
10824:                                         if ($type eq 'default') {
10825:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
10826:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
10827:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
10828:                                             } else {
10829:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
10830:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
10831:                                             }
10832:                                         } else {
10833:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
10834:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
10835:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
10836:                                             } else {
10837:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
10838:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
10839:                                             }
10840:                                         }
10841:                                     }
10842:                                 }
10843:                             }
10844:                         }
10845:                         if ($output ne '') {
10846:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
10847:                                         '<ul>'.$output.'</ul>';
10848:                         }
10849:                     } elsif ($type eq 'captcha') {
10850:                         if ($savecaptcha{$type} eq 'notused') {
10851:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
10852:                         } else {
10853:                             my %captchas = &captcha_phrases();
10854:                             if ($captchas{$savecaptcha{$type}}) {
10855:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
10856:                             } else {
10857:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
10858:                             }
10859:                         }
10860:                     } elsif ($type eq 'recaptchakeys') {
10861:                         my ($privkey,$pubkey);
10862:                         if (ref($savecaptcha{$type}) eq 'HASH') {
10863:                             $pubkey = $savecaptcha{$type}{'public'};
10864:                             $privkey = $savecaptcha{$type}{'private'};
10865:                         }
10866:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
10867:                         if (!$pubkey) {
10868:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
10869:                         } else {
10870:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
10871:                         }
10872:                         if (!$privkey) {
10873:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
10874:                         } else {
10875:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
10876:                         }
10877:                         $chgtext .= '</ul>';
10878:                     } elsif ($type eq 'recaptchaversion') {
10879:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
10880:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
10881:                         }
10882:                     } elsif ($type eq 'emailusername') {
10883:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
10884:                             if (@statuses) {
10885:                                 foreach my $type (@statuses) {
10886:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
10887:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
10888:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
10889:                                                     '<ul>';
10890:                                             foreach my $field (@{$infofields}) {
10891:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
10892:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
10893:                                                 }
10894:                                             }
10895:                                             $chgtext .= '</ul>';
10896:                                         } else {
10897:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
10898:                                         }
10899:                                     } else {
10900:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
10901:                                     }
10902:                                 }
10903:                             }
10904:                         }
10905:                     } elsif ($type eq 'notify') {
10906:                         my $numapprove = 0;
10907:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
10908:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
10909:                                 if ($cancreate{'notify'}{'approval'}) {
10910:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
10911:                                     $numapprove ++;
10912:                                 }
10913:                             }
10914:                         }
10915:                         unless ($numapprove) {
10916:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
10917:                         }
10918:                     }
10919:                     if ($chgtext) {
10920:                         $resulttext .= '<li>'.$chgtext.'</li>';
10921:                     }
10922:                 }
10923:             }
10924:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
10925:                 my ($emailrules,$emailruleorder) =
10926:                     &Apache::lonnet::inst_userrules($dom,'email');
10927:                 foreach my $type (@{$changes{'email_rule'}}) {
10928:                     if (ref($email_rule{$type}) eq 'ARRAY') {
10929:                         my $chgtext = '<ul>';
10930:                         foreach my $rule (@{$email_rule{$type}}) {
10931:                             if (ref($emailrules->{$rule}) eq 'HASH') {
10932:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
10933:                             }
10934:                         }
10935:                         $chgtext .= '</ul>';
10936:                         my $typename;
10937:                         if (@types) {
10938:                             if ($type eq 'default') {
10939:                                 $typename = $othertitle;
10940:                             } else {
10941:                                 $typename = $usertypes{$type};
10942:                             }
10943:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
10944:                         }
10945:                         if (@{$email_rule{$type}} > 0) {
10946:                             $resulttext .= '<li>'.
10947:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
10948:                                                $usertypes{$type}).
10949:                                            $chgtext.
10950:                                            '</li>';
10951:                         } else {
10952:                             $resulttext .= '<li>'.
10953:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
10954:                                            '</li>'.
10955:                                            &mt('(Affiliation: [_1])',$typename);
10956:                         }
10957:                     }
10958:                 }
10959:             }
10960:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
10961:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
10962:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
10963:                         my $chgtext = '<ul>';
10964:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
10965:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
10966:                         }
10967:                         $chgtext .= '</ul>';
10968:                         $resulttext .= '<li>'.
10969:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
10970:                                           $chgtext.
10971:                                        '</li>';
10972:                     } else {
10973:                         $resulttext .= '<li>'.
10974:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
10975:                                        '</li>';
10976:                     }
10977:                 }
10978:             }
10979:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
10980:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
10981:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
10982:                 foreach my $type (@{$changes{'selfcreate'}}) {
10983:                     my $typename = $type;
10984:                     if (keys(%usertypes) > 0) {
10985:                         if ($usertypes{$type} ne '') {
10986:                             $typename = $usertypes{$type};
10987:                         }
10988:                     }
10989:                     my @modifiable;
10990:                     $resulttext .= '<li>'.
10991:                                     &mt('Self-creation of account by users with status: [_1]',
10992:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
10993:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
10994:                     foreach my $field (@fields) {
10995:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
10996:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
10997:                         }
10998:                     }
10999:                     if (@modifiable > 0) {
11000:                         $resulttext .= join(', ',@modifiable);
11001:                     } else {
11002:                         $resulttext .= &mt('none');
11003:                     }
11004:                     $resulttext .= '</li>';
11005:                 }
11006:                 $resulttext .= '</ul></li>';
11007:             }
11008:             $resulttext .= '</ul>';
11009:             my $cachetime = 24*60*60;
11010:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
11011:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
11012:             if (ref($lastactref) eq 'HASH') {
11013:                 $lastactref->{'domdefaults'} = 1;
11014:             }
11015:         } else {
11016:             $resulttext = &mt('No changes made to self-creation settings');
11017:         }
11018:     } else {
11019:         $resulttext = '<span class="LC_error">'.
11020:             &mt('An error occurred: [_1]',$putresult).'</span>';
11021:     }
11022:     if ($warningmsg ne '') {
11023:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
11024:     }
11025:     return $resulttext;
11026: }
11027: 
11028: sub process_captcha {
11029:     my ($container,$changes,$newsettings,$current) = @_;
11030:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH') || (ref($current) eq 'HASH'));
11031:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
11032:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
11033:         $newsettings->{'captcha'} = 'original';
11034:     }
11035:     if ($current->{'captcha'} ne $newsettings->{'captcha'}) {
11036:         if ($container eq 'cancreate') {
11037:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
11038:                 push(@{$changes->{'cancreate'}},'captcha');
11039:             } elsif (!defined($changes->{'cancreate'})) {
11040:                 $changes->{'cancreate'} = ['captcha'];
11041:             }
11042:         } else {
11043:             $changes->{'captcha'} = 1;
11044:         }
11045:     }
11046:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
11047:     if ($newsettings->{'captcha'} eq 'recaptcha') {
11048:         $newpub = $env{'form.'.$container.'_recaptchapub'};
11049:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
11050:         $newpub =~ s/[^\w\-]//g;
11051:         $newpriv =~ s/[^\w\-]//g;
11052:         $newsettings->{'recaptchakeys'} = {
11053:                                              public  => $newpub,
11054:                                              private => $newpriv,
11055:                                           };
11056:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
11057:         $newversion =~ s/\D//g;
11058:         if ($newversion ne '2') {
11059:             $newversion = 1;
11060:         }
11061:         $newsettings->{'recaptchaversion'} = $newversion;
11062:     }
11063:     if (ref($current->{'recaptchakeys'}) eq 'HASH') {
11064:         $currpub = $current->{'recaptchakeys'}{'public'};
11065:         $currpriv = $current->{'recaptchakeys'}{'private'};
11066:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
11067:             $newsettings->{'recaptchakeys'} = {
11068:                                                  public  => '',
11069:                                                  private => '',
11070:                                               }
11071:         }
11072:     }
11073:     if ($current->{'captcha'} eq 'recaptcha') {
11074:         $currversion = $current->{'recaptchaversion'};
11075:         if ($currversion ne '2') {
11076:             $currversion = 1;
11077:         }
11078:     }
11079:     if ($currversion ne $newversion) {
11080:         if ($container eq 'cancreate') {
11081:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
11082:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
11083:             } elsif (!defined($changes->{'cancreate'})) {
11084:                 $changes->{'cancreate'} = ['recaptchaversion'];
11085:             }
11086:         } else {
11087:             $changes->{'recaptchaversion'} = 1;
11088:         }
11089:     }
11090:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
11091:         if ($container eq 'cancreate') {
11092:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
11093:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
11094:             } elsif (!defined($changes->{'cancreate'})) {
11095:                 $changes->{'cancreate'} = ['recaptchakeys'];
11096:             }
11097:         } else {
11098:             $changes->{'recaptchakeys'} = 1;
11099:         }
11100:     }
11101:     return;
11102: }
11103: 
11104: sub modify_usermodification {
11105:     my ($dom,%domconfig) = @_;
11106:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
11107:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
11108:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
11109:             if ($key eq 'selfcreate') {
11110:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
11111:             } else {  
11112:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
11113:             }
11114:         }
11115:     }
11116:     my @contexts = ('author','course');
11117:     my %context_title = (
11118:                            author => 'In author context',
11119:                            course => 'In course context',
11120:                         );
11121:     my @fields = ('lastname','firstname','middlename','generation',
11122:                   'permanentemail','id');
11123:     my %roles = (
11124:                   author => ['ca','aa'],
11125:                   course => ['st','ep','ta','in','cr'],
11126:                 );
11127:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
11128:     foreach my $context (@contexts) {
11129:         foreach my $role (@{$roles{$context}}) {
11130:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
11131:             foreach my $item (@fields) {
11132:                 if (grep(/^\Q$item\E$/,@modifiable)) {
11133:                     $modifyhash{$context}{$role}{$item} = 1;
11134:                 } else {
11135:                     $modifyhash{$context}{$role}{$item} = 0;
11136:                 }
11137:             }
11138:         }
11139:         if (ref($curr_usermodification{$context}) eq 'HASH') {
11140:             foreach my $role (@{$roles{$context}}) {
11141:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
11142:                     foreach my $field (@fields) {
11143:                         if ($modifyhash{$context}{$role}{$field} ne 
11144:                                 $curr_usermodification{$context}{$role}{$field}) {
11145:                             push(@{$changes{$context}},$role);
11146:                             last;
11147:                         }
11148:                     }
11149:                 }
11150:             }
11151:         } else {
11152:             foreach my $context (@contexts) {
11153:                 foreach my $role (@{$roles{$context}}) {
11154:                     push(@{$changes{$context}},$role);
11155:                 }
11156:             }
11157:         }
11158:     }
11159:     my %usermodification_hash =  (
11160:                                    usermodification => \%modifyhash,
11161:                                  );
11162:     my $putresult = &Apache::lonnet::put_dom('configuration',
11163:                                              \%usermodification_hash,$dom);
11164:     if ($putresult eq 'ok') {
11165:         if (keys(%changes) > 0) {
11166:             $resulttext = &mt('Changes made: ').'<ul>';
11167:             foreach my $context (@contexts) {
11168:                 if (ref($changes{$context}) eq 'ARRAY') {
11169:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
11170:                     if (ref($changes{$context}) eq 'ARRAY') {
11171:                         foreach my $role (@{$changes{$context}}) {
11172:                             my $rolename;
11173:                             if ($role eq 'cr') {
11174:                                 $rolename = &mt('Custom');
11175:                             } else {
11176:                                 $rolename = &Apache::lonnet::plaintext($role);
11177:                             }
11178:                             my @modifiable;
11179:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
11180:                             foreach my $field (@fields) {
11181:                                 if ($modifyhash{$context}{$role}{$field}) {
11182:                                     push(@modifiable,$fieldtitles{$field});
11183:                                 }
11184:                             }
11185:                             if (@modifiable > 0) {
11186:                                 $resulttext .= join(', ',@modifiable);
11187:                             } else {
11188:                                 $resulttext .= &mt('none'); 
11189:                             }
11190:                             $resulttext .= '</li>';
11191:                         }
11192:                         $resulttext .= '</ul></li>';
11193:                     }
11194:                 }
11195:             }
11196:             $resulttext .= '</ul>';
11197:         } else {
11198:             $resulttext = &mt('No changes made to user modification settings');
11199:         }
11200:     } else {
11201:         $resulttext = '<span class="LC_error">'.
11202:             &mt('An error occurred: [_1]',$putresult).'</span>';
11203:     }
11204:     return $resulttext;
11205: }
11206: 
11207: sub modify_defaults {
11208:     my ($dom,$lastactref,%domconfig) = @_;
11209:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
11210:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
11211:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
11212:                  'portal_def','intauth_cost','intauth_check','intauth_switch');
11213:     my @authtypes = ('internal','krb4','krb5','localauth');
11214:     foreach my $item (@items) {
11215:         $newvalues{$item} = $env{'form.'.$item};
11216:         if ($item eq 'auth_def') {
11217:             if ($newvalues{$item} ne '') {
11218:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
11219:                     push(@errors,$item);
11220:                 }
11221:             }
11222:         } elsif ($item eq 'lang_def') {
11223:             if ($newvalues{$item} ne '') {
11224:                 if ($newvalues{$item} =~ /^(\w+)/) {
11225:                     my $langcode = $1;
11226:                     if ($langcode ne 'x_chef') {
11227:                         if (code2language($langcode) eq '') {
11228:                             push(@errors,$item);
11229:                         }
11230:                     }
11231:                 } else {
11232:                     push(@errors,$item);
11233:                 }
11234:             }
11235:         } elsif ($item eq 'timezone_def') {
11236:             if ($newvalues{$item} ne '') {
11237:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
11238:                     push(@errors,$item);   
11239:                 }
11240:             }
11241:         } elsif ($item eq 'datelocale_def') {
11242:             if ($newvalues{$item} ne '') {
11243:                 my @datelocale_ids = DateTime::Locale->ids();
11244:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
11245:                     push(@errors,$item);
11246:                 }
11247:             }
11248:         } elsif ($item eq 'portal_def') {
11249:             if ($newvalues{$item} ne '') {
11250:                 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])\/?$/) {
11251:                     push(@errors,$item);
11252:                 }
11253:             }
11254:         } elsif ($item eq 'intauth_cost') {
11255:             if ($newvalues{$item} ne '') {
11256:                 if ($newvalues{$item} =~ /\D/) {
11257:                     push(@errors,$item);
11258:                 }
11259:             }
11260:         } elsif ($item eq 'intauth_check') {
11261:             if ($newvalues{$item} ne '') {
11262:                 unless ($newvalues{$item} =~ /^(0|1|2)$/) {
11263:                     push(@errors,$item);
11264:                 }
11265:             }
11266:         } elsif ($item eq 'intauth_switch') {
11267:             if ($newvalues{$item} ne '') {
11268:                 unless ($newvalues{$item} =~ /^(0|1|2)$/) {
11269:                     push(@errors,$item);
11270:                 }
11271:             }
11272:         }
11273:         if (grep(/^\Q$item\E$/,@errors)) {
11274:             $newvalues{$item} = $domdefaults{$item};
11275:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
11276:             $changes{$item} = 1;
11277:         }
11278:         $domdefaults{$item} = $newvalues{$item};
11279:     }
11280:     my %defaults_hash = (
11281:                          defaults => \%newvalues,
11282:                         );
11283:     my $title = &defaults_titles();
11284: 
11285:     my $currinststatus;
11286:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
11287:         $currinststatus = $domconfig{'inststatus'};
11288:     } else {
11289:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
11290:         $currinststatus = {
11291:                              inststatustypes => $usertypes,
11292:                              inststatusorder => $types,
11293:                              inststatusguest => [],
11294:                           };
11295:     }
11296:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
11297:     my @allpos;
11298:     my %alltypes;
11299:     my @inststatusguest;
11300:     if (ref($currinststatus) eq 'HASH') {
11301:         if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
11302:             foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
11303:                 unless (grep(/^\Q$type\E$/,@todelete)) {
11304:                     push(@inststatusguest,$type);
11305:                 }
11306:             }
11307:         }
11308:     }
11309:     my ($currtitles,$currorder);
11310:     if (ref($currinststatus) eq 'HASH') {
11311:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
11312:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
11313:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
11314:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
11315:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
11316:                     }
11317:                 }
11318:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
11319:                     my $position = $env{'form.inststatus_pos_'.$type};
11320:                     $position =~ s/\D+//g;
11321:                     $allpos[$position] = $type;
11322:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
11323:                     $alltypes{$type} =~ s/`//g;
11324:                 }
11325:             }
11326:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
11327:             $currtitles =~ s/,$//;
11328:         }
11329:     }
11330:     if ($env{'form.addinststatus'}) {
11331:         my $newtype = $env{'form.addinststatus'};
11332:         $newtype =~ s/\W//g;
11333:         unless (exists($alltypes{$newtype})) {
11334:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
11335:             $alltypes{$newtype} =~ s/`//g; 
11336:             my $position = $env{'form.addinststatus_pos'};
11337:             $position =~ s/\D+//g;
11338:             if ($position ne '') {
11339:                 $allpos[$position] = $newtype;
11340:             }
11341:         }
11342:     }
11343:     my @orderedstatus;
11344:     foreach my $type (@allpos) {
11345:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
11346:             push(@orderedstatus,$type);
11347:         }
11348:     }
11349:     foreach my $type (keys(%alltypes)) {
11350:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
11351:             delete($alltypes{$type});
11352:         }
11353:     }
11354:     $defaults_hash{'inststatus'} = {
11355:                                      inststatustypes => \%alltypes,
11356:                                      inststatusorder => \@orderedstatus,
11357:                                      inststatusguest => \@inststatusguest,
11358:                                    };
11359:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
11360:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
11361:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
11362:         }
11363:     }
11364:     if ($currorder ne join(',',@orderedstatus)) {
11365:         $changes{'inststatus'}{'inststatusorder'} = 1;
11366:     }
11367:     my $newtitles;
11368:     foreach my $item (@orderedstatus) {
11369:         $newtitles .= $alltypes{$item}.',';
11370:     }
11371:     $newtitles =~ s/,$//;
11372:     if ($currtitles ne $newtitles) {
11373:         $changes{'inststatus'}{'inststatustypes'} = 1;
11374:     }
11375:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
11376:                                              $dom);
11377:     if ($putresult eq 'ok') {
11378:         if (keys(%changes) > 0) {
11379:             $resulttext = &mt('Changes made:').'<ul>';
11380:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
11381:             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";
11382:             foreach my $item (sort(keys(%changes))) {
11383:                 if ($item eq 'inststatus') {
11384:                     if (ref($changes{'inststatus'}) eq 'HASH') {
11385:                         if (@orderedstatus) {
11386:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
11387:                             foreach my $type (@orderedstatus) { 
11388:                                 $resulttext .= $alltypes{$type}.', ';
11389:                             }
11390:                             $resulttext =~ s/, $//;
11391:                             $resulttext .= '</li>';
11392:                         } else {
11393:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>';
11394:                         }
11395:                     }
11396:                 } else {
11397:                     my $value = $env{'form.'.$item};
11398:                     if ($value eq '') {
11399:                         $value = &mt('none');
11400:                     } elsif ($item eq 'auth_def') {
11401:                         my %authnames = &authtype_names();
11402:                         my %shortauth = (
11403:                                           internal   => 'int',
11404:                                           krb4       => 'krb4',
11405:                                           krb5       => 'krb5',
11406:                                           localauth  => 'loc',
11407:                         );
11408:                         $value = $authnames{$shortauth{$value}};
11409:                     } elsif ($item eq 'intauth_switch') {
11410:                         my %optiondesc = &Apache::lonlocal::texthash (
11411:                                             0 => 'No',
11412:                                             1 => 'Yes',
11413:                                             2 => 'Yes, and copy existing passwd file to passwd.bak file',
11414:                                          );
11415:                         if ($value =~ /^(0|1|2)$/) {
11416:                             $value = $optiondesc{$value};
11417:                         } else {
11418:                             $value = &mt('none -- defaults to No');
11419:                         }
11420:                     } elsif ($item eq 'intauth_check') {
11421:                         my %optiondesc = &Apache::lonlocal::texthash (
11422:                                              0 => 'No',
11423:                                              1 => 'Yes, allow login then update passwd file using default cost (if higher)',
11424:                                              2 => 'Yes, disallow login if stored cost is less than domain default',
11425:                                          );
11426:                         if ($value =~ /^(0|1|2)$/) {
11427:                             $value = $optiondesc{$value};
11428:                         } else {
11429:                             $value = &mt('none -- defaults to No');
11430:                         }
11431:                     }
11432:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
11433:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
11434:                 }
11435:             }
11436:             $resulttext .= '</ul>';
11437:             $mailmsgtext .= "\n";
11438:             my $cachetime = 24*60*60;
11439:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
11440:             if (ref($lastactref) eq 'HASH') {
11441:                 $lastactref->{'domdefaults'} = 1;
11442:             }
11443:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
11444:                 my $notify = 1;
11445:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
11446:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
11447:                         $notify = 0;
11448:                     }
11449:                 }
11450:                 if ($notify) {
11451:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
11452:                                                "LON-CAPA Domain Settings Change - $dom",
11453:                                                $mailmsgtext);
11454:                 }
11455:             }
11456:         } else {
11457:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
11458:         }
11459:     } else {
11460:         $resulttext = '<span class="LC_error">'.
11461:             &mt('An error occurred: [_1]',$putresult).'</span>';
11462:     }
11463:     if (@errors > 0) {
11464:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
11465:         foreach my $item (@errors) {
11466:             $resulttext .= ' "'.$title->{$item}.'",';
11467:         }
11468:         $resulttext =~ s/,$//;
11469:     }
11470:     return $resulttext;
11471: }
11472: 
11473: sub modify_scantron {
11474:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
11475:     my ($resulttext,%confhash,%changes,$errors);
11476:     my $custom = 'custom.tab';
11477:     my $default = 'default.tab';
11478:     my $servadm = $r->dir_config('lonAdmEMail');
11479:     my ($configuserok,$author_ok,$switchserver) = 
11480:         &config_check($dom,$confname,$servadm);
11481:     if ($env{'form.scantronformat.filename'} ne '') {
11482:         my $error;
11483:         if ($configuserok eq 'ok') {
11484:             if ($switchserver) {
11485:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
11486:             } else {
11487:                 if ($author_ok eq 'ok') {
11488:                     my ($result,$scantronurl) =
11489:                         &publishlogo($r,'upload','scantronformat',$dom,
11490:                                      $confname,'scantron','','',$custom);
11491:                     if ($result eq 'ok') {
11492:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
11493:                         $changes{'scantronformat'} = 1;
11494:                     } else {
11495:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
11496:                     }
11497:                 } else {
11498:                     $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);
11499:                 }
11500:             }
11501:         } else {
11502:             $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);
11503:         }
11504:         if ($error) {
11505:             &Apache::lonnet::logthis($error);
11506:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11507:         }
11508:     }
11509:     if (ref($domconfig{'scantron'}) eq 'HASH') {
11510:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
11511:             if ($env{'form.scantronformat_del'}) {
11512:                 $confhash{'scantron'}{'scantronformat'} = '';
11513:                 $changes{'scantronformat'} = 1;
11514:             }
11515:         }
11516:     }
11517:     if (keys(%confhash) > 0) {
11518:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
11519:                                                  $dom);
11520:         if ($putresult eq 'ok') {
11521:             if (keys(%changes) > 0) {
11522:                 if (ref($confhash{'scantron'}) eq 'HASH') {
11523:                     $resulttext = &mt('Changes made:').'<ul>';
11524:                     if ($confhash{'scantron'}{'scantronformat'} eq '') {
11525:                         $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
11526:                     } else {
11527:                         $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
11528:                     }
11529:                     $resulttext .= '</ul>';
11530:                 } else {
11531:                     $resulttext = &mt('Changes made to bubblesheet format file.');
11532:                 }
11533:                 $resulttext .= '</ul>';
11534:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
11535:                 if (ref($lastactref) eq 'HASH') {
11536:                     $lastactref->{'domainconfig'} = 1;
11537:                 }
11538:             } else {
11539:                 $resulttext = &mt('No changes made to bubblesheet format file');
11540:             }
11541:         } else {
11542:             $resulttext = '<span class="LC_error">'.
11543:                 &mt('An error occurred: [_1]',$putresult).'</span>';
11544:         }
11545:     } else {
11546:         $resulttext = &mt('No changes made to bubblesheet format file'); 
11547:     }
11548:     if ($errors) {
11549:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
11550:                        $errors.'</ul>';
11551:     }
11552:     return $resulttext;
11553: }
11554: 
11555: sub modify_coursecategories {
11556:     my ($dom,$lastactref,%domconfig) = @_;
11557:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
11558:         $cathash);
11559:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
11560:     my @catitems = ('unauth','auth');
11561:     my @cattypes = ('std','domonly','codesrch','none');
11562:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
11563:         $cathash = $domconfig{'coursecategories'}{'cats'};
11564:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
11565:             $changes{'togglecats'} = 1;
11566:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
11567:         }
11568:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
11569:             $changes{'categorize'} = 1;
11570:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
11571:         }
11572:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
11573:             $changes{'togglecatscomm'} = 1;
11574:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
11575:         }
11576:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
11577:             $changes{'categorizecomm'} = 1;
11578:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
11579:         }
11580:         foreach my $item (@catitems) {
11581:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
11582:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
11583:                     $changes{$item} = 1;
11584:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
11585:                 }
11586:             }
11587:         }
11588:     } else {
11589:         $changes{'togglecats'} = 1;
11590:         $changes{'categorize'} = 1;
11591:         $changes{'togglecatscomm'} = 1;
11592:         $changes{'categorizecomm'} = 1;
11593:         $domconfig{'coursecategories'} = {
11594:                                              togglecats => $env{'form.togglecats'},
11595:                                              categorize => $env{'form.categorize'},
11596:                                              togglecatscomm => $env{'form.togglecatscomm'},
11597:                                              categorizecomm => $env{'form.categorizecomm'},
11598:                                          };
11599:         foreach my $item (@catitems) {
11600:             if ($env{'form.coursecat_'.$item} ne 'std') {
11601:                 $changes{$item} = 1;
11602:             }
11603:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
11604:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
11605:             }
11606:         }
11607:     }
11608:     if (ref($cathash) eq 'HASH') {
11609:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
11610:             push (@deletecategory,'instcode::0');
11611:         }
11612:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
11613:             push(@deletecategory,'communities::0');
11614:         }
11615:     }
11616:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
11617:     if (ref($cathash) eq 'HASH') {
11618:         if (@deletecategory > 0) {
11619:             #FIXME Need to remove category from all courses using a deleted category 
11620:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
11621:             foreach my $item (@deletecategory) {
11622:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
11623:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
11624:                     $deletions{$item} = 1;
11625:                     &recurse_cat_deletes($item,$cathash,\%deletions);
11626:                 }
11627:             }
11628:         }
11629:         foreach my $item (keys(%{$cathash})) {
11630:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
11631:             if ($cathash->{$item} ne $env{'form.'.$item}) {
11632:                 $reorderings{$item} = 1;
11633:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
11634:             }
11635:             if ($env{'form.addcategory_name_'.$item} ne '') {
11636:                 my $newcat = $env{'form.addcategory_name_'.$item};
11637:                 my $newdepth = $depth+1;
11638:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
11639:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
11640:                 $adds{$newitem} = 1; 
11641:             }
11642:             if ($env{'form.subcat_'.$item} ne '') {
11643:                 my $newcat = $env{'form.subcat_'.$item};
11644:                 my $newdepth = $depth+1;
11645:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
11646:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
11647:                 $adds{$newitem} = 1;
11648:             }
11649:         }
11650:     }
11651:     if ($env{'form.instcode'} eq '1') {
11652:         if (ref($cathash) eq 'HASH') {
11653:             my $newitem = 'instcode::0';
11654:             if ($cathash->{$newitem} eq '') {  
11655:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
11656:                 $adds{$newitem} = 1;
11657:             }
11658:         } else {
11659:             my $newitem = 'instcode::0';
11660:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
11661:             $adds{$newitem} = 1;
11662:         }
11663:     }
11664:     if ($env{'form.communities'} eq '1') {
11665:         if (ref($cathash) eq 'HASH') {
11666:             my $newitem = 'communities::0';
11667:             if ($cathash->{$newitem} eq '') {
11668:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
11669:                 $adds{$newitem} = 1;
11670:             }
11671:         } else {
11672:             my $newitem = 'communities::0';
11673:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
11674:             $adds{$newitem} = 1;
11675:         }
11676:     }
11677:     if ($env{'form.addcategory_name'} ne '') {
11678:         if (($env{'form.addcategory_name'} ne 'instcode') &&
11679:             ($env{'form.addcategory_name'} ne 'communities')) {
11680:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
11681:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
11682:             $adds{$newitem} = 1;
11683:         }
11684:     }
11685:     my $putresult;
11686:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
11687:         if (keys(%deletions) > 0) {
11688:             foreach my $key (keys(%deletions)) {
11689:                 if ($predelallitems{$key} ne '') {
11690:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
11691:                 }
11692:             }
11693:         }
11694:         my (@chkcats,@chktrails,%chkallitems);
11695:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
11696:         if (ref($chkcats[0]) eq 'ARRAY') {
11697:             my $depth = 0;
11698:             my $chg = 0;
11699:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
11700:                 my $name = $chkcats[0][$i];
11701:                 my $item;
11702:                 if ($name eq '') {
11703:                     $chg ++;
11704:                 } else {
11705:                     $item = &escape($name).'::0';
11706:                     if ($chg) {
11707:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
11708:                     }
11709:                     $depth ++; 
11710:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
11711:                     $depth --;
11712:                 }
11713:             }
11714:         }
11715:     }
11716:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
11717:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
11718:         if ($putresult eq 'ok') {
11719:             my %title = (
11720:                          togglecats     => 'Show/Hide a course in catalog',
11721:                          categorize     => 'Assign a category to a course',
11722:                          togglecatscomm => 'Show/Hide a community in catalog',
11723:                          categorizecomm => 'Assign a category to a community',
11724:                         );
11725:             my %level = (
11726:                          dom  => 'set in Domain ("Modify Course/Community")',
11727:                          crs  => 'set in Course ("Course Configuration")',
11728:                          comm => 'set in Community ("Community Configuration")',
11729:                          none     => 'No catalog',
11730:                          std      => 'Standard catalog',
11731:                          domonly  => 'Domain-only catalog',
11732:                          codesrch => 'Code search form',
11733:                         );
11734:             $resulttext = &mt('Changes made:').'<ul>';
11735:             if ($changes{'togglecats'}) {
11736:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
11737:             }
11738:             if ($changes{'categorize'}) {
11739:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
11740:             }
11741:             if ($changes{'togglecatscomm'}) {
11742:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
11743:             }
11744:             if ($changes{'categorizecomm'}) {
11745:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
11746:             }
11747:             if ($changes{'unauth'}) {
11748:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
11749:             }
11750:             if ($changes{'auth'}) {
11751:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
11752:             }
11753:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
11754:                 my $cathash;
11755:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
11756:                     $cathash = $domconfig{'coursecategories'}{'cats'};
11757:                 } else {
11758:                     $cathash = {};
11759:                 } 
11760:                 my (@cats,@trails,%allitems);
11761:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
11762:                 if (keys(%deletions) > 0) {
11763:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
11764:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
11765:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
11766:                     }
11767:                     $resulttext .= '</ul></li>';
11768:                 }
11769:                 if (keys(%reorderings) > 0) {
11770:                     my %sort_by_trail;
11771:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
11772:                     foreach my $key (keys(%reorderings)) {
11773:                         if ($allitems{$key} ne '') {
11774:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
11775:                         }
11776:                     }
11777:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
11778:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
11779:                     }
11780:                     $resulttext .= '</ul></li>';
11781:                 }
11782:                 if (keys(%adds) > 0) {
11783:                     my %sort_by_trail;
11784:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
11785:                     foreach my $key (keys(%adds)) {
11786:                         if ($allitems{$key} ne '') {
11787:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
11788:                         }
11789:                     }
11790:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
11791:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
11792:                     }
11793:                     $resulttext .= '</ul></li>';
11794:                 }
11795:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
11796:                 if (ref($lastactref) eq 'HASH') {
11797:                     $lastactref->{'cats'} = 1;
11798:                 }
11799:             }
11800:             $resulttext .= '</ul>';
11801:             if ($changes{'unauth'} || $changes{'auth'}) {
11802:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11803:                 if ($changes{'auth'}) {
11804:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
11805:                 }
11806:                 if ($changes{'unauth'}) {
11807:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
11808:                 }
11809:                 my $cachetime = 24*60*60;
11810:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
11811:                 if (ref($lastactref) eq 'HASH') {
11812:                     $lastactref->{'domdefaults'} = 1;
11813:                 }
11814:             }
11815:         } else {
11816:             $resulttext = '<span class="LC_error">'.
11817:                           &mt('An error occurred: [_1]',$putresult).'</span>';
11818:         }
11819:     } else {
11820:         $resulttext = &mt('No changes made to course and community categories');
11821:     }
11822:     return $resulttext;
11823: }
11824: 
11825: sub modify_serverstatuses {
11826:     my ($dom,%domconfig) = @_;
11827:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
11828:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
11829:         %currserverstatus = %{$domconfig{'serverstatuses'}};
11830:     }
11831:     my @pages = &serverstatus_pages();
11832:     foreach my $type (@pages) {
11833:         $newserverstatus{$type}{'namedusers'} = '';
11834:         $newserverstatus{$type}{'machines'} = '';
11835:         if (defined($env{'form.'.$type.'_namedusers'})) {
11836:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
11837:             my @okusers;
11838:             foreach my $user (@users) {
11839:                 my ($uname,$udom) = split(/:/,$user);
11840:                 if (($udom =~ /^$match_domain$/) &&   
11841:                     (&Apache::lonnet::domain($udom)) &&
11842:                     ($uname =~ /^$match_username$/)) {
11843:                     if (!grep(/^\Q$user\E/,@okusers)) {
11844:                         push(@okusers,$user);
11845:                     }
11846:                 }
11847:             }
11848:             if (@okusers > 0) {
11849:                  @okusers = sort(@okusers);
11850:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
11851:             }
11852:         }
11853:         if (defined($env{'form.'.$type.'_machines'})) {
11854:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
11855:             my @okmachines;
11856:             foreach my $ip (@machines) {
11857:                 my @parts = split(/\./,$ip);
11858:                 next if (@parts < 4);
11859:                 my $badip = 0;
11860:                 for (my $i=0; $i<4; $i++) {
11861:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
11862:                         $badip = 1;
11863:                         last;
11864:                     }
11865:                 }
11866:                 if (!$badip) {
11867:                     push(@okmachines,$ip);     
11868:                 }
11869:             }
11870:             @okmachines = sort(@okmachines);
11871:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
11872:         }
11873:     }
11874:     my %serverstatushash =  (
11875:                                 serverstatuses => \%newserverstatus,
11876:                             );
11877:     foreach my $type (@pages) {
11878:         foreach my $setting ('namedusers','machines') {
11879:             my (@current,@new);
11880:             if (ref($currserverstatus{$type}) eq 'HASH') {
11881:                 if ($currserverstatus{$type}{$setting} ne '') { 
11882:                     @current = split(/,/,$currserverstatus{$type}{$setting});
11883:                 }
11884:             }
11885:             if ($newserverstatus{$type}{$setting} ne '') {
11886:                 @new = split(/,/,$newserverstatus{$type}{$setting});
11887:             }
11888:             if (@current > 0) {
11889:                 if (@new > 0) {
11890:                     foreach my $item (@current) {
11891:                         if (!grep(/^\Q$item\E$/,@new)) {
11892:                             $changes{$type}{$setting} = 1;
11893:                             last;
11894:                         }
11895:                     }
11896:                     foreach my $item (@new) {
11897:                         if (!grep(/^\Q$item\E$/,@current)) {
11898:                             $changes{$type}{$setting} = 1;
11899:                             last;
11900:                         }
11901:                     }
11902:                 } else {
11903:                     $changes{$type}{$setting} = 1;
11904:                 }
11905:             } elsif (@new > 0) {
11906:                 $changes{$type}{$setting} = 1;
11907:             }
11908:         }
11909:     }
11910:     if (keys(%changes) > 0) {
11911:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
11912:         my $putresult = &Apache::lonnet::put_dom('configuration',
11913:                                                  \%serverstatushash,$dom);
11914:         if ($putresult eq 'ok') {
11915:             $resulttext .= &mt('Changes made:').'<ul>';
11916:             foreach my $type (@pages) {
11917:                 if (ref($changes{$type}) eq 'HASH') {
11918:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
11919:                     if ($changes{$type}{'namedusers'}) {
11920:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
11921:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
11922:                         } else {
11923:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
11924:                         }
11925:                     }
11926:                     if ($changes{$type}{'machines'}) {
11927:                         if ($newserverstatus{$type}{'machines'} eq '') {
11928:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
11929:                         } else {
11930:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
11931:                         }
11932: 
11933:                     }
11934:                     $resulttext .= '</ul></li>';
11935:                 }
11936:             }
11937:             $resulttext .= '</ul>';
11938:         } else {
11939:             $resulttext = '<span class="LC_error">'.
11940:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
11941: 
11942:         }
11943:     } else {
11944:         $resulttext = &mt('No changes made to access to server status pages');
11945:     }
11946:     return $resulttext;
11947: }
11948: 
11949: sub modify_helpsettings {
11950:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
11951:     my ($resulttext,$errors,%changes,%helphash);
11952:     my %defaultchecked = ('submitbugs' => 'on');
11953:     my @offon = ('off','on');
11954:     my @toggles = ('submitbugs');
11955:     my %current = ('submitbugs' => '',
11956:                    'adhoc'      => {},
11957:                   );
11958:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
11959:         %current = %{$domconfig{'helpsettings'}};
11960:     }
11961:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
11962:     foreach my $item (@toggles) {
11963:         if ($defaultchecked{$item} eq 'on') { 
11964:             if ($current{$item} eq '') {
11965:                 if ($env{'form.'.$item} eq '0') {
11966:                     $changes{$item} = 1;
11967:                 }
11968:             } elsif ($current{$item} ne $env{'form.'.$item}) {
11969:                 $changes{$item} = 1;
11970:             }
11971:         } elsif ($defaultchecked{$item} eq 'off') {
11972:             if ($current{$item} eq '') {
11973:                 if ($env{'form.'.$item} eq '1') {
11974:                     $changes{$item} = 1;
11975:                 }
11976:             } elsif ($current{$item} ne $env{'form.'.$item}) {
11977:                 $changes{$item} = 1;
11978:             }
11979:         }
11980:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
11981:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
11982:         }
11983:     }
11984:     my $maxnum = $env{'form.helproles_maxnum'};
11985:     my $confname = $dom.'-domainconfig';
11986:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
11987:     my (@allpos,%newsettings,%changedprivs,$newrole);
11988:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
11989:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
11990:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
11991:     my %lt = &Apache::lonlocal::texthash(
11992:                     s      => 'system',
11993:                     d      => 'domain',
11994:                     order  => 'Display order',
11995:                     access => 'Role usage',
11996:                     all    => 'All with domain helpdesk or helpdesk assistant role',
11997:                     dh     => 'All with domain helpdesk role',
11998:                     da     => 'All with domain helpdesk assistant role',
11999:                     none   => 'None',
12000:                     status => 'Determined based on institutional status',
12001:                     inc    => 'Include all, but exclude specific personnel',
12002:                     exc    => 'Exclude all, but include specific personnel',
12003:     );
12004:     for (my $num=0; $num<=$maxnum; $num++) {
12005:         my ($prefix,$identifier,$rolename,%curr);
12006:         if ($num == $maxnum) {
12007:             next unless ($env{'form.newcusthelp'} == $maxnum);
12008:             $identifier = 'custhelp'.$num;
12009:             $prefix = 'helproles_'.$num;
12010:             $rolename = $env{'form.custhelpname'.$num};
12011:             $rolename=~s/[^A-Za-z0-9]//gs;
12012:             next if ($rolename eq '');
12013:             next if (exists($existing{'rolesdef_'.$rolename}));
12014:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
12015:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
12016:                                                      $newprivs{'c'},$confname,$dom);
12017:             if ($result ne 'ok') {
12018:                 $errors .= '<li><span class="LC_error">'.
12019:                            &mt('An error occurred storing the new custom role: [_1]',
12020:                            $result).'</span></li>';
12021:                 next;
12022:             } else {
12023:                 $changedprivs{$rolename} = \%newprivs;
12024:                 $newrole = $rolename;
12025:             }
12026:         } else {
12027:             $prefix = 'helproles_'.$num;
12028:             $rolename = $env{'form.'.$prefix};
12029:             next if ($rolename eq '');
12030:             next unless (exists($existing{'rolesdef_'.$rolename}));
12031:             $identifier = 'custhelp'.$num;
12032:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
12033:             my %currprivs;
12034:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
12035:                 split(/\_/,$existing{'rolesdef_'.$rolename});
12036:             foreach my $level ('c','d','s') {
12037:                 if ($newprivs{$level} ne $currprivs{$level}) {
12038:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
12039:                                                              $newprivs{'c'},$confname,$dom);
12040:                     if ($result ne 'ok') {
12041:                         $errors .= '<li><span class="LC_error">'.
12042:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
12043:                                        $rolename,$result).'</span></li>';
12044:                     } else {
12045:                         $changedprivs{$rolename} = \%newprivs;
12046:                     }
12047:                     last;
12048:                 }
12049:             }
12050:             if (ref($current{'adhoc'}) eq 'HASH') {
12051:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
12052:                     %curr = %{$current{'adhoc'}{$rolename}};
12053:                 }
12054:             }
12055:         }
12056:         my $newpos = $env{'form.'.$prefix.'_pos'};
12057:         $newpos =~ s/\D+//g;
12058:         $allpos[$newpos] = $rolename;
12059:         my $newdesc = $env{'form.'.$prefix.'_desc'};
12060:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
12061:         if ($curr{'desc'}) {
12062:             if ($curr{'desc'} ne $newdesc) {
12063:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
12064:                 $newsettings{$rolename}{'desc'} = $newdesc;
12065:             }
12066:         } elsif ($newdesc ne '') {
12067:             $changes{'customrole'}{$rolename}{'desc'} = 1;
12068:             $newsettings{$rolename}{'desc'} = $newdesc;
12069:         }
12070:         my $access = $env{'form.'.$prefix.'_access'};
12071:         if (grep(/^\Q$access\E$/,@accesstypes)) {
12072:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
12073:             if ($access eq 'status') {
12074:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
12075:                 if (scalar(@statuses) == 0) {
12076:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
12077:                 } else {
12078:                     my (@shownstatus,$numtypes);
12079:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
12080:                     if (ref($types) eq 'ARRAY') {
12081:                         $numtypes = scalar(@{$types});
12082:                         foreach my $type (sort(@statuses)) {
12083:                             if ($type eq 'default') {
12084:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
12085:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
12086:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
12087:                                 push(@shownstatus,$usertypes->{$type});
12088:                             }
12089:                         }
12090:                     }
12091:                     if (grep(/^default$/,@statuses)) {
12092:                         push(@shownstatus,$othertitle);
12093:                     }
12094:                     if (scalar(@shownstatus) == 1+$numtypes) {
12095:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
12096:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
12097:                     } else {
12098:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
12099:                         if (ref($curr{'status'}) eq 'ARRAY') {
12100:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
12101:                             if (@diffs) {
12102:                                 $changes{'customrole'}{$rolename}{$access} = 1;
12103:                             }
12104:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
12105:                             $changes{'customrole'}{$rolename}{$access} = 1;
12106:                         }
12107:                     }
12108:                 }
12109:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
12110:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
12111:                 my @newspecstaff;
12112:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
12113:                 foreach my $person (sort(@personnel)) {
12114:                     if ($domhelpdesk{$person}) {
12115:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
12116:                     }
12117:                 }
12118:                 if (ref($curr{$access}) eq 'ARRAY') {
12119:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
12120:                     if (@diffs) {
12121:                         $changes{'customrole'}{$rolename}{$access} = 1;
12122:                     }
12123:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
12124:                     $changes{'customrole'}{$rolename}{$access} = 1;
12125:                 }
12126:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
12127:                     my ($uname,$udom) = split(/:/,$person);
12128:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
12129:                 }
12130:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
12131:             }
12132:         } else {
12133:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
12134:         }
12135:         unless ($curr{'access'} eq $access) {
12136:             $changes{'customrole'}{$rolename}{'access'} = 1;
12137:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
12138:         }
12139:     }
12140:     if (@allpos > 0) {
12141:         my $idx = 0;
12142:         foreach my $rolename (@allpos) {
12143:             if ($rolename ne '') {
12144:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
12145:                 if (ref($current{'adhoc'}) eq 'HASH') {
12146:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
12147:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
12148:                             $changes{'customrole'}{$rolename}{'order'} = 1;
12149:                             $newsettings{$rolename}{'order'} = $idx+1;
12150:                         }
12151:                     }
12152:                 }
12153:                 $idx ++;
12154:             }
12155:         }
12156:     }
12157:     my $putresult;
12158:     if (keys(%changes) > 0) {
12159:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
12160:         if ($putresult eq 'ok') {
12161:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
12162:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
12163:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
12164:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
12165:                 }
12166:             }
12167:             my $cachetime = 24*60*60;
12168:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
12169:             if (ref($lastactref) eq 'HASH') {
12170:                 $lastactref->{'domdefaults'} = 1;
12171:             }
12172:         } else {
12173:             $errors .= '<li><span class="LC_error">'.
12174:                        &mt('An error occurred storing the settings: [_1]',
12175:                            $putresult).'</span></li>';
12176:         }
12177:     }
12178:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
12179:         $resulttext = &mt('Changes made:').'<ul>';
12180:         my (%shownprivs,@levelorder);
12181:         @levelorder = ('c','d','s');
12182:         if ((keys(%changes)) && ($putresult eq 'ok')) {
12183:             foreach my $item (sort(keys(%changes))) {
12184:                 if ($item eq 'submitbugs') {
12185:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
12186:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
12187:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
12188:                 } elsif ($item eq 'customrole') {
12189:                     if (ref($changes{'customrole'}) eq 'HASH') {
12190:                         my @keyorder = ('order','desc','access','status','exc','inc');
12191:                         my %keytext = &Apache::lonlocal::texthash(
12192:                                                                    order  => 'Order',
12193:                                                                    desc   => 'Role description',
12194:                                                                    access => 'Role usage',
12195:                                                                    status => 'Allowed institutional types',
12196:                                                                    exc    => 'Allowed personnel',
12197:                                                                    inc    => 'Disallowed personnel',
12198:                         );
12199:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
12200:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
12201:                                 if ($role eq $newrole) {
12202:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
12203:                                                               $role).'<ul>';
12204:                                 } else {
12205:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
12206:                                                               $role).'<ul>';
12207:                                 }
12208:                                 foreach my $key (@keyorder) {
12209:                                     if ($changes{'customrole'}{$role}{$key}) {
12210:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
12211:                                                                   $keytext{$key},$newsettings{$role}{$key}).
12212:                                                        '</li>';
12213:                                     }
12214:                                 }
12215:                                 if (ref($changedprivs{$role}) eq 'HASH') {
12216:                                     $shownprivs{$role} = 1;
12217:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
12218:                                     foreach my $level (@levelorder) {
12219:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
12220:                                             next if ($item eq '');
12221:                                             my ($priv) = split(/\&/,$item,2);
12222:                                             if (&Apache::lonnet::plaintext($priv)) {
12223:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
12224:                                                 unless ($level eq 'c') {
12225:                                                     $resulttext .= ' ('.$lt{$level}.')';
12226:                                                 }
12227:                                                 $resulttext .= '</li>';
12228:                                             }
12229:                                         }
12230:                                     }
12231:                                     $resulttext .= '</ul>';
12232:                                 }
12233:                                 $resulttext .= '</ul></li>';
12234:                             }
12235:                         }
12236:                     }
12237:                 }
12238:             }
12239:         }
12240:         if (keys(%changedprivs)) {
12241:             foreach my $role (sort(keys(%changedprivs))) {
12242:                 unless ($shownprivs{$role}) {
12243:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
12244:                                               $role).'<ul>'.
12245:                                    '<li>'.&mt('Privileges set to :').'<ul>';
12246:                     foreach my $level (@levelorder) {
12247:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
12248:                             next if ($item eq '');
12249:                             my ($priv) = split(/\&/,$item,2);
12250:                             if (&Apache::lonnet::plaintext($priv)) {
12251:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
12252:                                 unless ($level eq 'c') {
12253:                                     $resulttext .= ' ('.$lt{$level}.')';
12254:                                 }
12255:                                 $resulttext .= '</li>';
12256:                             }
12257:                         }
12258:                     }
12259:                     $resulttext .= '</ul></li></ul></li>';
12260:                 }
12261:             }
12262:         }
12263:         $resulttext .= '</ul>';
12264:     } else {
12265:         $resulttext = &mt('No changes made to help settings');
12266:     }
12267:     if ($errors) {
12268:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
12269:                                     $errors.'</ul>';
12270:     }
12271:     return $resulttext;
12272: }
12273: 
12274: sub modify_coursedefaults {
12275:     my ($dom,$lastactref,%domconfig) = @_;
12276:     my ($resulttext,$errors,%changes,%defaultshash);
12277:     my %defaultchecked = (
12278:                            'uselcmath'       => 'on',
12279:                            'usejsme'         => 'on'
12280:                          );
12281:     my @toggles = ('uselcmath','usejsme');
12282:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
12283:                    'uploadquota_community','uploadquota_textbook','mysqltables_official',
12284:                    'mysqltables_unofficial','mysqltables_community','mysqltables_textbook');
12285:     my @types = ('official','unofficial','community','textbook');
12286:     my %staticdefaults = (
12287:                            anonsurvey_threshold => 10,
12288:                            uploadquota          => 500,
12289:                            postsubmit           => 60,
12290:                            mysqltables          => 172800,
12291:                          );
12292:     my %texoptions = (
12293:                         MathJax  => 'MathJax',
12294:                         mimetex  => &mt('Convert to Images'),
12295:                         tth      => &mt('TeX to HTML'),
12296:                      );
12297:     $defaultshash{'coursedefaults'} = {};
12298: 
12299:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
12300:         if ($domconfig{'coursedefaults'} eq '') {
12301:             $domconfig{'coursedefaults'} = {};
12302:         }
12303:     }
12304: 
12305:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
12306:         foreach my $item (@toggles) {
12307:             if ($defaultchecked{$item} eq 'on') {
12308:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
12309:                     ($env{'form.'.$item} eq '0')) {
12310:                     $changes{$item} = 1;
12311:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
12312:                     $changes{$item} = 1;
12313:                 }
12314:             } elsif ($defaultchecked{$item} eq 'off') {
12315:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
12316:                     ($env{'form.'.$item} eq '1')) {
12317:                     $changes{$item} = 1;
12318:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
12319:                     $changes{$item} = 1;
12320:                 }
12321:             }
12322:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
12323:         }
12324:         foreach my $item (@numbers) {
12325:             my ($currdef,$newdef);
12326:             $newdef = $env{'form.'.$item};
12327:             if ($item eq 'anonsurvey_threshold') {
12328:                 $currdef = $domconfig{'coursedefaults'}{$item};
12329:                 $newdef =~ s/\D//g;
12330:                 if ($newdef eq '' || $newdef < 1) {
12331:                     $newdef = 1;
12332:                 }
12333:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
12334:             } else {
12335:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
12336:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
12337:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
12338:                 }
12339:                 $newdef =~ s/[^\w.\-]//g;
12340:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
12341:             }
12342:             if ($currdef ne $newdef) {
12343:                 if ($item eq 'anonsurvey_threshold') {
12344:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
12345:                         $changes{$item} = 1;
12346:                     }
12347:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
12348:                     my $setting = $1;
12349:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
12350:                         $changes{$setting} = 1;
12351:                     }
12352:                 }
12353:             }
12354:         }
12355:         my $texengine;
12356:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
12357:             $texengine = $env{'form.texengine'};
12358:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
12359:             if ($currdef eq '') {
12360:                 unless ($texengine eq $Apache::lonnet::deftex) {
12361:                     $changes{'texengine'} = 1;
12362:                 }
12363:             } elsif ($currdef ne $texengine) {
12364:                 $changes{'texengine'} = 1;
12365:             }
12366:         }
12367:         if ($texengine ne '') {
12368:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
12369:         }
12370:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
12371:         my @currclonecode;
12372:         if (ref($currclone) eq 'HASH') {
12373:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
12374:                 @currclonecode = @{$currclone->{'instcode'}};
12375:             }
12376:         }
12377:         my $newclone;
12378:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
12379:             $newclone = $env{'form.canclone'};
12380:         }
12381:         if ($newclone eq 'instcode') {
12382:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
12383:             my (%codedefaults,@code_order,@clonecode);
12384:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
12385:                                                     \@code_order);
12386:             foreach my $item (@code_order) {
12387:                 if (grep(/^\Q$item\E$/,@newcodes)) {
12388:                     push(@clonecode,$item);
12389:                 }
12390:             }
12391:             if (@clonecode) {
12392:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
12393:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
12394:                 if (@diffs) {
12395:                     $changes{'canclone'} = 1;
12396:                 }
12397:             } else {
12398:                 $newclone eq '';
12399:             }
12400:         } elsif ($newclone ne '') {
12401:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
12402:         }
12403:         if ($newclone ne $currclone) {
12404:             $changes{'canclone'} = 1;
12405:         }
12406:         my %credits;
12407:         foreach my $type (@types) {
12408:             unless ($type eq 'community') {
12409:                 $credits{$type} = $env{'form.'.$type.'_credits'};
12410:                 $credits{$type} =~ s/[^\d.]+//g;
12411:             }
12412:         }
12413:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
12414:             ($env{'form.coursecredits'} eq '1')) {
12415:             $changes{'coursecredits'} = 1;
12416:             foreach my $type (keys(%credits)) {
12417:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
12418:             }
12419:         } else {
12420:             if ($env{'form.coursecredits'} eq '1') {
12421:                 foreach my $type (@types) {
12422:                     unless ($type eq 'community') {
12423:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
12424:                             $changes{'coursecredits'} = 1;
12425:                         }
12426:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
12427:                     }
12428:                 }
12429:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
12430:                 foreach my $type (@types) {
12431:                     unless ($type eq 'community') {
12432:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
12433:                             $changes{'coursecredits'} = 1;
12434:                             last;
12435:                         }
12436:                     }
12437:                 }
12438:             }
12439:         }
12440:         if ($env{'form.postsubmit'} eq '1') {
12441:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
12442:             my %currtimeout;
12443:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
12444:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
12445:                     $changes{'postsubmit'} = 1;
12446:                 }
12447:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
12448:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
12449:                 }
12450:             } else {
12451:                 $changes{'postsubmit'} = 1;
12452:             }
12453:             foreach my $type (@types) {
12454:                 my $timeout = $env{'form.'.$type.'_timeout'};
12455:                 $timeout =~ s/\D//g;
12456:                 if ($timeout == $staticdefaults{'postsubmit'}) {
12457:                     $timeout = '';
12458:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
12459:                     $timeout = '0';
12460:                 }
12461:                 unless ($timeout eq '') {
12462:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
12463:                 }
12464:                 if (exists($currtimeout{$type})) {
12465:                     if ($timeout ne $currtimeout{$type}) {
12466:                         $changes{'postsubmit'} = 1;
12467:                     }
12468:                 } elsif ($timeout ne '') {
12469:                     $changes{'postsubmit'} = 1;
12470:                 }
12471:             }
12472:         } else {
12473:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
12474:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
12475:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
12476:                     $changes{'postsubmit'} = 1;
12477:                 }
12478:             } else {
12479:                 $changes{'postsubmit'} = 1;
12480:             }
12481:         }
12482:     }
12483:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
12484:                                              $dom);
12485:     if ($putresult eq 'ok') {
12486:         if (keys(%changes) > 0) {
12487:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12488:             if (($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
12489:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
12490:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'})) {
12491:                 foreach my $item ('uselcmath','usejsme','texengine') {
12492:                     if ($changes{$item}) {
12493:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
12494:                     }
12495:                 }
12496:                 if ($changes{'coursecredits'}) {
12497:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
12498:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
12499:                             $domdefaults{$type.'credits'} =
12500:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
12501:                         }
12502:                     }
12503:                 }
12504:                 if ($changes{'postsubmit'}) {
12505:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
12506:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
12507:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
12508:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
12509:                                 $domdefaults{$type.'postsubtimeout'} =
12510:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
12511:                             }
12512:                         }
12513:                     }
12514:                 }
12515:                 if ($changes{'uploadquota'}) {
12516:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
12517:                         foreach my $type (@types) {
12518:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
12519:                         }
12520:                     }
12521:                 }
12522:                 if ($changes{'canclone'}) {
12523:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
12524:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
12525:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
12526:                             if (@clonecodes) {
12527:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
12528:                             }
12529:                         }
12530:                     } else {
12531:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
12532:                     }
12533:                 }
12534:                 my $cachetime = 24*60*60;
12535:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
12536:                 if (ref($lastactref) eq 'HASH') {
12537:                     $lastactref->{'domdefaults'} = 1;
12538:                 }
12539:             }
12540:             $resulttext = &mt('Changes made:').'<ul>';
12541:             foreach my $item (sort(keys(%changes))) {
12542:                 if ($item eq 'uselcmath') {
12543:                     if ($env{'form.'.$item} eq '1') {
12544:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
12545:                     } else {
12546:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
12547:                     }
12548:                 } elsif ($item eq 'usejsme') {
12549:                     if ($env{'form.'.$item} eq '1') {
12550:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
12551:                     } else {
12552:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
12553:                     }
12554:                 } elsif ($item eq 'texengine') {
12555:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
12556:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
12557:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
12558:                     }
12559:                 } elsif ($item eq 'anonsurvey_threshold') {
12560:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
12561:                 } elsif ($item eq 'uploadquota') {
12562:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
12563:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
12564:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
12565:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
12566:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
12567: 
12568:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
12569:                                        '</ul>'.
12570:                                        '</li>';
12571:                     } else {
12572:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
12573:                     }
12574:                 } elsif ($item eq 'mysqltables') {
12575:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
12576:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
12577:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
12578:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
12579:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
12580:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
12581:                                        '</ul>'.
12582:                                        '</li>';
12583:                     } else {
12584:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
12585:                     }
12586:                 } elsif ($item eq 'postsubmit') {
12587:                     if ($domdefaults{'postsubmit'} eq 'off') {
12588:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
12589:                     } else {
12590:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
12591:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
12592:                             $resulttext .= &mt('durations:').'<ul>';
12593:                             foreach my $type (@types) {
12594:                                 $resulttext .= '<li>';
12595:                                 my $timeout;
12596:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
12597:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
12598:                                 }
12599:                                 my $display;
12600:                                 if ($timeout eq '0') {
12601:                                     $display = &mt('unlimited');
12602:                                 } elsif ($timeout eq '') {
12603:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
12604:                                 } else {
12605:                                     $display = &mt('[quant,_1,second]',$timeout);
12606:                                 }
12607:                                 if ($type eq 'community') {
12608:                                     $resulttext .= &mt('Communities');
12609:                                 } elsif ($type eq 'official') {
12610:                                     $resulttext .= &mt('Official courses');
12611:                                 } elsif ($type eq 'unofficial') {
12612:                                     $resulttext .= &mt('Unofficial courses');
12613:                                 } elsif ($type eq 'textbook') {
12614:                                     $resulttext .= &mt('Textbook courses');
12615:                                 }
12616:                                 $resulttext .= ' -- '.$display.'</li>';
12617:                             }
12618:                             $resulttext .= '</ul>';
12619:                         }
12620:                         $resulttext .= '</li>';
12621:                     }
12622:                 } elsif ($item eq 'coursecredits') {
12623:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
12624:                         if (($domdefaults{'officialcredits'} eq '') &&
12625:                             ($domdefaults{'unofficialcredits'} eq '') &&
12626:                             ($domdefaults{'textbookcredits'} eq '')) {
12627:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
12628:                         } else {
12629:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
12630:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
12631:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
12632:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
12633:                                            '</ul>'.
12634:                                            '</li>';
12635:                         }
12636:                     } else {
12637:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
12638:                     }
12639:                 } elsif ($item eq 'canclone') {
12640:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
12641:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
12642:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
12643:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
12644:                         }
12645:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
12646:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
12647:                     } else {
12648:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
12649:                     }
12650:                 }
12651:             }
12652:             $resulttext .= '</ul>';
12653:         } else {
12654:             $resulttext = &mt('No changes made to course defaults');
12655:         }
12656:     } else {
12657:         $resulttext = '<span class="LC_error">'.
12658:             &mt('An error occurred: [_1]',$putresult).'</span>';
12659:     }
12660:     return $resulttext;
12661: }
12662: 
12663: sub modify_selfenrollment {
12664:     my ($dom,$lastactref,%domconfig) = @_;
12665:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
12666:     my @types = ('official','unofficial','community','textbook');
12667:     my %titles = &tool_titles();
12668:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
12669:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
12670:     $ordered{'default'} = ['types','registered','approval','limit'];
12671: 
12672:     my (%roles,%shown,%toplevel);
12673:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
12674: 
12675:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
12676:         if ($domconfig{'selfenrollment'} eq '') {
12677:             $domconfig{'selfenrollment'} = {};
12678:         }
12679:     }
12680:     %toplevel = (
12681:                   admin      => 'Configuration Rights',
12682:                   default    => 'Default settings',
12683:                   validation => 'Validation of self-enrollment requests',
12684:                 );
12685:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
12686: 
12687:     if (ref($ordered{'admin'}) eq 'ARRAY') {
12688:         foreach my $item (@{$ordered{'admin'}}) {
12689:             foreach my $type (@types) {
12690:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
12691:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
12692:                 } else {
12693:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
12694:                 }
12695:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
12696:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
12697:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
12698:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
12699:                             push(@{$changes{'admin'}{$type}},$item);
12700:                         }
12701:                     } else {
12702:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
12703:                             push(@{$changes{'admin'}{$type}},$item);
12704:                         }
12705:                     }
12706:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
12707:                     push(@{$changes{'admin'}{$type}},$item);
12708:                 }
12709:             }
12710:         }
12711:     }
12712: 
12713:     foreach my $item (@{$ordered{'default'}}) {
12714:         foreach my $type (@types) {
12715:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
12716:             if ($item eq 'types') {
12717:                 unless (($value eq 'all') || ($value eq 'dom')) {
12718:                     $value = '';
12719:                 }
12720:             } elsif ($item eq 'registered') {
12721:                 unless ($value eq '1') {
12722:                     $value = 0;
12723:                 }
12724:             } elsif ($item eq 'approval') {
12725:                 unless ($value =~ /^[012]$/) {
12726:                     $value = 0;
12727:                 }
12728:             } else {
12729:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
12730:                     $value = 'none';
12731:                 }
12732:             }
12733:             $selfenrollhash{'default'}{$type}{$item} = $value;
12734:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
12735:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
12736:                     if ($selfenrollhash{'default'}{$type}{$item} ne
12737:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
12738:                          push(@{$changes{'default'}{$type}},$item);
12739:                     }
12740:                 } else {
12741:                     push(@{$changes{'default'}{$type}},$item);
12742:                 }
12743:             } else {
12744:                 push(@{$changes{'default'}{$type}},$item);
12745:             }
12746:             if ($item eq 'limit') {
12747:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
12748:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
12749:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
12750:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
12751:                     }
12752:                 } else {
12753:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
12754:                 }
12755:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
12756:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
12757:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
12758:                          push(@{$changes{'default'}{$type}},'cap');
12759:                     }
12760:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
12761:                     push(@{$changes{'default'}{$type}},'cap');
12762:                 }
12763:             }
12764:         }
12765:     }
12766: 
12767:     foreach my $item (@{$itemsref}) {
12768:         if ($item eq 'fields') {
12769:             my @changed;
12770:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
12771:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
12772:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
12773:             }
12774:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
12775:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
12776:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
12777:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
12778:                 } else {
12779:                     @changed = @{$selfenrollhash{'validation'}{$item}};
12780:                 }
12781:             } else {
12782:                 @changed = @{$selfenrollhash{'validation'}{$item}};
12783:             }
12784:             if (@changed) {
12785:                 if ($selfenrollhash{'validation'}{$item}) { 
12786:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
12787:                 } else {
12788:                     $changes{'validation'}{$item} = &mt('None');
12789:                 }
12790:             }
12791:         } else {
12792:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
12793:             if ($item eq 'markup') {
12794:                if ($env{'form.selfenroll_validation_'.$item}) {
12795:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
12796:                }
12797:             }
12798:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
12799:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
12800:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
12801:                 }
12802:             }
12803:         }
12804:     }
12805: 
12806:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
12807:                                              $dom);
12808:     if ($putresult eq 'ok') {
12809:         if (keys(%changes) > 0) {
12810:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12811:             $resulttext = &mt('Changes made:').'<ul>';
12812:             foreach my $key ('admin','default','validation') {
12813:                 if (ref($changes{$key}) eq 'HASH') {
12814:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
12815:                     if ($key eq 'validation') {
12816:                         foreach my $item (@{$itemsref}) {
12817:                             if (exists($changes{$key}{$item})) {
12818:                                 if ($item eq 'markup') {
12819:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
12820:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
12821:                                 } else {  
12822:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
12823:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
12824:                                 }
12825:                             }
12826:                         }
12827:                     } else {
12828:                         foreach my $type (@types) {
12829:                             if ($type eq 'community') {
12830:                                 $roles{'1'} = &mt('Community personnel');
12831:                             } else {
12832:                                 $roles{'1'} = &mt('Course personnel');
12833:                             }
12834:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
12835:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
12836:                                     if ($key eq 'admin') {
12837:                                         my @mgrdc = ();
12838:                                         if (ref($ordered{$key}) eq 'ARRAY') {
12839:                                             foreach my $item (@{$ordered{'admin'}}) {
12840:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
12841:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
12842:                                                         push(@mgrdc,$item);
12843:                                                     }
12844:                                                 }
12845:                                             }
12846:                                             if (@mgrdc) {
12847:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
12848:                                             } else {
12849:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
12850:                                             }
12851:                                         }
12852:                                     } else {
12853:                                         if (ref($ordered{$key}) eq 'ARRAY') {
12854:                                             foreach my $item (@{$ordered{$key}}) {
12855:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
12856:                                                     $domdefaults{$type.'selfenroll'.$item} =
12857:                                                         $selfenrollhash{$key}{$type}{$item};
12858:                                                 }
12859:                                             }
12860:                                         }
12861:                                     }
12862:                                 }
12863:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
12864:                                 foreach my $item (@{$ordered{$key}}) {
12865:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
12866:                                         $resulttext .= '<li>';
12867:                                         if ($key eq 'admin') {
12868:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
12869:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
12870:                                         } else {
12871:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
12872:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
12873:                                         }
12874:                                         $resulttext .= '</li>';
12875:                                     }
12876:                                 }
12877:                                 $resulttext .= '</ul></li>';
12878:                             }
12879:                         }
12880:                         $resulttext .= '</ul></li>'; 
12881:                     }
12882:                 }
12883:             }
12884:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
12885:                 my $cachetime = 24*60*60;
12886:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
12887:                 if (ref($lastactref) eq 'HASH') {
12888:                     $lastactref->{'domdefaults'} = 1;
12889:                 }
12890:             }
12891:             $resulttext .= '</ul>';
12892:         } else {
12893:             $resulttext = &mt('No changes made to self-enrollment settings');
12894:         }
12895:     } else {
12896:         $resulttext = '<span class="LC_error">'.
12897:             &mt('An error occurred: [_1]',$putresult).'</span>';
12898:     }
12899:     return $resulttext;
12900: }
12901: 
12902: sub modify_usersessions {
12903:     my ($dom,$lastactref,%domconfig) = @_;
12904:     my @hostingtypes = ('version','excludedomain','includedomain');
12905:     my @offloadtypes = ('primary','default');
12906:     my %types = (
12907:                   remote => \@hostingtypes,
12908:                   hosted => \@hostingtypes,
12909:                   spares => \@offloadtypes,
12910:                 );
12911:     my @prefixes = ('remote','hosted','spares');
12912:     my @lcversions = &Apache::lonnet::all_loncaparevs();
12913:     my (%by_ip,%by_location,@intdoms);
12914:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
12915:     my @locations = sort(keys(%by_location));
12916:     my (%defaultshash,%changes);
12917:     foreach my $prefix (@prefixes) {
12918:         $defaultshash{'usersessions'}{$prefix} = {};
12919:     }
12920:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12921:     my $resulttext;
12922:     my %iphost = &Apache::lonnet::get_iphost();
12923:     foreach my $prefix (@prefixes) {
12924:         next if ($prefix eq 'spares');
12925:         foreach my $type (@{$types{$prefix}}) {
12926:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
12927:             if ($type eq 'version') {
12928:                 my $value = $env{'form.'.$prefix.'_'.$type};
12929:                 my $okvalue;
12930:                 if ($value ne '') {
12931:                     if (grep(/^\Q$value\E$/,@lcversions)) {
12932:                         $okvalue = $value;
12933:                     }
12934:                 }
12935:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
12936:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
12937:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
12938:                             if ($inuse == 0) {
12939:                                 $changes{$prefix}{$type} = 1;
12940:                             } else {
12941:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
12942:                                     $changes{$prefix}{$type} = 1;
12943:                                 }
12944:                                 if ($okvalue ne '') {
12945:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
12946:                                 } 
12947:                             }
12948:                         } else {
12949:                             if (($inuse == 1) && ($okvalue ne '')) {
12950:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
12951:                                 $changes{$prefix}{$type} = 1;
12952:                             }
12953:                         }
12954:                     } else {
12955:                         if (($inuse == 1) && ($okvalue ne '')) {
12956:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
12957:                             $changes{$prefix}{$type} = 1;
12958:                         }
12959:                     }
12960:                 } else {
12961:                     if (($inuse == 1) && ($okvalue ne '')) {
12962:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
12963:                         $changes{$prefix}{$type} = 1;
12964:                     }
12965:                 }
12966:             } else {
12967:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
12968:                 my @okvals;
12969:                 foreach my $val (@vals) {
12970:                     if ($val =~ /:/) {
12971:                         my @items = split(/:/,$val);
12972:                         foreach my $item (@items) {
12973:                             if (ref($by_location{$item}) eq 'ARRAY') {
12974:                                 push(@okvals,$item);
12975:                             }
12976:                         }
12977:                     } else {
12978:                         if (ref($by_location{$val}) eq 'ARRAY') {
12979:                             push(@okvals,$val);
12980:                         }
12981:                     }
12982:                 }
12983:                 @okvals = sort(@okvals);
12984:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
12985:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
12986:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
12987:                             if ($inuse == 0) {
12988:                                 $changes{$prefix}{$type} = 1; 
12989:                             } else {
12990:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
12991:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
12992:                                 if (@changed > 0) {
12993:                                     $changes{$prefix}{$type} = 1;
12994:                                 }
12995:                             }
12996:                         } else {
12997:                             if ($inuse == 1) {
12998:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
12999:                                 $changes{$prefix}{$type} = 1;
13000:                             }
13001:                         } 
13002:                     } else {
13003:                         if ($inuse == 1) {
13004:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
13005:                             $changes{$prefix}{$type} = 1;
13006:                         }
13007:                     }
13008:                 } else {
13009:                     if ($inuse == 1) {
13010:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
13011:                         $changes{$prefix}{$type} = 1;
13012:                     }
13013:                 }
13014:             }
13015:         }
13016:     }
13017: 
13018:     my @alldoms = &Apache::lonnet::all_domains();
13019:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
13020:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
13021:     my $savespares;
13022: 
13023:     foreach my $lonhost (sort(keys(%servers))) {
13024:         my $serverhomeID =
13025:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
13026:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
13027:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
13028:         my %spareschg;
13029:         foreach my $type (@{$types{'spares'}}) {
13030:             my @okspares;
13031:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
13032:             foreach my $server (@checked) {
13033:                 if (&Apache::lonnet::hostname($server) ne '') {
13034:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
13035:                         unless (grep(/^\Q$server\E$/,@okspares)) {
13036:                             push(@okspares,$server);
13037:                         }
13038:                     }
13039:                 }
13040:             }
13041:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
13042:             my $newspare;
13043:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
13044:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
13045:                     $newspare = $new;
13046:                 }
13047:             }
13048:             my @spares;
13049:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
13050:                 @spares = sort(@okspares,$newspare);
13051:             } else {
13052:                 @spares = sort(@okspares);
13053:             }
13054:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
13055:             if (ref($spareid{$lonhost}) eq 'HASH') {
13056:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
13057:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
13058:                     if (@diffs > 0) {
13059:                         $spareschg{$type} = 1;
13060:                     }
13061:                 }
13062:             }
13063:         }
13064:         if (keys(%spareschg) > 0) {
13065:             $changes{'spares'}{$lonhost} = \%spareschg;
13066:         }
13067:     }
13068:     $defaultshash{'usersessions'}{'offloadnow'} = {};
13069:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
13070:     my @okoffload;
13071:     if (@offloadnow) {
13072:         foreach my $server (@offloadnow) {
13073:             if (&Apache::lonnet::hostname($server) ne '') {
13074:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
13075:                     push(@okoffload,$server);
13076:                 }
13077:             }
13078:         }
13079:         if (@okoffload) {
13080:             foreach my $lonhost (@okoffload) {
13081:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
13082:             }
13083:         }
13084:     }
13085:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
13086:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
13087:             if (ref($changes{'spares'}) eq 'HASH') {
13088:                 if (keys(%{$changes{'spares'}}) > 0) {
13089:                     $savespares = 1;
13090:                 }
13091:             }
13092:         } else {
13093:             $savespares = 1;
13094:         }
13095:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
13096:             foreach my $lonhost (keys(%{$domconfig{'usersessions'}{'offloadnow'}})) {
13097:                 unless ($defaultshash{'usersessions'}{'offloadnow'}{$lonhost}) {
13098:                     $changes{'offloadnow'} = 1;
13099:                     last;
13100:                 }
13101:             }
13102:             unless ($changes{'offloadnow'}) {
13103:                 foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{'offloadnow'}})) {
13104:                     unless ($domconfig{'usersessions'}{'offloadnow'}{$lonhost}) {
13105:                         $changes{'offloadnow'} = 1;
13106:                         last;
13107:                     }
13108:                 }
13109:             }
13110:         } elsif (@okoffload) {
13111:             $changes{'offloadnow'} = 1;
13112:         }
13113:     } elsif (@okoffload) {
13114:         $changes{'offloadnow'} = 1;
13115:     }
13116:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
13117:     if ((keys(%changes) > 0) || ($savespares)) {
13118:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
13119:                                                  $dom);
13120:         if ($putresult eq 'ok') {
13121:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
13122:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
13123:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
13124:                 }
13125:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
13126:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
13127:                 }
13128:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
13129:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
13130:                 }
13131:             }
13132:             my $cachetime = 24*60*60;
13133:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
13134:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
13135:             if (ref($lastactref) eq 'HASH') {
13136:                 $lastactref->{'domdefaults'} = 1;
13137:                 $lastactref->{'usersessions'} = 1;
13138:             }
13139:             if (keys(%changes) > 0) {
13140:                 my %lt = &usersession_titles();
13141:                 $resulttext = &mt('Changes made:').'<ul>';
13142:                 foreach my $prefix (@prefixes) {
13143:                     if (ref($changes{$prefix}) eq 'HASH') {
13144:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
13145:                         if ($prefix eq 'spares') {
13146:                             if (ref($changes{$prefix}) eq 'HASH') {
13147:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
13148:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
13149:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
13150:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
13151:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
13152:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
13153:                                         foreach my $type (@{$types{$prefix}}) {
13154:                                             if ($changes{$prefix}{$lonhost}{$type}) {
13155:                                                 my $offloadto = &mt('None');
13156:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
13157:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
13158:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
13159:                                                     }
13160:                                                 }
13161:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
13162:                                             }
13163:                                         }
13164:                                     }
13165:                                     $resulttext .= '</li>';
13166:                                 }
13167:                             }
13168:                         } else {
13169:                             foreach my $type (@{$types{$prefix}}) {
13170:                                 if (defined($changes{$prefix}{$type})) {
13171:                                     my $newvalue;
13172:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
13173:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
13174:                                             if ($type eq 'version') {
13175:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
13176:                                             } elsif (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
13177:                                                 if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
13178:                                                     $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
13179:                                                 }
13180:                                             }
13181:                                         }
13182:                                     }
13183:                                     if ($newvalue eq '') {
13184:                                         if ($type eq 'version') {
13185:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
13186:                                         } else {
13187:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
13188:                                         }
13189:                                     } else {
13190:                                         if ($type eq 'version') {
13191:                                             $newvalue .= ' '.&mt('(or later)'); 
13192:                                         }
13193:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
13194:                                     }
13195:                                 }
13196:                             }
13197:                         }
13198:                         $resulttext .= '</ul>';
13199:                     }
13200:                 }
13201:                 if ($changes{'offloadnow'}) {
13202:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
13203:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
13204:                             $resulttext .= '<li>'.&mt('Switch active users on next access, for server(s):').'<ul>';
13205:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
13206:                                 $resulttext .= '<li>'.$lonhost.'</li>';
13207:                             }
13208:                             $resulttext .= '</ul>';
13209:                         } else {
13210:                             $resulttext .= '<li>'.&mt('No servers now set to switch active users on next access.');
13211:                         }
13212:                     } else {
13213:                         $resulttext .= '<li>'.&mt('No servers now set to switch active users on next access.').'</li>';
13214:                     }
13215:                 }
13216:                 $resulttext .= '</ul>';
13217:             } else {
13218:                 $resulttext = $nochgmsg;
13219:             }
13220:         } else {
13221:             $resulttext = '<span class="LC_error">'.
13222:                           &mt('An error occurred: [_1]',$putresult).'</span>';
13223:         }
13224:     } else {
13225:         $resulttext = $nochgmsg;
13226:     }
13227:     return $resulttext;
13228: }
13229: 
13230: sub modify_loadbalancing {
13231:     my ($dom,%domconfig) = @_;
13232:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
13233:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
13234:     my ($othertitle,$usertypes,$types) =
13235:         &Apache::loncommon::sorted_inst_types($dom);
13236:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
13237:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
13238:     my @sparestypes = ('primary','default');
13239:     my %typetitles = &sparestype_titles();
13240:     my $resulttext;
13241:     my (%currbalancer,%currtargets,%currrules,%existing);
13242:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
13243:         %existing = %{$domconfig{'loadbalancing'}};
13244:     }
13245:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
13246:                               \%currtargets,\%currrules);
13247:     my ($saveloadbalancing,%defaultshash,%changes);
13248:     my ($alltypes,$othertypes,$titles) =
13249:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
13250:     my %ruletitles = &offloadtype_text();
13251:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
13252:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
13253:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
13254:         if ($balancer eq '') {
13255:             next;
13256:         }
13257:         if (!exists($servers{$balancer})) {
13258:             if (exists($currbalancer{$balancer})) {
13259:                 push(@{$changes{'delete'}},$balancer);
13260:             }
13261:             next;
13262:         }
13263:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
13264:             push(@{$changes{'delete'}},$balancer);
13265:             next;
13266:         }
13267:         if (!exists($currbalancer{$balancer})) {
13268:             push(@{$changes{'add'}},$balancer);
13269:         }
13270:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
13271:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
13272:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
13273:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
13274:             $saveloadbalancing = 1;
13275:         }
13276:         foreach my $sparetype (@sparestypes) {
13277:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
13278:             my @offloadto;
13279:             foreach my $target (@targets) {
13280:                 if (($servers{$target}) && ($target ne $balancer)) {
13281:                     if ($sparetype eq 'default') {
13282:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
13283:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
13284:                         }
13285:                     }
13286:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
13287:                         push(@offloadto,$target);
13288:                     }
13289:                 }
13290:             }
13291:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
13292:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
13293:                     push(@offloadto,$balancer);
13294:                 }
13295:             }
13296:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
13297:         }
13298:         if (ref($currtargets{$balancer}) eq 'HASH') {
13299:             foreach my $sparetype (@sparestypes) {
13300:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
13301:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
13302:                     if (@targetdiffs > 0) {
13303:                         $changes{'curr'}{$balancer}{'targets'} = 1;
13304:                     }
13305:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
13306:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
13307:                         $changes{'curr'}{$balancer}{'targets'} = 1;
13308:                     }
13309:                 }
13310:             }
13311:         } else {
13312:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
13313:                 foreach my $sparetype (@sparestypes) {
13314:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
13315:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
13316:                             $changes{'curr'}{$balancer}{'targets'} = 1;
13317:                         }
13318:                     }
13319:                 }
13320:             }
13321:         }
13322:         my $ishomedom;
13323:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
13324:             $ishomedom = 1;
13325:         }
13326:         if (ref($alltypes) eq 'ARRAY') {
13327:             foreach my $type (@{$alltypes}) {
13328:                 my $rule;
13329:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
13330:                          (!$ishomedom)) {
13331:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
13332:                 }
13333:                 if ($rule eq 'specific') {
13334:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
13335:                     if (exists($servers{$specifiedhost})) {
13336:                         $rule = $specifiedhost;
13337:                     }
13338:                 }
13339:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
13340:                 if (ref($currrules{$balancer}) eq 'HASH') {
13341:                     if ($rule ne $currrules{$balancer}{$type}) {
13342:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
13343:                     }
13344:                 } elsif ($rule ne '') {
13345:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
13346:                 }
13347:             }
13348:         }
13349:     }
13350:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
13351:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
13352:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
13353:             $defaultshash{'loadbalancing'} = {};
13354:         }
13355:         my $putresult = &Apache::lonnet::put_dom('configuration',
13356:                                                  \%defaultshash,$dom);
13357:         if ($putresult eq 'ok') {
13358:             if (keys(%changes) > 0) {
13359:                 my %toupdate;
13360:                 if (ref($changes{'delete'}) eq 'ARRAY') {
13361:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
13362:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
13363:                         $toupdate{$balancer} = 1;
13364:                     }
13365:                 }
13366:                 if (ref($changes{'add'}) eq 'ARRAY') {
13367:                     foreach my $balancer (sort(@{$changes{'add'}})) {
13368:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
13369:                         $toupdate{$balancer} = 1;
13370:                     }
13371:                 }
13372:                 if (ref($changes{'curr'}) eq 'HASH') {
13373:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
13374:                         $toupdate{$balancer} = 1;
13375:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
13376:                             if ($changes{'curr'}{$balancer}{'targets'}) {
13377:                                 my %offloadstr;
13378:                                 foreach my $sparetype (@sparestypes) {
13379:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
13380:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
13381:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
13382:                                         }
13383:                                     }
13384:                                 }
13385:                                 if (keys(%offloadstr) == 0) {
13386:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
13387:                                 } else {
13388:                                     my $showoffload;
13389:                                     foreach my $sparetype (@sparestypes) {
13390:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
13391:                                         if (defined($offloadstr{$sparetype})) {
13392:                                             $showoffload .= $offloadstr{$sparetype};
13393:                                         } else {
13394:                                             $showoffload .= &mt('None');
13395:                                         }
13396:                                         $showoffload .= ('&nbsp;'x3);
13397:                                     }
13398:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
13399:                                 }
13400:                             }
13401:                         }
13402:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
13403:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
13404:                                 foreach my $type (@{$alltypes}) {
13405:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
13406:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
13407:                                         my $balancetext;
13408:                                         if ($rule eq '') {
13409:                                             $balancetext =  $ruletitles{'default'};
13410:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
13411:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
13412:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
13413:                                                 foreach my $sparetype (@sparestypes) {
13414:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
13415:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
13416:                                                     }
13417:                                                 }
13418:                                                 foreach my $item (@{$alltypes}) {
13419:                                                     next if ($item =~  /^_LC_ipchange/);
13420:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
13421:                                                     if ($hasrule eq 'homeserver') {
13422:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
13423:                                                     } else {
13424:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
13425:                                                             if ($servers{$hasrule}) {
13426:                                                                 $toupdate{$hasrule} = 1;
13427:                                                             }
13428:                                                         }
13429:                                                     }
13430:                                                 }
13431:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
13432:                                                     $balancetext =  $ruletitles{$rule};
13433:                                                 } else {
13434:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
13435:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
13436:                                                     if ($receiver) {
13437:                                                         $toupdate{$receiver};
13438:                                                     }
13439:                                                 }
13440:                                             } else {
13441:                                                 $balancetext =  $ruletitles{$rule};
13442:                                             }
13443:                                         } else {
13444:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
13445:                                         }
13446:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
13447:                                     }
13448:                                 }
13449:                             }
13450:                         }
13451:                         if (keys(%toupdate)) {
13452:                             my %thismachine;
13453:                             my $updatedhere;
13454:                             my $cachetime = 60*60*24;
13455:                             map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
13456:                             foreach my $lonhost (keys(%toupdate)) {
13457:                                 if ($thismachine{$lonhost}) {
13458:                                     unless ($updatedhere) {
13459:                                         &Apache::lonnet::do_cache_new('loadbalancing',$dom,
13460:                                                                       $defaultshash{'loadbalancing'},
13461:                                                                       $cachetime);
13462:                                         $updatedhere = 1;
13463:                                     }
13464:                                 } else {
13465:                                     my $cachekey = &escape('loadbalancing').':'.&escape($dom);
13466:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
13467:                                 }
13468:                             }
13469:                         }
13470:                     }
13471:                 }
13472:                 if ($resulttext ne '') {
13473:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
13474:                 } else {
13475:                     $resulttext = $nochgmsg;
13476:                 }
13477:             } else {
13478:                 $resulttext = $nochgmsg;
13479:             }
13480:         } else {
13481:             $resulttext = '<span class="LC_error">'.
13482:                           &mt('An error occurred: [_1]',$putresult).'</span>';
13483:         }
13484:     } else {
13485:         $resulttext = $nochgmsg;
13486:     }
13487:     return $resulttext;
13488: }
13489: 
13490: sub recurse_check {
13491:     my ($chkcats,$categories,$depth,$name) = @_;
13492:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
13493:         my $chg = 0;
13494:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
13495:             my $category = $chkcats->[$depth]{$name}[$j];
13496:             my $item;
13497:             if ($category eq '') {
13498:                 $chg ++;
13499:             } else {
13500:                 my $deeper = $depth + 1;
13501:                 $item = &escape($category).':'.&escape($name).':'.$depth;
13502:                 if ($chg) {
13503:                     $categories->{$item} -= $chg;
13504:                 }
13505:                 &recurse_check($chkcats,$categories,$deeper,$category);
13506:                 $deeper --;
13507:             }
13508:         }
13509:     }
13510:     return;
13511: }
13512: 
13513: sub recurse_cat_deletes {
13514:     my ($item,$coursecategories,$deletions) = @_;
13515:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
13516:     my $subdepth = $depth + 1;
13517:     if (ref($coursecategories) eq 'HASH') {
13518:         foreach my $subitem (keys(%{$coursecategories})) {
13519:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
13520:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
13521:                 delete($coursecategories->{$subitem});
13522:                 $deletions->{$subitem} = 1;
13523:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
13524:             }
13525:         }
13526:     }
13527:     return;
13528: }
13529: 
13530: sub active_dc_picker {
13531:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
13532:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
13533:     my @domcoord = keys(%domcoords);
13534:     if (keys(%currhash)) {
13535:         foreach my $dc (keys(%currhash)) {
13536:             unless (exists($domcoords{$dc})) {
13537:                 push(@domcoord,$dc);
13538:             }
13539:         }
13540:     }
13541:     @domcoord = sort(@domcoord);
13542:     my $numdcs = scalar(@domcoord);
13543:     my $rows = 0;
13544:     my $table;
13545:     if ($numdcs > 1) {
13546:         $table = '<table>';
13547:         for (my $i=0; $i<@domcoord; $i++) {
13548:             my $rem = $i%($numinrow);
13549:             if ($rem == 0) {
13550:                 if ($i > 0) {
13551:                     $table .= '</tr>';
13552:                 }
13553:                 $table .= '<tr>';
13554:                 $rows ++;
13555:             }
13556:             my $check = '';
13557:             if ($inputtype eq 'radio') {
13558:                 if (keys(%currhash) == 0) {
13559:                     if (!$i) {
13560:                         $check = ' checked="checked"';
13561:                     }
13562:                 } elsif (exists($currhash{$domcoord[$i]})) {
13563:                     $check = ' checked="checked"';
13564:                 }
13565:             } else {
13566:                 if (exists($currhash{$domcoord[$i]})) {
13567:                     $check = ' checked="checked"';
13568:                 }
13569:             }
13570:             if ($i == @domcoord - 1) {
13571:                 my $colsleft = $numinrow - $rem;
13572:                 if ($colsleft > 1) {
13573:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
13574:                 } else {
13575:                     $table .= '<td class="LC_left_item">';
13576:                 }
13577:             } else {
13578:                 $table .= '<td class="LC_left_item">';
13579:             }
13580:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
13581:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
13582:             $table .= '<span class="LC_nobreak"><label>'.
13583:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
13584:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
13585:             if ($user ne $dcname.':'.$dcdom) {
13586:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
13587:             }
13588:             $table .= '</label></span></td>';
13589:         }
13590:         $table .= '</tr></table>';
13591:     } elsif ($numdcs == 1) {
13592:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
13593:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
13594:         if ($inputtype eq 'radio') {
13595:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
13596:             if ($user ne $dcname.':'.$dcdom) {
13597:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
13598:             }
13599:         } else {
13600:             my $check;
13601:             if (exists($currhash{$domcoord[0]})) {
13602:                 $check = ' checked="checked"';
13603:             }
13604:             $table = '<span class="LC_nobreak"><label>'.
13605:                      '<input type="checkbox" name="'.$name.'" '.
13606:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
13607:             if ($user ne $dcname.':'.$dcdom) {
13608:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
13609:             }
13610:             $table .= '</label></span>';
13611:             $rows ++;
13612:         }
13613:     }
13614:     return ($numdcs,$table,$rows);
13615: }
13616: 
13617: sub usersession_titles {
13618:     return &Apache::lonlocal::texthash(
13619:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
13620:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
13621:                spares => 'Servers offloaded to, when busy',
13622:                version => 'LON-CAPA version requirement',
13623:                excludedomain => 'Allow all, but exclude specific domains',
13624:                includedomain => 'Deny all, but include specific domains',
13625:                primary => 'Primary (checked first)',
13626:                default => 'Default',
13627:            );
13628: }
13629: 
13630: sub id_for_thisdom {
13631:     my (%servers) = @_;
13632:     my %altids;
13633:     foreach my $server (keys(%servers)) {
13634:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
13635:         if ($serverhome ne $server) {
13636:             $altids{$serverhome} = $server;
13637:         }
13638:     }
13639:     return %altids;
13640: }
13641: 
13642: sub count_servers {
13643:     my ($currbalancer,%servers) = @_;
13644:     my (@spares,$numspares);
13645:     foreach my $lonhost (sort(keys(%servers))) {
13646:         next if ($currbalancer eq $lonhost);
13647:         push(@spares,$lonhost);
13648:     }
13649:     if ($currbalancer) {
13650:         $numspares = scalar(@spares);
13651:     } else {
13652:         $numspares = scalar(@spares) - 1;
13653:     }
13654:     return ($numspares,@spares);
13655: }
13656: 
13657: sub lonbalance_targets_js {
13658:     my ($dom,$types,$servers,$settings) = @_;
13659:     my $select = &mt('Select');
13660:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
13661:     if (ref($servers) eq 'HASH') {
13662:         $alltargets = join("','",sort(keys(%{$servers})));
13663:         my @homedoms;
13664:         foreach my $server (sort(keys(%{$servers}))) {
13665:             if (&Apache::lonnet::host_domain($server) eq $dom) {
13666:                 push(@homedoms,'1');
13667:             } else {
13668:                 push(@homedoms,'0');
13669:             }
13670:         }
13671:         $allishome = join("','",@homedoms);
13672:     }
13673:     if (ref($types) eq 'ARRAY') {
13674:         if (@{$types} > 0) {
13675:             @alltypes = @{$types};
13676:         }
13677:     }
13678:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
13679:     $allinsttypes = join("','",@alltypes);
13680:     my (%currbalancer,%currtargets,%currrules,%existing);
13681:     if (ref($settings) eq 'HASH') {
13682:         %existing = %{$settings};
13683:     }
13684:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
13685:                               \%currtargets,\%currrules);
13686:     my $balancers = join("','",sort(keys(%currbalancer)));
13687:     return <<"END";
13688: 
13689: <script type="text/javascript">
13690: // <![CDATA[
13691: 
13692: currBalancers = new Array('$balancers');
13693: 
13694: function toggleTargets(balnum) {
13695:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
13696:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
13697:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
13698:     var prevbalancer = prevhostitem.value;
13699:     var baltotal = document.getElementById('loadbalancing_total').value;
13700:     prevhostitem.value = balancer;
13701:     if (prevbalancer != '') {
13702:         var prevIdx = currBalancers.indexOf(prevbalancer);
13703:         if (prevIdx != -1) {
13704:             currBalancers.splice(prevIdx,1);
13705:         }
13706:     }
13707:     if (balancer == '') {
13708:         hideSpares(balnum);
13709:     } else {
13710:         var currIdx = currBalancers.indexOf(balancer);
13711:         if (currIdx == -1) {
13712:             currBalancers.push(balancer);
13713:         }
13714:         var homedoms = new Array('$allishome');
13715:         var ishomedom = homedoms[lonhostitem.selectedIndex];
13716:         showSpares(balancer,ishomedom,balnum);
13717:     }
13718:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
13719:     return;
13720: }
13721: 
13722: function showSpares(balancer,ishomedom,balnum) {
13723:     var alltargets = new Array('$alltargets');
13724:     var insttypes = new Array('$allinsttypes');
13725:     var offloadtypes = new Array('primary','default');
13726: 
13727:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
13728:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
13729:  
13730:     for (var i=0; i<offloadtypes.length; i++) {
13731:         var count = 0;
13732:         for (var j=0; j<alltargets.length; j++) {
13733:             if (alltargets[j] != balancer) {
13734:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
13735:                 item.value = alltargets[j];
13736:                 item.style.textAlign='left';
13737:                 item.style.textFace='normal';
13738:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
13739:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
13740:                     item.disabled = '';
13741:                 } else {
13742:                     item.disabled = 'disabled';
13743:                     item.checked = false;
13744:                 }
13745:                 count ++;
13746:             }
13747:         }
13748:     }
13749:     for (var k=0; k<insttypes.length; k++) {
13750:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
13751:             if (ishomedom == 1) {
13752:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
13753:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
13754:             } else {
13755:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
13756:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
13757:             }
13758:         } else {
13759:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
13760:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
13761:         }
13762:         if ((insttypes[k] != '_LC_external') && 
13763:             ((insttypes[k] != '_LC_internetdom') ||
13764:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
13765:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
13766:             item.options.length = 0;
13767:             item.options[0] = new Option("","",true,true);
13768:             var idx = 0;
13769:             for (var m=0; m<alltargets.length; m++) {
13770:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
13771:                     idx ++;
13772:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
13773:                 }
13774:             }
13775:         }
13776:     }
13777:     return;
13778: }
13779: 
13780: function hideSpares(balnum) {
13781:     var alltargets = new Array('$alltargets');
13782:     var insttypes = new Array('$allinsttypes');
13783:     var offloadtypes = new Array('primary','default');
13784: 
13785:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
13786:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
13787: 
13788:     var total = alltargets.length - 1;
13789:     for (var i=0; i<offloadtypes; i++) {
13790:         for (var j=0; j<total; j++) {
13791:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
13792:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
13793:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
13794:         }
13795:     }
13796:     for (var k=0; k<insttypes.length; k++) {
13797:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
13798:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
13799:         if (insttypes[k] != '_LC_external') {
13800:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
13801:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
13802:         }
13803:     }
13804:     return;
13805: }
13806: 
13807: function checkOffloads(item,balnum,type) {
13808:     var alltargets = new Array('$alltargets');
13809:     var offloadtypes = new Array('primary','default');
13810:     if (item.checked) {
13811:         var total = alltargets.length - 1;
13812:         var other;
13813:         if (type == offloadtypes[0]) {
13814:             other = offloadtypes[1];
13815:         } else {
13816:             other = offloadtypes[0];
13817:         }
13818:         for (var i=0; i<total; i++) {
13819:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
13820:             if (server == item.value) {
13821:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
13822:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
13823:                 }
13824:             }
13825:         }
13826:     }
13827:     return;
13828: }
13829: 
13830: function singleServerToggle(balnum,type) {
13831:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
13832:     if (offloadtoSelIdx == 0) {
13833:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
13834:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
13835: 
13836:     } else {
13837:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
13838:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
13839:     }
13840:     return;
13841: }
13842: 
13843: function balanceruleChange(formname,balnum,type) {
13844:     if (type == '_LC_external') {
13845:         return;
13846:     }
13847:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
13848:     for (var i=0; i<typesRules.length; i++) {
13849:         if (formname.elements[typesRules[i]].checked) {
13850:             if (formname.elements[typesRules[i]].value != 'specific') {
13851:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
13852:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
13853:             } else {
13854:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
13855:             }
13856:         }
13857:     }
13858:     return;
13859: }
13860: 
13861: function balancerDeleteChange(balnum) {
13862:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
13863:     var baltotal = document.getElementById('loadbalancing_total').value;
13864:     var addtarget;
13865:     var removetarget;
13866:     var action = 'delete';
13867:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
13868:         var lonhost = hostitem.value;
13869:         var currIdx = currBalancers.indexOf(lonhost);
13870:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
13871:             if (currIdx != -1) {
13872:                 currBalancers.splice(currIdx,1);
13873:             }
13874:             addtarget = lonhost;
13875:         } else {
13876:             if (currIdx == -1) {
13877:                 currBalancers.push(lonhost);
13878:             }
13879:             removetarget = lonhost;
13880:             action = 'undelete';
13881:         }
13882:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
13883:     }
13884:     return;
13885: }
13886: 
13887: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
13888:     if (baltotal > 1) {
13889:         var offloadtypes = new Array('primary','default');
13890:         var alltargets = new Array('$alltargets');
13891:         var insttypes = new Array('$allinsttypes');
13892:         for (var i=0; i<baltotal; i++) {
13893:             if (i != balnum) {
13894:                 for (var j=0; j<offloadtypes.length; j++) {
13895:                     var total = alltargets.length - 1;
13896:                     for (var k=0; k<total; k++) {
13897:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
13898:                         var server = serveritem.value;
13899:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
13900:                             if (server == addtarget) {
13901:                                 serveritem.disabled = '';
13902:                             }
13903:                         }
13904:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
13905:                             if (server == removetarget) {
13906:                                 serveritem.disabled = 'disabled';
13907:                                 serveritem.checked = false;
13908:                             }
13909:                         }
13910:                     }
13911:                 }
13912:                 for (var j=0; j<insttypes.length; j++) {
13913:                     if (insttypes[j] != '_LC_external') {
13914:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
13915:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
13916:                             var currSel = singleserver.selectedIndex;
13917:                             var currVal = singleserver.options[currSel].value;
13918:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
13919:                                 var numoptions = singleserver.options.length;
13920:                                 var needsnew = 1;
13921:                                 for (var k=0; k<numoptions; k++) {
13922:                                     if (singleserver.options[k] == addtarget) {
13923:                                         needsnew = 0;
13924:                                         break;
13925:                                     }
13926:                                 }
13927:                                 if (needsnew == 1) {
13928:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
13929:                                 }
13930:                             }
13931:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
13932:                                 singleserver.options.length = 0;
13933:                                 if ((currVal) && (currVal != removetarget)) {
13934:                                     singleserver.options[0] = new Option("","",false,false);
13935:                                 } else {
13936:                                     singleserver.options[0] = new Option("","",true,true);
13937:                                 }
13938:                                 var idx = 0;
13939:                                 for (var m=0; m<alltargets.length; m++) {
13940:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
13941:                                         idx ++;
13942:                                         if (currVal == alltargets[m]) {
13943:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
13944:                                         } else {
13945:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
13946:                                         }
13947:                                     }
13948:                                 }
13949:                             }
13950:                         }
13951:                     }
13952:                 }
13953:             }
13954:         }
13955:     }
13956:     return;
13957: }
13958: 
13959: // ]]>
13960: </script>
13961: 
13962: END
13963: }
13964: 
13965: sub new_spares_js {
13966:     my @sparestypes = ('primary','default');
13967:     my $types = join("','",@sparestypes);
13968:     my $select = &mt('Select');
13969:     return <<"END";
13970: 
13971: <script type="text/javascript">
13972: // <![CDATA[
13973: 
13974: function updateNewSpares(formname,lonhost) {
13975:     var types = new Array('$types');
13976:     var include = new Array();
13977:     var exclude = new Array();
13978:     for (var i=0; i<types.length; i++) {
13979:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
13980:         for (var j=0; j<spareboxes.length; j++) {
13981:             if (formname.elements[spareboxes[j]].checked) {
13982:                 exclude.push(formname.elements[spareboxes[j]].value);
13983:             } else {
13984:                 include.push(formname.elements[spareboxes[j]].value);
13985:             }
13986:         }
13987:     }
13988:     for (var i=0; i<types.length; i++) {
13989:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
13990:         var selIdx = newSpare.selectedIndex;
13991:         var currnew = newSpare.options[selIdx].value;
13992:         var okSpares = new Array();
13993:         for (var j=0; j<newSpare.options.length; j++) {
13994:             var possible = newSpare.options[j].value;
13995:             if (possible != '') {
13996:                 if (exclude.indexOf(possible) == -1) {
13997:                     okSpares.push(possible);
13998:                 } else {
13999:                     if (currnew == possible) {
14000:                         selIdx = 0;
14001:                     }
14002:                 }
14003:             }
14004:         }
14005:         for (var k=0; k<include.length; k++) {
14006:             if (okSpares.indexOf(include[k]) == -1) {
14007:                 okSpares.push(include[k]);
14008:             }
14009:         }
14010:         okSpares.sort();
14011:         newSpare.options.length = 0;
14012:         if (selIdx == 0) {
14013:             newSpare.options[0] = new Option("$select","",true,true);
14014:         } else {
14015:             newSpare.options[0] = new Option("$select","",false,false);
14016:         }
14017:         for (var m=0; m<okSpares.length; m++) {
14018:             var idx = m+1;
14019:             var selThis = 0;
14020:             if (selIdx != 0) {
14021:                 if (okSpares[m] == currnew) {
14022:                     selThis = 1;
14023:                 }
14024:             }
14025:             if (selThis == 1) {
14026:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
14027:             } else {
14028:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
14029:             }
14030:         }
14031:     }
14032:     return;
14033: }
14034: 
14035: function checkNewSpares(lonhost,type) {
14036:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
14037:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
14038:     if (chosen != '') { 
14039:         var othertype;
14040:         var othernewSpare;
14041:         if (type == 'primary') {
14042:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
14043:         }
14044:         if (type == 'default') {
14045:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
14046:         }
14047:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
14048:             othernewSpare.selectedIndex = 0;
14049:         }
14050:     }
14051:     return;
14052: }
14053: 
14054: // ]]>
14055: </script>
14056: 
14057: END
14058: 
14059: }
14060: 
14061: sub common_domprefs_js {
14062:     return <<"END";
14063: 
14064: <script type="text/javascript">
14065: // <![CDATA[
14066: 
14067: function getIndicesByName(formname,item) {
14068:     var group = new Array();
14069:     for (var i=0;i<formname.elements.length;i++) {
14070:         if (formname.elements[i].name == item) {
14071:             group.push(formname.elements[i].id);
14072:         }
14073:     }
14074:     return group;
14075: }
14076: 
14077: // ]]>
14078: </script>
14079: 
14080: END
14081: 
14082: }
14083: 
14084: sub recaptcha_js {
14085:     my %lt = &captcha_phrases();
14086:     return <<"END";
14087: 
14088: <script type="text/javascript">
14089: // <![CDATA[
14090: 
14091: function updateCaptcha(caller,context) {
14092:     var privitem;
14093:     var pubitem;
14094:     var privtext;
14095:     var pubtext;
14096:     var versionitem;
14097:     var versiontext;
14098:     if (document.getElementById(context+'_recaptchapub')) {
14099:         pubitem = document.getElementById(context+'_recaptchapub');
14100:     } else {
14101:         return;
14102:     }
14103:     if (document.getElementById(context+'_recaptchapriv')) {
14104:         privitem = document.getElementById(context+'_recaptchapriv');
14105:     } else {
14106:         return;
14107:     }
14108:     if (document.getElementById(context+'_recaptchapubtxt')) {
14109:         pubtext = document.getElementById(context+'_recaptchapubtxt');
14110:     } else {
14111:         return;
14112:     }
14113:     if (document.getElementById(context+'_recaptchaprivtxt')) {
14114:         privtext = document.getElementById(context+'_recaptchaprivtxt');
14115:     } else {
14116:         return;
14117:     }
14118:     if (document.getElementById(context+'_recaptchaversion')) {
14119:         versionitem = document.getElementById(context+'_recaptchaversion');
14120:     } else {
14121:         return;
14122:     }
14123:     if (document.getElementById(context+'_recaptchavertxt')) {
14124:         versiontext = document.getElementById(context+'_recaptchavertxt');
14125:     } else {
14126:         return;
14127:     }
14128:     if (caller.checked) {
14129:         if (caller.value == 'recaptcha') {
14130:             pubitem.type = 'text';
14131:             privitem.type = 'text';
14132:             pubitem.size = '40';
14133:             privitem.size = '40';
14134:             pubtext.innerHTML = "$lt{'pub'}";
14135:             privtext.innerHTML = "$lt{'priv'}";
14136:             versionitem.type = 'text';
14137:             versionitem.size = '3';
14138:             versiontext.innerHTML = "$lt{'ver'}";
14139:         } else {
14140:             pubitem.type = 'hidden';
14141:             privitem.type = 'hidden';
14142:             versionitem.type = 'hidden';
14143:             pubtext.innerHTML = '';
14144:             privtext.innerHTML = '';
14145:             versiontext.innerHTML = '';
14146:         }
14147:     }
14148:     return;
14149: }
14150: 
14151: // ]]>
14152: </script>
14153: 
14154: END
14155: 
14156: }
14157: 
14158: sub toggle_display_js {
14159:     return <<"END";
14160: 
14161: <script type="text/javascript">
14162: // <![CDATA[
14163: 
14164: function toggleDisplay(domForm,caller) {
14165:     if (document.getElementById(caller)) {
14166:         var divitem = document.getElementById(caller);
14167:         var optionsElement = domForm.coursecredits;
14168:         var checkval = 1;
14169:         var dispval = 'block';
14170:         var selfcreateRegExp = /^cancreate_emailverified/;
14171:         if (caller == 'emailoptions') {
14172:             optionsElement = domForm.cancreate_email; 
14173:         }
14174:         if (caller == 'studentsubmission') {
14175:             optionsElement = domForm.postsubmit;
14176:         }
14177:         if (caller == 'cloneinstcode') {
14178:             optionsElement = domForm.canclone;
14179:             checkval = 'instcode';
14180:         }
14181:         if (selfcreateRegExp.test(caller)) {
14182:             optionsElement = domForm.elements[caller];
14183:             checkval = 'other';
14184:             dispval = 'inline'
14185:         }
14186:         if (optionsElement.length) {
14187:             var currval;
14188:             for (var i=0; i<optionsElement.length; i++) {
14189:                 if (optionsElement[i].checked) {
14190:                    currval = optionsElement[i].value;
14191:                 }
14192:             }
14193:             if (currval == checkval) {
14194:                 divitem.style.display = dispval;
14195:             } else {
14196:                 divitem.style.display = 'none';
14197:             }
14198:         }
14199:     }
14200:     return;
14201: }
14202: 
14203: // ]]>
14204: </script>
14205: 
14206: END
14207: 
14208: }
14209: 
14210: sub captcha_phrases {
14211:     return &Apache::lonlocal::texthash (
14212:                  priv => 'Private key',
14213:                  pub  => 'Public key',
14214:                  original  => 'original (CAPTCHA)',
14215:                  recaptcha => 'successor (ReCAPTCHA)',
14216:                  notused   => 'unused',
14217:                  ver => 'ReCAPTCHA version (1 or 2)',
14218:     );
14219: }
14220: 
14221: sub devalidate_remote_domconfs {
14222:     my ($dom,$cachekeys) = @_;
14223:     return unless (ref($cachekeys) eq 'HASH');
14224:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
14225:     my %thismachine;
14226:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
14227:     my @posscached = ('domainconfig','domdefaults','usersessions','directorysrch','cats');
14228:     if (keys(%servers)) {
14229:         foreach my $server (keys(%servers)) {
14230:             next if ($thismachine{$server});
14231:             my @cached;
14232:             foreach my $name (@posscached) {
14233:                 if ($cachekeys->{$name}) {
14234:                     push(@cached,&escape($name).':'.&escape($dom));
14235:                 }
14236:             }
14237:             if (@cached) {
14238:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
14239:             }
14240:         }
14241:     }
14242:     return;
14243: }
14244: 
14245: 1;

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