File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.160.6.105: download - view: text, annotated - select for diffs
Sat May 2 18:36:17 2020 UTC (4 years, 2 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.160: preferred, unified
- For 2.11
  Backport 1.371

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.160.6.105 2020/05/02 18:36:17 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','passwords'],$dom);
  220:     my @prefs_order = ('rolecolors','login','defaults','passwords','quotas','autoenroll',
  221:                        'autoupdate','autocreate','directorysrch','contacts',
  222:                        'usercreation','selfcreation','usermodification','scantron',
  223:                        'requestcourses','requestauthor','coursecategories',
  224:                        'serverstatuses','helpsettings','coursedefaults',
  225:                        'selfenrollment','usersessions');
  226:     my %existing;
  227:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  228:         %existing = %{$domconfig{'loadbalancing'}};
  229:     }
  230:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  231:         push(@prefs_order,'loadbalancing');
  232:     }
  233:     my %prefs = (
  234:         'rolecolors' =>
  235:                    { text => 'Default color schemes',
  236:                      help => 'Domain_Configuration_Color_Schemes',
  237:                      header => [{col1 => 'Student Settings',
  238:                                  col2 => '',},
  239:                                 {col1 => 'Coordinator Settings',
  240:                                  col2 => '',},
  241:                                 {col1 => 'Author Settings',
  242:                                  col2 => '',},
  243:                                 {col1 => 'Administrator Settings',
  244:                                  col2 => '',}],
  245:                       print => \&print_rolecolors,
  246:                       modify => \&modify_rolecolors,
  247:                     },
  248:         'login' =>
  249:                     { text => 'Log-in page options',
  250:                       help => 'Domain_Configuration_Login_Page',
  251:                       header => [{col1 => 'Log-in Page Items',
  252:                                   col2 => '',},
  253:                                  {col1 => 'Log-in Help',
  254:                                   col2 => 'Value'},
  255:                                  {col1 => 'Custom HTML in document head',
  256:                                   col2 => 'Value'}],
  257:                       print => \&print_login,
  258:                       modify => \&modify_login,
  259:                     },
  260:         'defaults' => 
  261:                     { text => 'Default authentication/language/timezone/portal/types',
  262:                       help => 'Domain_Configuration_LangTZAuth',
  263:                       header => [{col1 => 'Setting',
  264:                                   col2 => 'Value'},
  265:                                  {col1 => 'Institutional user types',
  266:                                   col2 => 'Name displayed'}],
  267:                       print => \&print_defaults,
  268:                       modify => \&modify_defaults,
  269:                     },
  270:         'passwords' =>
  271:                     { text => 'Passwords (Internal authentication)',
  272:                       help => 'Domain_Configuration_Passwords',
  273:                       header => [{col1 => 'Resetting Forgotten Password',
  274:                                   col2 => 'Settings'},
  275:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  276:                                   col2 => 'Settings'},
  277:                                  {col1 => 'Rules for LON-CAPA Passwords',
  278:                                   col2 => 'Settings'},
  279:                                  {col1 => 'Course Owner Changing Student Passwords',
  280:                                   col2 => 'Settings'}],
  281:                       print => \&print_passwords,
  282:                       modify => \&modify_passwords,
  283:                     },
  284:         'quotas' => 
  285:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  286:                       help => 'Domain_Configuration_Quotas',
  287:                       header => [{col1 => 'User affiliation',
  288:                                   col2 => 'Available tools',
  289:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  290:                       print => \&print_quotas,
  291:                       modify => \&modify_quotas,
  292:                     },
  293:         'autoenroll' =>
  294:                    { text => 'Auto-enrollment settings',
  295:                      help => 'Domain_Configuration_Auto_Enrollment',
  296:                      header => [{col1 => 'Configuration setting',
  297:                                  col2 => 'Value(s)'}],
  298:                      print => \&print_autoenroll,
  299:                      modify => \&modify_autoenroll,
  300:                    },
  301:         'autoupdate' => 
  302:                    { text => 'Auto-update settings',
  303:                      help => 'Domain_Configuration_Auto_Updates',
  304:                      header => [{col1 => 'Setting',
  305:                                  col2 => 'Value',},
  306:                                 {col1 => 'Setting',
  307:                                  col2 => 'Affiliation'},
  308:                                 {col1 => 'User population',
  309:                                  col2 => 'Updatable user data'}],
  310:                      print => \&print_autoupdate,
  311:                      modify => \&modify_autoupdate,
  312:                   },
  313:         'autocreate' => 
  314:                   { text => 'Auto-course creation settings',
  315:                      help => 'Domain_Configuration_Auto_Creation',
  316:                      header => [{col1 => 'Configuration Setting',
  317:                                  col2 => 'Value',}],
  318:                      print => \&print_autocreate,
  319:                      modify => \&modify_autocreate,
  320:                   },
  321:         'directorysrch' => 
  322:                   { text => 'Directory searches',
  323:                     help => 'Domain_Configuration_InstDirectory_Search',
  324:                     header => [{col1 => 'Institutional Directory Setting',
  325:                                 col2 => 'Value',},
  326:                                {col1 => 'LON-CAPA Directory Setting',
  327:                                 col2 => 'Value',}],
  328:                     print => \&print_directorysrch,
  329:                     modify => \&modify_directorysrch,
  330:                   },
  331:         'contacts' =>
  332:                   { text => 'E-mail addresses and helpform',
  333:                     help => 'Domain_Configuration_Contact_Info',
  334:                     header => [{col1 => 'Default e-mail addresses',
  335:                                 col2 => 'Value',},
  336:                                {col1 => 'Recipient(s) for notifications',
  337:                                 col2 => 'Value',},
  338:                                {col1 => 'Ask helpdesk form settings',
  339:                                 col2 => 'Value',},],
  340:                     print => \&print_contacts,
  341:                     modify => \&modify_contacts,
  342:                   },
  343:         'usercreation' => 
  344:                   { text => 'User creation',
  345:                     help => 'Domain_Configuration_User_Creation',
  346:                     header => [{col1 => 'Format rule type',
  347:                                 col2 => 'Format rules in force'},
  348:                                {col1 => 'User account creation',
  349:                                 col2 => 'Usernames which may be created',},
  350:                                {col1 => 'Context',
  351:                                 col2 => 'Assignable authentication types'}],
  352:                     print => \&print_usercreation,
  353:                     modify => \&modify_usercreation,
  354:                   },
  355:         'selfcreation' => 
  356:                   { text => 'Users self-creating accounts',
  357:                     help => 'Domain_Configuration_Self_Creation', 
  358:                     header => [{col1 => 'Self-creation with institutional username',
  359:                                 col2 => 'Enabled?'},
  360:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  361:                                 col2 => 'Information user can enter'},
  362:                                {col1 => 'Self-creation with e-mail verification',
  363:                                 col2 => 'Settings'}],
  364:                     print => \&print_selfcreation,
  365:                     modify => \&modify_selfcreation,
  366:                   },
  367:         'usermodification' =>
  368:                   { text => 'User modification',
  369:                     help => 'Domain_Configuration_User_Modification',
  370:                     header => [{col1 => 'Target user has role',
  371:                                 col2 => 'User information updatable in author context'},
  372:                                {col1 => 'Target user has role',
  373:                                 col2 => 'User information updatable in course context'}],
  374:                     print => \&print_usermodification,
  375:                     modify => \&modify_usermodification,
  376:                   },
  377:         'scantron' =>
  378:                   { text => 'Bubblesheet format',
  379:                     help => 'Domain_Configuration_Scantron_Format',
  380:                     header => [ {col1 => 'Bubblesheet format file',
  381:                                  col2 => ''},
  382:                                 {col1 => 'Bubblesheet data upload formats',
  383:                                  col2 => 'Settings'}],
  384:                     print => \&print_scantron,
  385:                     modify => \&modify_scantron,
  386:                   },
  387:         'requestcourses' => 
  388:                  {text => 'Request creation of courses',
  389:                   help => 'Domain_Configuration_Request_Courses',
  390:                   header => [{col1 => 'User affiliation',
  391:                               col2 => 'Availability/Processing of requests',},
  392:                              {col1 => 'Setting',
  393:                               col2 => 'Value'},
  394:                              {col1 => 'Available textbooks',
  395:                               col2 => ''},
  396:                              {col1 => 'Available templates',
  397:                               col2 => ''},
  398:                              {col1 => 'Validation (not official courses)',
  399:                               col2 => 'Value'},],
  400:                   print => \&print_quotas,
  401:                   modify => \&modify_quotas,
  402:                  },
  403:         'requestauthor' =>
  404:                  {text => 'Request Authoring Space',
  405:                   help => 'Domain_Configuration_Request_Author',
  406:                   header => [{col1 => 'User affiliation',
  407:                               col2 => 'Availability/Processing of requests',},
  408:                              {col1 => 'Setting',
  409:                               col2 => 'Value'}],
  410:                   print => \&print_quotas,
  411:                   modify => \&modify_quotas,
  412:                  },
  413:         'coursecategories' =>
  414:                   { text => 'Cataloging of courses/communities',
  415:                     help => 'Domain_Configuration_Cataloging_Courses',
  416:                     header => [{col1 => 'Catalog type/availability',
  417:                                 col2 => '',},
  418:                                {col1 => 'Category settings for standard catalog',
  419:                                 col2 => '',},
  420:                                {col1 => 'Categories',
  421:                                 col2 => '',
  422:                                }],
  423:                     print => \&print_coursecategories,
  424:                     modify => \&modify_coursecategories,
  425:                   },
  426:         'serverstatuses' =>
  427:                  {text   => 'Access to server status pages',
  428:                   help   => 'Domain_Configuration_Server_Status',
  429:                   header => [{col1 => 'Status Page',
  430:                               col2 => 'Other named users',
  431:                               col3 => 'Specific IPs',
  432:                             }],
  433:                   print => \&print_serverstatuses,
  434:                   modify => \&modify_serverstatuses,
  435:                  },
  436:         'helpsettings' =>
  437:                  {text   => 'Support settings',
  438:                   help   => 'Domain_Configuration_Help_Settings',
  439:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  440:                               col2 => 'Value'},
  441:                              {col1 => 'Helpdesk Roles',
  442:                               col2 => 'Settings'},],
  443:                   print  => \&print_helpsettings,
  444:                   modify => \&modify_helpsettings,
  445:                  },
  446:         'coursedefaults' => 
  447:                  {text => 'Course/Community defaults',
  448:                   help => 'Domain_Configuration_Course_Defaults',
  449:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  450:                               col2 => 'Value',},
  451:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  452:                               col2 => 'Value',},],
  453:                   print => \&print_coursedefaults,
  454:                   modify => \&modify_coursedefaults,
  455:                  },
  456:         'selfenrollment' => 
  457:                  {text   => 'Self-enrollment in Course/Community',
  458:                   help   => 'Domain_Configuration_Selfenrollment',
  459:                   header => [{col1 => 'Configuration Rights',
  460:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  461:                              {col1 => 'Defaults',
  462:                               col2 => 'Value'},
  463:                              {col1 => 'Self-enrollment validation (optional)',
  464:                               col2 => 'Value'},],
  465:                   print => \&print_selfenrollment,
  466:                   modify => \&modify_selfenrollment,
  467:                  },
  468:         'usersessions' =>
  469:                  {text  => 'User session hosting/offloading',
  470:                   help  => 'Domain_Configuration_User_Sessions',
  471:                   header => [{col1 => 'Domain server',
  472:                               col2 => 'Servers to offload sessions to when busy'},
  473:                              {col1 => 'Hosting of users from other domains',
  474:                               col2 => 'Rules'},
  475:                              {col1 => "Hosting domain's own users elsewhere",
  476:                               col2 => 'Rules'}],
  477:                   print => \&print_usersessions,
  478:                   modify => \&modify_usersessions,
  479:                  },
  480:         'loadbalancing' =>
  481:                  {text  => 'Dedicated Load Balancer(s)',
  482:                   help  => 'Domain_Configuration_Load_Balancing',
  483:                   header => [{col1 => 'Balancers',
  484:                               col2 => 'Default destinations',
  485:                               col3 => 'User affiliation',
  486:                               col4 => 'Overrides'},
  487:                             ],
  488:                   print => \&print_loadbalancing,
  489:                   modify => \&modify_loadbalancing,
  490:                  },
  491:     );
  492:     if (keys(%servers) > 1) {
  493:         $prefs{'login'}  = { text   => 'Log-in page options',
  494:                              help   => 'Domain_Configuration_Login_Page',
  495:                             header => [{col1 => 'Log-in Service',
  496:                                         col2 => 'Server Setting',},
  497:                                        {col1 => 'Log-in Page Items',
  498:                                         col2 => ''},
  499:                                        {col1 => 'Log-in Help',
  500:                                         col2 => 'Value'},
  501:                                        {col1 => 'Custom HTML in document head',
  502:                                         col2 => 'Value'}],
  503:                             print => \&print_login,
  504:                             modify => \&modify_login,
  505:                            };
  506:     }
  507: 
  508:     my @roles = ('student','coordinator','author','admin');
  509:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  510:     &Apache::lonhtmlcommon::add_breadcrumb
  511:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  512:       text=>"Settings to display/modify"});
  513:     my $confname = $dom.'-domainconfig';
  514: 
  515:     if ($phase eq 'process') {
  516:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  517:                                                               \%prefs,\%domconfig,$confname,\@roles);
  518:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  519:             $r->rflush();
  520:             &devalidate_remote_domconfs($dom,$result);
  521:         }
  522:     } elsif ($phase eq 'display') {
  523:         my $js = &recaptcha_js().
  524:                  &toggle_display_js();
  525:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  526:             my ($othertitle,$usertypes,$types) =
  527:                 &Apache::loncommon::sorted_inst_types($dom);
  528:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  529:                                           $domconfig{'loadbalancing'}).
  530:                    &new_spares_js().
  531:                    &common_domprefs_js().
  532:                    &Apache::loncommon::javascript_array_indexof();
  533:         }
  534:         if (grep(/^requestcourses$/,@actions)) {
  535:             my $javascript_validations;
  536:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  537:             $js .= <<END;
  538: <script type="text/javascript">
  539: $javascript_validations
  540: </script>
  541: $coursebrowserjs
  542: END
  543:         }
  544:         if (grep(/^selfcreation$/,@actions)) {
  545:             $js .= &selfcreate_javascript();
  546:         }
  547:         if (grep(/^contacts$/,@actions)) {
  548:             $js .= &contacts_javascript();
  549:         }
  550:         if (grep(/^scantron$/,@actions)) {
  551:             $js .= &scantron_javascript();
  552:         }
  553:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  554:     } else {
  555: # check if domconfig user exists for the domain.
  556:         my $servadm = $r->dir_config('lonAdmEMail');
  557:         my ($configuserok,$author_ok,$switchserver) =
  558:             &config_check($dom,$confname,$servadm);
  559:         unless ($configuserok eq 'ok') {
  560:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  561:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  562:                           $confname).
  563:                       '<br />'
  564:             );
  565:             if ($switchserver) {
  566:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  567:                           '<br />'.
  568:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  569:                           '<br />'.
  570:                           &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).
  571:                           '<br />'.
  572:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  573:                 );
  574:             } else {
  575:                 $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.').
  576:                           '<br />'.
  577:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  578:                 );
  579:             }
  580:             $r->print(&Apache::loncommon::end_page());
  581:             return OK;
  582:         }
  583:         if (keys(%domconfig) == 0) {
  584:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  585:             my @ids=&Apache::lonnet::current_machine_ids();
  586:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  587:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  588:                 my @loginimages = ('img','logo','domlogo','login');
  589:                 my $custom_img_count = 0;
  590:                 foreach my $img (@loginimages) {
  591:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  592:                         $custom_img_count ++;
  593:                     }
  594:                 }
  595:                 foreach my $role (@roles) {
  596:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  597:                         $custom_img_count ++;
  598:                     }
  599:                 }
  600:                 if ($custom_img_count > 0) {
  601:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  602:                     my $switch_server = &check_switchserver($dom,$confname);
  603:                     $r->print(
  604:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  605:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  606:     &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 />'.
  607:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  608:                     if ($switch_server) {
  609:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  610:                     }
  611:                     $r->print(&Apache::loncommon::end_page());
  612:                     return OK;
  613:                 }
  614:             }
  615:         }
  616:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  617:     }
  618:     return OK;
  619: }
  620: 
  621: sub process_changes {
  622:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  623:     my %domconfig;
  624:     if (ref($values) eq 'HASH') {
  625:         %domconfig = %{$values};
  626:     }
  627:     my $output;
  628:     if ($action eq 'login') {
  629:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  630:     } elsif ($action eq 'rolecolors') {
  631:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  632:                                      $lastactref,%domconfig);
  633:     } elsif ($action eq 'quotas') {
  634:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  635:     } elsif ($action eq 'autoenroll') {
  636:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  637:     } elsif ($action eq 'autoupdate') {
  638:         $output = &modify_autoupdate($dom,%domconfig);
  639:     } elsif ($action eq 'autocreate') {
  640:         $output = &modify_autocreate($dom,%domconfig);
  641:     } elsif ($action eq 'directorysrch') {
  642:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  643:     } elsif ($action eq 'usercreation') {
  644:         $output = &modify_usercreation($dom,%domconfig);
  645:     } elsif ($action eq 'selfcreation') {
  646:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  647:     } elsif ($action eq 'usermodification') {
  648:         $output = &modify_usermodification($dom,%domconfig);
  649:     } elsif ($action eq 'contacts') {
  650:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  651:     } elsif ($action eq 'defaults') {
  652:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  653:     } elsif ($action eq 'scantron') {
  654:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  655:     } elsif ($action eq 'coursecategories') {
  656:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  657:     } elsif ($action eq 'serverstatuses') {
  658:         $output = &modify_serverstatuses($dom,%domconfig);
  659:     } elsif ($action eq 'requestcourses') {
  660:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  661:     } elsif ($action eq 'requestauthor') {
  662:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  663:     } elsif ($action eq 'helpsettings') {
  664:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  665:     } elsif ($action eq 'coursedefaults') {
  666:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  667:     } elsif ($action eq 'selfenrollment') {
  668:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  669:     } elsif ($action eq 'usersessions') {
  670:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  671:     } elsif ($action eq 'loadbalancing') {
  672:         $output = &modify_loadbalancing($dom,%domconfig);
  673:     } elsif ($action eq 'passwords') {
  674:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  675:     }
  676:     return $output;
  677: }
  678: 
  679: sub print_config_box {
  680:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  681:     my $rowtotal = 0;
  682:     my $output;
  683:     if ($action eq 'coursecategories') {
  684:         $output = &coursecategories_javascript($settings);
  685:     } elsif ($action eq 'defaults') {
  686:         $output = &defaults_javascript($settings); 
  687:     } elsif ($action eq 'passwords') {
  688:         $output = &passwords_javascript();
  689:     } elsif ($action eq 'helpsettings') {
  690:         my (%privs,%levelscurrent);
  691:         my %full=();
  692:         my %levels=(
  693:                      course => {},
  694:                      domain => {},
  695:                      system => {},
  696:                    );
  697:         my $context = 'domain';
  698:         my $crstype = 'Course';
  699:         my $formname = 'display';
  700:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  701:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  702:         $output =
  703:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full,
  704:                                                       \@templateroles);
  705:     }
  706:     $output .=
  707:          '<table class="LC_nested_outer">
  708:           <tr>
  709:            <th align="left" valign="middle"><span class="LC_nobreak">'.
  710:            &mt($item->{text}).'&nbsp;'.
  711:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  712:           '</tr>';
  713:     $rowtotal ++;
  714:     my $numheaders = 1;
  715:     if (ref($item->{'header'}) eq 'ARRAY') {
  716:         $numheaders = scalar(@{$item->{'header'}});
  717:     }
  718:     if ($numheaders > 1) {
  719:         my $colspan = '';
  720:         my $rightcolspan = '';
  721:         my $leftnobr = '';  
  722:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  723:             ($action eq 'directorysrch') ||
  724:             (($action eq 'login') && ($numheaders < 4))) {
  725:             $colspan = ' colspan="2"';
  726:         }
  727:         if ($action eq 'usersessions') {
  728:             $rightcolspan = ' colspan="3"'; 
  729:         }
  730:         if ($action eq 'passwords') {
  731:             $leftnobr = ' LC_nobreak';
  732:         }
  733:         $output .= '
  734:           <tr>
  735:            <td>
  736:             <table class="LC_nested">
  737:              <tr class="LC_info_row">
  738:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  739:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  740:              </tr>';
  741:         $rowtotal ++;
  742:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  743:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  744:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'directorysrch') ||
  745:             ($action eq 'helpsettings') || ($action eq 'contacts')) {
  746:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  747:         } elsif ($action eq 'passwords') {
  748:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  749:         } elsif ($action eq 'coursecategories') {
  750:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  751:         } elsif ($action eq 'scantron') {
  752:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  753:         } elsif ($action eq 'login') {
  754:             if ($numheaders == 4) {
  755:                 $colspan = ' colspan="2"';
  756:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  757:             } else {
  758:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  759:             }
  760:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  761:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  762:         } elsif ($action eq 'rolecolors') {
  763:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  764:         }
  765:         $output .= '
  766:            </table>
  767:           </td>
  768:          </tr>
  769:          <tr>
  770:            <td>
  771:             <table class="LC_nested">
  772:              <tr class="LC_info_row">
  773:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  774:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  775:              </tr>';
  776:             $rowtotal ++;
  777:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  778:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  779:             ($action eq 'usersessions') || ($action eq 'coursecategories') ||
  780:             ($action eq 'contacts') || ($action eq 'passwords')) {
  781:             if ($action eq 'coursecategories') {
  782:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  783:                 $colspan = ' colspan="2"';
  784:             } elsif ($action eq 'passwords') {
  785:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
  786:             } else {
  787:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  788:             }
  789:             $output .= '
  790:            </table>
  791:           </td>
  792:          </tr>
  793:          <tr>
  794:            <td>
  795:             <table class="LC_nested">
  796:              <tr class="LC_info_row">
  797:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  798:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  799:              </tr>'."\n";
  800:             if ($action eq 'coursecategories') {
  801:                 $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
  802:             } elsif ($action eq 'passwords') {
  803:                 $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal).'
  804:              </tr>
  805:             </table>
  806:            </td>
  807:           </tr>
  808:           <tr>
  809:            <td>
  810:             <table class="LC_nested">
  811:              <tr class="LC_info_row">
  812:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  813:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n".
  814:               $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal).'
  815:             </table>
  816:           </td>
  817:          </tr>
  818:          <tr>';
  819:             } else {
  820:                 $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  821:             }
  822:             $rowtotal ++;
  823:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
  824:                  ($action eq 'defaults') || ($action eq 'directorysrch') ||
  825:                  ($action eq 'helpsettings')) {
  826:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  827:         } elsif ($action eq 'scantron') {
  828:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
  829:         } elsif ($action eq 'login') {
  830:             if ($numheaders == 4) {
  831:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
  832:            </table>
  833:           </td>
  834:          </tr>
  835:          <tr>
  836:            <td>
  837:             <table class="LC_nested">
  838:              <tr class="LC_info_row">
  839:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  840:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
  841:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  842:                 $rowtotal ++;
  843:             } else {
  844:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
  845:             }
  846:             $output .= '
  847:            </table>
  848:           </td>
  849:          </tr>
  850:          <tr>
  851:            <td>
  852:             <table class="LC_nested">
  853:              <tr class="LC_info_row">';
  854:             if ($numheaders == 4) {
  855:                 $output .= '
  856:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  857:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  858:              </tr>';
  859:             } else {
  860:                 $output .= '
  861:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  862:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  863:              </tr>';
  864:             }
  865:             $rowtotal ++;
  866:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal);
  867:         } elsif ($action eq 'requestcourses') {
  868:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
  869:             $rowtotal ++;
  870:             $output .= &print_studentcode($settings,\$rowtotal).'
  871:            </table>
  872:           </td>
  873:          </tr>
  874:          <tr>
  875:            <td>
  876:             <table class="LC_nested">
  877:              <tr class="LC_info_row">
  878:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  879:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
  880:                        &textbookcourses_javascript($settings).
  881:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
  882:             </table>
  883:            </td>
  884:           </tr>
  885:          <tr>
  886:            <td>
  887:             <table class="LC_nested">
  888:              <tr class="LC_info_row">
  889:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  890:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
  891:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
  892:             </table>
  893:            </td>
  894:           </tr>
  895:           <tr>
  896:            <td>
  897:             <table class="LC_nested">
  898:              <tr class="LC_info_row">
  899:               <td class="LC_left_item"'.$colspan.' valign="top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
  900:               <td class="LC_right_item" valign="top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
  901:              </tr>'.
  902:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
  903:         } elsif ($action eq 'requestauthor') {
  904:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
  905:             $rowtotal ++;
  906:         } elsif ($action eq 'rolecolors') {
  907:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
  908:            </table>
  909:           </td>
  910:          </tr>
  911:          <tr>
  912:            <td>
  913:             <table class="LC_nested">
  914:              <tr class="LC_info_row">
  915:               <td class="LC_left_item"'.$colspan.' valign="top">'.
  916:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
  917:               <td class="LC_right_item" valign="top">'.
  918:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
  919:              </tr>'.
  920:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
  921:            </table>
  922:           </td>
  923:          </tr>
  924:          <tr>
  925:            <td>
  926:             <table class="LC_nested">
  927:              <tr class="LC_info_row">
  928:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  929:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
  930:              </tr>'.
  931:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
  932:             $rowtotal += 2;
  933:         }
  934:     } else {
  935:         $output .= '
  936:           <tr>
  937:            <td>
  938:             <table class="LC_nested">
  939:              <tr class="LC_info_row">';
  940:         if ($action eq 'login') {
  941:             $output .= '  
  942:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
  943:         } elsif ($action eq 'serverstatuses') {
  944:             $output .= '
  945:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).
  946:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
  947: 
  948:         } else {
  949:             $output .= '
  950:               <td class="LC_left_item" valign="top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
  951:         }
  952:         if (defined($item->{'header'}->[0]->{'col3'})) {
  953:             $output .= '<td class="LC_left_item" valign="top">'.
  954:                        &mt($item->{'header'}->[0]->{'col2'});
  955:             if ($action eq 'serverstatuses') {
  956:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
  957:             } 
  958:         } else {
  959:             $output .= '<td class="LC_right_item" valign="top">'.
  960:                        &mt($item->{'header'}->[0]->{'col2'});
  961:         }
  962:         $output .= '</td>';
  963:         if ($item->{'header'}->[0]->{'col3'}) {
  964:             if (defined($item->{'header'}->[0]->{'col4'})) {
  965:                 $output .= '<td class="LC_left_item" valign="top">'.
  966:                             &mt($item->{'header'}->[0]->{'col3'});
  967:             } else {
  968:                 $output .= '<td class="LC_right_item" valign="top">'.
  969:                            &mt($item->{'header'}->[0]->{'col3'});
  970:             }
  971:             if ($action eq 'serverstatuses') {
  972:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
  973:             }
  974:             $output .= '</td>';
  975:         }
  976:         if ($item->{'header'}->[0]->{'col4'}) {
  977:             $output .= '<td class="LC_right_item" valign="top">'.
  978:                        &mt($item->{'header'}->[0]->{'col4'});
  979:         }
  980:         $output .= '</tr>';
  981:         $rowtotal ++;
  982:         if ($action eq 'quotas') {
  983:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  984:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
  985:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing')) {
  986:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
  987:         }
  988:     }
  989:     $output .= '
  990:    </table>
  991:   </td>
  992:  </tr>
  993: </table><br />';
  994:     return ($output,$rowtotal);
  995: }
  996: 
  997: sub print_login {
  998:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
  999:     my ($css_class,$datatable);
 1000:     my %choices = &login_choices();
 1001: 
 1002:     if ($caller eq 'service') {
 1003:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1004:         my $choice = $choices{'disallowlogin'};
 1005:         $css_class = ' class="LC_odd_row"';
 1006:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1007:                       '<td align="right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1008:                       '<th>'.$choices{'server'}.'</th>'.
 1009:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1010:                       '<th>'.$choices{'custompath'}.'</th>'.
 1011:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1012:         my %disallowed;
 1013:         if (ref($settings) eq 'HASH') {
 1014:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1015:                %disallowed = %{$settings->{'loginvia'}};
 1016:             }
 1017:         }
 1018:         foreach my $lonhost (sort(keys(%servers))) {
 1019:             my $direct = 'selected="selected"';
 1020:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1021:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1022:                     $direct = '';
 1023:                 }
 1024:             }
 1025:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1026:                           '<td><select name="'.$lonhost.'_server">'.
 1027:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1028:                           '</option>';
 1029:             foreach my $hostid (sort(keys(%servers))) {
 1030:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1031:                 my $selected = '';
 1032:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1033:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1034:                         $selected = 'selected="selected"';
 1035:                     }
 1036:                 }
 1037:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1038:                               $servers{$hostid}.'</option>';
 1039:             }
 1040:             $datatable .= '</select></td>'.
 1041:                           '<td><select name="'.$lonhost.'_serverpath">';
 1042:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1043:                 my $pathname = $path;
 1044:                 if ($path eq 'custom') {
 1045:                     $pathname = &mt('Custom Path').' ->';
 1046:                 }
 1047:                 my $selected = '';
 1048:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1049:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1050:                         $selected = 'selected="selected"';
 1051:                     }
 1052:                 } elsif ($path eq '') {
 1053:                     $selected = 'selected="selected"';
 1054:                 }
 1055:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1056:             }
 1057:             $datatable .= '</select></td>';
 1058:             my ($custom,$exempt);
 1059:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1060:                 $custom = $disallowed{$lonhost}{'custompath'};
 1061:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1062:             }
 1063:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1064:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1065:                           '</tr>';
 1066:         }
 1067:         $datatable .= '</table></td></tr>';
 1068:         return $datatable;
 1069:     } elsif ($caller eq 'page') {
 1070:         my %defaultchecked = ( 
 1071:                                'coursecatalog' => 'on',
 1072:                                'helpdesk'      => 'on',
 1073:                                'adminmail'     => 'off',
 1074:                                'newuser'       => 'off',
 1075:                              );
 1076:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1077:         my (%checkedon,%checkedoff);
 1078:         foreach my $item (@toggles) {
 1079:             if ($defaultchecked{$item} eq 'on') { 
 1080:                 $checkedon{$item} = ' checked="checked" ';
 1081:                 $checkedoff{$item} = ' ';
 1082:             } elsif ($defaultchecked{$item} eq 'off') {
 1083:                 $checkedoff{$item} = ' checked="checked" ';
 1084:                 $checkedon{$item} = ' ';
 1085:             }
 1086:         }
 1087:         my @images = ('img','logo','domlogo','login');
 1088:         my @logintext = ('textcol','bgcol');
 1089:         my @bgs = ('pgbg','mainbg','sidebg');
 1090:         my @links = ('link','alink','vlink');
 1091:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1092:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1093:         my (%is_custom,%designs);
 1094:         my %defaults = (
 1095:                        font => $defaultdesign{'login.font'},
 1096:                        );
 1097:         foreach my $item (@images) {
 1098:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1099:             $defaults{'showlogo'}{$item} = 1;
 1100:         }
 1101:         foreach my $item (@bgs) {
 1102:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1103:         }
 1104:         foreach my $item (@logintext) {
 1105:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1106:         }
 1107:         foreach my $item (@links) {
 1108:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1109:         }
 1110:         if (ref($settings) eq 'HASH') {
 1111:             foreach my $item (@toggles) {
 1112:                 if ($settings->{$item} eq '1') {
 1113:                     $checkedon{$item} =  ' checked="checked" ';
 1114:                     $checkedoff{$item} = ' ';
 1115:                 } elsif ($settings->{$item} eq '0') {
 1116:                     $checkedoff{$item} =  ' checked="checked" ';
 1117:                     $checkedon{$item} = ' ';
 1118:                 }
 1119:             }
 1120:             foreach my $item (@images) {
 1121:                 if (defined($settings->{$item})) {
 1122:                     $designs{$item} = $settings->{$item};
 1123:                     $is_custom{$item} = 1;
 1124:                 }
 1125:                 if (defined($settings->{'showlogo'}{$item})) {
 1126:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1127:                 }
 1128:             }
 1129:             foreach my $item (@logintext) {
 1130:                 if ($settings->{$item} ne '') {
 1131:                     $designs{'logintext'}{$item} = $settings->{$item};
 1132:                     $is_custom{$item} = 1;
 1133:                 }
 1134:             }
 1135:             if ($settings->{'font'} ne '') {
 1136:                 $designs{'font'} = $settings->{'font'};
 1137:                 $is_custom{'font'} = 1;
 1138:             }
 1139:             foreach my $item (@bgs) {
 1140:                 if ($settings->{$item} ne '') {
 1141:                     $designs{'bgs'}{$item} = $settings->{$item};
 1142:                     $is_custom{$item} = 1;
 1143:                 }
 1144:             }
 1145:             foreach my $item (@links) {
 1146:                 if ($settings->{$item} ne '') {
 1147:                     $designs{'links'}{$item} = $settings->{$item};
 1148:                     $is_custom{$item} = 1;
 1149:                 }
 1150:             }
 1151:         } else {
 1152:             if ($designhash{$dom.'.login.font'} ne '') {
 1153:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1154:                 $is_custom{'font'} = 1;
 1155:             }
 1156:             foreach my $item (@images) {
 1157:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1158:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1159:                     $is_custom{$item} = 1;
 1160:                 }
 1161:             }
 1162:             foreach my $item (@bgs) {
 1163:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1164:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1165:                     $is_custom{$item} = 1;
 1166:                 }
 1167:             }
 1168:             foreach my $item (@links) {
 1169:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1170:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1171:                     $is_custom{$item} = 1;
 1172:                 }
 1173:             }
 1174:         }
 1175:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1176:                                                       logo => 'Institution Logo',
 1177:                                                       domlogo => 'Domain Logo',
 1178:                                                       login => 'Login box');
 1179:         my $itemcount = 1;
 1180:         foreach my $item (@toggles) {
 1181:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1182:             $datatable .=  
 1183:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1184:                 '</td><td>'.
 1185:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1186:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1187:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1188:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1189:                 '</tr>';
 1190:             $itemcount ++;
 1191:         }
 1192:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1193:         $datatable .= '</tr></table></td></tr>';
 1194:     } elsif ($caller eq 'help') {
 1195:         my ($defaulturl,$defaulttype,%url,%type,%lt,%langchoices);
 1196:         my $switchserver = &check_switchserver($dom,$confname);
 1197:         my $itemcount = 1;
 1198:         $defaulturl = '/adm/loginproblems.html';
 1199:         $defaulttype = 'default';
 1200:         %lt = &Apache::lonlocal::texthash (
 1201:                      del     => 'Delete?',
 1202:                      rep     => 'Replace:',
 1203:                      upl     => 'Upload:',
 1204:                      default => 'Default',
 1205:                      custom  => 'Custom',
 1206:                                              );
 1207:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1208:         my @currlangs;
 1209:         if (ref($settings) eq 'HASH') {
 1210:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1211:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1212:                     next if ($settings->{'helpurl'}{$key} eq '');
 1213:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1214:                     $type{$key} = 'custom';
 1215:                     unless ($key eq 'nolang') {
 1216:                         push(@currlangs,$key);
 1217:                     }
 1218:                 }
 1219:             } elsif ($settings->{'helpurl'} ne '') {
 1220:                 $type{'nolang'} = 'custom';
 1221:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1222:             }
 1223:         }
 1224:         foreach my $lang ('nolang',sort(@currlangs)) {
 1225:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1226:             $datatable .= '<tr'.$css_class.'>';
 1227:             if ($url{$lang} eq '') {
 1228:                 $url{$lang} = $defaulturl;
 1229:             }
 1230:             if ($type{$lang} eq '') {
 1231:                 $type{$lang} = $defaulttype;
 1232:             }
 1233:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1234:             if ($lang eq 'nolang') {
 1235:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1236:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1237:             } else {
 1238:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1239:                                   $langchoices{$lang},
 1240:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1241:             }
 1242:             $datatable .= '</span></td>'."\n".
 1243:                           '<td class="LC_left_item">';
 1244:             if ($type{$lang} eq 'custom') {
 1245:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1246:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1247:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1248:             } else {
 1249:                 $datatable .= $lt{'upl'};
 1250:             }
 1251:             $datatable .='<br />';
 1252:             if ($switchserver) {
 1253:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1254:             } else {
 1255:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1256:             }
 1257:             $datatable .= '</td></tr>';
 1258:             $itemcount ++;
 1259:         }
 1260:         my @addlangs;
 1261:         foreach my $lang (sort(keys(%langchoices))) {
 1262:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1263:             push(@addlangs,$lang);
 1264:         }
 1265:         if (@addlangs > 0) {
 1266:             my %toadd;
 1267:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1268:             $toadd{''} = &mt('Select');
 1269:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1270:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1271:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1272:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1273:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1274:             if ($switchserver) {
 1275:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1276:             } else {
 1277:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1278:             }
 1279:             $datatable .= '</td></tr>';
 1280:             $itemcount ++;
 1281:         }
 1282:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1283:     } elsif ($caller eq 'headtag') {
 1284:         my %domservers = &Apache::lonnet::get_servers($dom);
 1285:         my $choice = $choices{'headtag'};
 1286:         $css_class = ' class="LC_odd_row"';
 1287:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1288:                       '<td align="left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1289:                       '<th>'.$choices{'current'}.'</th>'.
 1290:                       '<th>'.$choices{'action'}.'</th>'.
 1291:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1292:         my (%currurls,%currexempt);
 1293:         if (ref($settings) eq 'HASH') {
 1294:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1295:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1296:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1297:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1298:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1299:                     }
 1300:                 }
 1301:             }
 1302:         }
 1303:         my %lt = &Apache::lonlocal::texthash(
 1304:                                                del  => 'Delete?',
 1305:                                                rep  => 'Replace:',
 1306:                                                upl  => 'Upload:',
 1307:                                                curr => 'View contents',
 1308:                                                none => 'None',
 1309:         );
 1310:         my $switchserver = &check_switchserver($dom,$confname);
 1311:         foreach my $lonhost (sort(keys(%domservers))) {
 1312:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1313:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1314:             if ($currurls{$lonhost}) {
 1315:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1316:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1317:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1318:                               '">'.$lt{'curr'}.'</a></td>'.
 1319:                               '<td><span class="LC_nobreak"><label>'.
 1320:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1321:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1322:             } else {
 1323:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1324:             }
 1325:             $datatable .='<br />';
 1326:             if ($switchserver) {
 1327:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1328:             } else {
 1329:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1330:             }
 1331:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1332:         }
 1333:         $datatable .= '</table></td></tr>';
 1334:     }
 1335:     return $datatable;
 1336: }
 1337: 
 1338: sub login_choices {
 1339:     my %choices =
 1340:         &Apache::lonlocal::texthash (
 1341:             coursecatalog => 'Display Course/Community Catalog link?',
 1342:             adminmail     => "Display Administrator's E-mail Address?",
 1343:             helpdesk      => 'Display "Contact Helpdesk" link',
 1344:             disallowlogin => "Login page requests redirected",
 1345:             hostid        => "Server",
 1346:             server        => "Redirect to:",
 1347:             serverpath    => "Path",
 1348:             custompath    => "Custom", 
 1349:             exempt        => "Exempt IP(s)",
 1350:             directlogin   => "No redirect",
 1351:             newuser       => "Link to create a user account",
 1352:             img           => "Header",
 1353:             logo          => "Main Logo",
 1354:             domlogo       => "Domain Logo",
 1355:             login         => "Log-in Header", 
 1356:             textcol       => "Text color",
 1357:             bgcol         => "Box color",
 1358:             bgs           => "Background colors",
 1359:             links         => "Link colors",
 1360:             font          => "Font color",
 1361:             pgbg          => "Header",
 1362:             mainbg        => "Page",
 1363:             sidebg        => "Login box",
 1364:             link          => "Link",
 1365:             alink         => "Active link",
 1366:             vlink         => "Visited link",
 1367:             headtag       => "Custom markup",
 1368:             action        => "Action",
 1369:             current       => "Current",
 1370:         );
 1371:     return %choices;
 1372: }
 1373: 
 1374: sub print_rolecolors {
 1375:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1376:     my %choices = &color_font_choices();
 1377:     my @bgs = ('pgbg','tabbg','sidebg');
 1378:     my @links = ('link','alink','vlink');
 1379:     my @images = ('img');
 1380:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1381:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1382:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1383:     my (%is_custom,%designs);
 1384:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1385:     if (ref($settings) eq 'HASH') {
 1386:         if (ref($settings->{$role}) eq 'HASH') {
 1387:             if ($settings->{$role}->{'img'} ne '') {
 1388:                 $designs{'img'} = $settings->{$role}->{'img'};
 1389:                 $is_custom{'img'} = 1;
 1390:             }
 1391:             if ($settings->{$role}->{'font'} ne '') {
 1392:                 $designs{'font'} = $settings->{$role}->{'font'};
 1393:                 $is_custom{'font'} = 1;
 1394:             }
 1395:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1396:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1397:                 $is_custom{'fontmenu'} = 1;
 1398:             }
 1399:             foreach my $item (@bgs) {
 1400:                 if ($settings->{$role}->{$item} ne '') {
 1401:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1402:                     $is_custom{$item} = 1;
 1403:                 }
 1404:             }
 1405:             foreach my $item (@links) {
 1406:                 if ($settings->{$role}->{$item} ne '') {
 1407:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1408:                     $is_custom{$item} = 1;
 1409:                 }
 1410:             }
 1411:         }
 1412:     } else {
 1413:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1414:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1415:             $is_custom{'img'} = 1;
 1416:         }
 1417:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1418:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1419:             $is_custom{'fontmenu'} = 1; 
 1420:         }
 1421:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1422:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1423:             $is_custom{'font'} = 1;
 1424:         }
 1425:         foreach my $item (@bgs) {
 1426:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1427:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1428:                 $is_custom{$item} = 1;
 1429:             
 1430:             }
 1431:         }
 1432:         foreach my $item (@links) {
 1433:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1434:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1435:                 $is_custom{$item} = 1;
 1436:             }
 1437:         }
 1438:     }
 1439:     my $itemcount = 1;
 1440:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 1441:     $datatable .= '</tr></table></td></tr>';
 1442:     return $datatable;
 1443: }
 1444: 
 1445: sub role_defaults {
 1446:     my ($role,$bgs,$links,$images,$logintext) = @_;
 1447:     my %defaults;
 1448:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 1449:         return %defaults;
 1450:     }
 1451:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1452:     if ($role eq 'login') {
 1453:         %defaults = (
 1454:                        font => $defaultdesign{$role.'.font'},
 1455:                     );
 1456:         if (ref($logintext) eq 'ARRAY') {
 1457:             foreach my $item (@{$logintext}) {
 1458:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 1459:             }
 1460:         }
 1461:         foreach my $item (@{$images}) {
 1462:             $defaults{'showlogo'}{$item} = 1;
 1463:         }
 1464:     } else {
 1465:         %defaults = (
 1466:                        img => $defaultdesign{$role.'.img'},
 1467:                        font => $defaultdesign{$role.'.font'},
 1468:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 1469:                     );
 1470:     }
 1471:     foreach my $item (@{$bgs}) {
 1472:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 1473:     }
 1474:     foreach my $item (@{$links}) {
 1475:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 1476:     }
 1477:     foreach my $item (@{$images}) {
 1478:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 1479:     }
 1480:     return %defaults;
 1481: }
 1482: 
 1483: sub display_color_options {
 1484:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 1485:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 1486:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1487:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1488:     my $datatable = '<tr'.$css_class.'>'.
 1489:         '<td>'.$choices->{'font'}.'</td>';
 1490:     if (!$is_custom->{'font'}) {
 1491:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 1492:     } else {
 1493:         $datatable .= '<td>&nbsp;</td>';
 1494:     }
 1495:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 1496: 
 1497:     $datatable .= '<td><span class="LC_nobreak">'.
 1498:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 1499:                   ' value="'.$current_color.'" />&nbsp;'.
 1500:                   '&nbsp;</span></td></tr>';
 1501:     unless ($role eq 'login') { 
 1502:         $datatable .= '<tr'.$css_class.'>'.
 1503:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 1504:         if (!$is_custom->{'fontmenu'}) {
 1505:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 1506:         } else {
 1507:             $datatable .= '<td>&nbsp;</td>';
 1508:         }
 1509: 	$current_color = $designs->{'fontmenu'} ?
 1510: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 1511:         $datatable .= '<td><span class="LC_nobreak">'.
 1512:                       '<input class="colorchooser" type="text" size="10" name="'
 1513: 		      .$role.'_fontmenu"'.
 1514:                       ' value="'.$current_color.'" />&nbsp;'.
 1515:                       '&nbsp;</span></td></tr>';
 1516:     }
 1517:     my $switchserver = &check_switchserver($dom,$confname);
 1518:     foreach my $img (@{$images}) {
 1519: 	$itemcount ++;
 1520:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1521:         $datatable .= '<tr'.$css_class.'>'.
 1522:                       '<td>'.$choices->{$img};
 1523:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors);
 1524:         if ($role eq 'login') {
 1525:             if ($img eq 'login') {
 1526:                 $login_hdr_pick =
 1527:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 1528:                 $logincolors =
 1529:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 1530:                                        $designs,$defaults);
 1531:             } elsif ($img ne 'domlogo') {
 1532:                 $datatable.= &logo_display_options($img,$defaults,$designs);
 1533:             }
 1534:         }
 1535:         $datatable .= '</td>';
 1536:         if ($designs->{$img} ne '') {
 1537:             $imgfile = $designs->{$img};
 1538: 	    $img_import = ($imgfile =~ m{^/adm/});
 1539:         } else {
 1540:             $imgfile = $defaults->{$img};
 1541:         }
 1542:         if ($imgfile) {
 1543:             my ($showfile,$fullsize);
 1544:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 1545:                 my $urldir = $1;
 1546:                 my $filename = $2;
 1547:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 1548:                 if (@info) {
 1549:                     my $thumbfile = 'tn-'.$filename;
 1550:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 1551:                     if (@thumb) {
 1552:                         $showfile = $urldir.'/'.$thumbfile;
 1553:                     } else {
 1554:                         $showfile = $imgfile;
 1555:                     }
 1556:                 } else {
 1557:                     $showfile = '';
 1558:                 }
 1559:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 1560:                 $showfile = $imgfile;
 1561:                 my $imgdir = $1;
 1562:                 my $filename = $2;
 1563:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 1564:                     $showfile = "/$imgdir/tn-".$filename;
 1565:                 } else {
 1566:                     my $input = $londocroot.$imgfile;
 1567:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 1568:                     if (!-e $output) {
 1569:                         my ($width,$height) = &thumb_dimensions();
 1570:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 1571:                         if ($fullwidth ne '' && $fullheight ne '') {
 1572:                             if ($fullwidth > $width && $fullheight > $height) { 
 1573:                                 my $size = $width.'x'.$height;
 1574:                                 my @args = ('convert','-sample',$size,$input,$output);
 1575:                                 system({$args[0]} @args);
 1576:                                 $showfile = "/$imgdir/tn-".$filename;
 1577:                             }
 1578:                         }
 1579:                     }
 1580:                 }
 1581:             }
 1582:             if ($showfile) {
 1583:                 if ($showfile =~ m{^/(adm|res)/}) {
 1584:                     if ($showfile =~ m{^/res/}) {
 1585:                         my $local_showfile =
 1586:                             &Apache::lonnet::filelocation('',$showfile);
 1587:                         &Apache::lonnet::repcopy($local_showfile);
 1588:                     }
 1589:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 1590:                 }
 1591:                 if ($imgfile) {
 1592:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 1593:                         if ($imgfile =~ m{^/res/}) {
 1594:                             my $local_imgfile =
 1595:                                 &Apache::lonnet::filelocation('',$imgfile);
 1596:                             &Apache::lonnet::repcopy($local_imgfile);
 1597:                         }
 1598:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 1599:                     } else {
 1600:                         $fullsize = $imgfile;
 1601:                     }
 1602:                 }
 1603:                 $datatable .= '<td>';
 1604:                 if ($img eq 'login') {
 1605:                     $datatable .= $login_hdr_pick;
 1606:                 } 
 1607:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 1608:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 1609:             } else {
 1610:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1611:                               &mt('Upload:').'<br />';
 1612:             }
 1613:         } else {
 1614:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1615:                           &mt('Upload:').'<br />';
 1616:         }
 1617:         if ($switchserver) {
 1618:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1619:         } else {
 1620:             if ($img ne 'login') { # suppress file selection for Log-in header
 1621:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 1622:             }
 1623:         }
 1624:         $datatable .= '</td></tr>';
 1625:     }
 1626:     $itemcount ++;
 1627:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1628:     $datatable .= '<tr'.$css_class.'>'.
 1629:                   '<td>'.$choices->{'bgs'}.'</td>';
 1630:     my $bgs_def;
 1631:     foreach my $item (@{$bgs}) {
 1632:         if (!$is_custom->{$item}) {
 1633:             $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>';
 1634:         }
 1635:     }
 1636:     if ($bgs_def) {
 1637:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 1638:     } else {
 1639:         $datatable .= '<td>&nbsp;</td>';
 1640:     }
 1641:     $datatable .= '<td class="LC_right_item">'.
 1642:                   '<table border="0"><tr>';
 1643: 
 1644:     foreach my $item (@{$bgs}) {
 1645:         $datatable .= '<td align="center">'.$choices->{$item};
 1646: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 1647:         if ($designs->{'bgs'}{$item}) {
 1648:             $datatable .= '&nbsp;';
 1649:         }
 1650:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 1651:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 1652:     }
 1653:     $datatable .= '</tr></table></td></tr>';
 1654:     $itemcount ++;
 1655:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1656:     $datatable .= '<tr'.$css_class.'>'.
 1657:                   '<td>'.$choices->{'links'}.'</td>';
 1658:     my $links_def;
 1659:     foreach my $item (@{$links}) {
 1660:         if (!$is_custom->{$item}) {
 1661:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 1662:         }
 1663:     }
 1664:     if ($links_def) {
 1665:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 1666:     } else {
 1667:         $datatable .= '<td>&nbsp;</td>';
 1668:     }
 1669:     $datatable .= '<td class="LC_right_item">'.
 1670:                   '<table border="0"><tr>';
 1671:     foreach my $item (@{$links}) {
 1672: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 1673:         $datatable .= '<td align="center">'.$choices->{$item}."\n";
 1674:         if ($designs->{'links'}{$item}) {
 1675:             $datatable.='&nbsp;';
 1676:         }
 1677:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 1678:                       '" /></td>';
 1679:     }
 1680:     $$rowtotal += $itemcount;
 1681:     return $datatable;
 1682: }
 1683: 
 1684: sub logo_display_options {
 1685:     my ($img,$defaults,$designs) = @_;
 1686:     my $checkedon;
 1687:     if (ref($defaults) eq 'HASH') {
 1688:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 1689:             if ($defaults->{'showlogo'}{$img}) {
 1690:                 $checkedon = 'checked="checked" ';     
 1691:             }
 1692:         } 
 1693:     }
 1694:     if (ref($designs) eq 'HASH') {
 1695:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 1696:             if (defined($designs->{'showlogo'}{$img})) {
 1697:                 if ($designs->{'showlogo'}{$img} == 0) {
 1698:                     $checkedon = '';
 1699:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 1700:                     $checkedon = 'checked="checked" ';
 1701:                 }
 1702:             }
 1703:         }
 1704:     }
 1705:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 1706:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 1707:            &mt('show').'</label>'."\n";
 1708: }
 1709: 
 1710: sub login_header_options  {
 1711:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 1712:     my $output = '';
 1713:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 1714:         $output .= &mt('Text default(s):').'<br />';
 1715:         if (!$is_custom->{'textcol'}) {
 1716:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 1717:                        '&nbsp;&nbsp;&nbsp;';
 1718:         }
 1719:         if (!$is_custom->{'bgcol'}) {
 1720:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 1721:                        '<span id="css_'.$role.'_font" style="background-color: '.
 1722:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 1723:         }
 1724:         $output .= '<br />';
 1725:     }
 1726:     $output .='<br />';
 1727:     return $output;
 1728: }
 1729: 
 1730: sub login_text_colors {
 1731:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 1732:     my $color_menu = '<table border="0"><tr>';
 1733:     foreach my $item (@{$logintext}) {
 1734:         $color_menu .= '<td align="center">'.$choices->{$item};
 1735:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 1736:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 1737:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 1738:     }
 1739:     $color_menu .= '</tr></table><br />';
 1740:     return $color_menu;
 1741: }
 1742: 
 1743: sub image_changes {
 1744:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 1745:     my $output;
 1746:     if ($img eq 'login') {
 1747:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 1748:     } elsif (!$is_custom) {
 1749:         if ($img ne 'domlogo') {
 1750:             $output = &mt('Default image:').'<br />';
 1751:         } else {
 1752:             $output = &mt('Default in use:').'<br />';
 1753:         }
 1754:     }
 1755:     if ($img ne 'login') {
 1756:         if ($img_import) {
 1757:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 1758:         }
 1759:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 1760:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 1761:         if ($is_custom) {
 1762:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 1763:                        '<input type="checkbox" name="'.
 1764:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 1765:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 1766:         } else {
 1767:             $output .= '<td valign="middle">'.$logincolors.&mt('Upload:').'<br />';
 1768:         }
 1769:     }
 1770:     return $output;
 1771: }
 1772: 
 1773: sub print_quotas {
 1774:     my ($dom,$settings,$rowtotal,$action) = @_;
 1775:     my $context;
 1776:     if ($action eq 'quotas') {
 1777:         $context = 'tools';
 1778:     } else {
 1779:         $context = $action;
 1780:     }
 1781:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 1782:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 1783:     my $typecount = 0;
 1784:     my ($css_class,%titles);
 1785:     if ($context eq 'requestcourses') {
 1786:         @usertools = ('official','unofficial','community','textbook');
 1787:         @options =('norequest','approval','validate','autolimit');
 1788:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 1789:         %titles = &courserequest_titles();
 1790:     } elsif ($context eq 'requestauthor') {
 1791:         @usertools = ('author');
 1792:         @options = ('norequest','approval','automatic');
 1793:         %titles = &authorrequest_titles();
 1794:     } else {
 1795:         @usertools = ('aboutme','blog','webdav','portfolio');
 1796:         %titles = &tool_titles();
 1797:     }
 1798:     if (ref($types) eq 'ARRAY') {
 1799:         foreach my $type (@{$types}) {
 1800:             my ($currdefquota,$currauthorquota);
 1801:             unless (($context eq 'requestcourses') ||
 1802:                     ($context eq 'requestauthor')) {
 1803:                 if (ref($settings) eq 'HASH') {
 1804:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 1805:                         $currdefquota = $settings->{defaultquota}->{$type};
 1806:                     } else {
 1807:                         $currdefquota = $settings->{$type};
 1808:                     }
 1809:                     if (ref($settings->{authorquota}) eq 'HASH') {
 1810:                         $currauthorquota = $settings->{authorquota}->{$type};
 1811:                     }
 1812:                 }
 1813:             }
 1814:             if (defined($usertypes->{$type})) {
 1815:                 $typecount ++;
 1816:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 1817:                 $datatable .= '<tr'.$css_class.'>'.
 1818:                               '<td>'.$usertypes->{$type}.'</td>'.
 1819:                               '<td class="LC_left_item">';
 1820:                 if ($context eq 'requestcourses') {
 1821:                     $datatable .= '<table><tr>';
 1822:                 }
 1823:                 my %cell;  
 1824:                 foreach my $item (@usertools) {
 1825:                     if ($context eq 'requestcourses') {
 1826:                         my ($curroption,$currlimit);
 1827:                         if (ref($settings) eq 'HASH') {
 1828:                             if (ref($settings->{$item}) eq 'HASH') {
 1829:                                 $curroption = $settings->{$item}->{$type};
 1830:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 1831:                                     $currlimit = $1; 
 1832:                                 }
 1833:                             }
 1834:                         }
 1835:                         if (!$curroption) {
 1836:                             $curroption = 'norequest';
 1837:                         }
 1838:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 1839:                         foreach my $option (@options) {
 1840:                             my $val = $option;
 1841:                             if ($option eq 'norequest') {
 1842:                                 $val = 0;  
 1843:                             }
 1844:                             if ($option eq 'validate') {
 1845:                                 my $canvalidate = 0;
 1846:                                 if (ref($validations{$item}) eq 'HASH') { 
 1847:                                     if ($validations{$item}{$type}) {
 1848:                                         $canvalidate = 1;
 1849:                                     }
 1850:                                 }
 1851:                                 next if (!$canvalidate);
 1852:                             }
 1853:                             my $checked = '';
 1854:                             if ($option eq $curroption) {
 1855:                                 $checked = ' checked="checked"';
 1856:                             } elsif ($option eq 'autolimit') {
 1857:                                 if ($curroption =~ /^autolimit/) {
 1858:                                     $checked = ' checked="checked"';
 1859:                                 }                       
 1860:                             } 
 1861:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 1862:                                   '<input type="radio" name="crsreq_'.$item.
 1863:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 1864:                                   $titles{$option}.'</label>';
 1865:                             if ($option eq 'autolimit') {
 1866:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 1867:                                                 $item.'_limit_'.$type.'" size="1" '.
 1868:                                                 'value="'.$currlimit.'" />';
 1869:                             }
 1870:                             $cell{$item} .= '</span> ';
 1871:                             if ($option eq 'autolimit') {
 1872:                                 $cell{$item} .= $titles{'unlimited'};
 1873:                             }
 1874:                         }
 1875:                     } elsif ($context eq 'requestauthor') {
 1876:                         my $curroption;
 1877:                         if (ref($settings) eq 'HASH') {
 1878:                             $curroption = $settings->{$type};
 1879:                         }
 1880:                         if (!$curroption) {
 1881:                             $curroption = 'norequest';
 1882:                         }
 1883:                         foreach my $option (@options) {
 1884:                             my $val = $option;
 1885:                             if ($option eq 'norequest') {
 1886:                                 $val = 0;
 1887:                             }
 1888:                             my $checked = '';
 1889:                             if ($option eq $curroption) {
 1890:                                 $checked = ' checked="checked"';
 1891:                             }
 1892:                             $datatable .= '<span class="LC_nobreak"><label>'.
 1893:                                   '<input type="radio" name="authorreq_'.$type.
 1894:                                   '" value="'.$val.'"'.$checked.' />'.
 1895:                                   $titles{$option}.'</label></span>&nbsp; ';
 1896:                         }
 1897:                     } else {
 1898:                         my $checked = 'checked="checked" ';
 1899:                         if (ref($settings) eq 'HASH') {
 1900:                             if (ref($settings->{$item}) eq 'HASH') {
 1901:                                 if ($settings->{$item}->{$type} == 0) {
 1902:                                     $checked = '';
 1903:                                 } elsif ($settings->{$item}->{$type} == 1) {
 1904:                                     $checked =  'checked="checked" ';
 1905:                                 }
 1906:                             }
 1907:                         }
 1908:                         $datatable .= '<span class="LC_nobreak"><label>'.
 1909:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 1910:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 1911:                                       '</label></span>&nbsp; ';
 1912:                     }
 1913:                 }
 1914:                 if ($context eq 'requestcourses') {
 1915:                     $datatable .= '</tr><tr>';
 1916:                     foreach my $item (@usertools) {
 1917:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 1918:                     }
 1919:                     $datatable .= '</tr></table>';
 1920:                 }
 1921:                 $datatable .= '</td>';
 1922:                 unless (($context eq 'requestcourses') ||
 1923:                         ($context eq 'requestauthor')) {
 1924:                     $datatable .= 
 1925:                               '<td class="LC_right_item">'.
 1926:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 1927:                               '<input type="text" name="quota_'.$type.
 1928:                               '" value="'.$currdefquota.
 1929:                               '" size="5" /></span>'.('&nbsp;' x 2).
 1930:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 1931:                               '<input type="text" name="authorquota_'.$type.
 1932:                               '" value="'.$currauthorquota.
 1933:                               '" size="5" /></span></td>';
 1934:                 }
 1935:                 $datatable .= '</tr>';
 1936:             }
 1937:         }
 1938:     }
 1939:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 1940:         $defaultquota = '20';
 1941:         $authorquota = '500';
 1942:         if (ref($settings) eq 'HASH') {
 1943:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 1944:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 1945:             } elsif (defined($settings->{'default'})) {
 1946:                 $defaultquota = $settings->{'default'};
 1947:             }
 1948:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 1949:                 $authorquota = $settings->{'authorquota'}->{'default'};
 1950:             }
 1951:         }
 1952:     }
 1953:     $typecount ++;
 1954:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 1955:     $datatable .= '<tr'.$css_class.'>'.
 1956:                   '<td>'.$othertitle.'</td>'.
 1957:                   '<td class="LC_left_item">';
 1958:     if ($context eq 'requestcourses') {
 1959:         $datatable .= '<table><tr>';
 1960:     }
 1961:     my %defcell;
 1962:     foreach my $item (@usertools) {
 1963:         if ($context eq 'requestcourses') {
 1964:             my ($curroption,$currlimit);
 1965:             if (ref($settings) eq 'HASH') {
 1966:                 if (ref($settings->{$item}) eq 'HASH') {
 1967:                     $curroption = $settings->{$item}->{'default'};
 1968:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 1969:                         $currlimit = $1;
 1970:                     }
 1971:                 }
 1972:             }
 1973:             if (!$curroption) {
 1974:                 $curroption = 'norequest';
 1975:             }
 1976:             $datatable .= '<th>'.$titles{$item}.'</th>';
 1977:             foreach my $option (@options) {
 1978:                 my $val = $option;
 1979:                 if ($option eq 'norequest') {
 1980:                     $val = 0;
 1981:                 }
 1982:                 if ($option eq 'validate') {
 1983:                     my $canvalidate = 0;
 1984:                     if (ref($validations{$item}) eq 'HASH') {
 1985:                         if ($validations{$item}{'default'}) {
 1986:                             $canvalidate = 1;
 1987:                         }
 1988:                     }
 1989:                     next if (!$canvalidate);
 1990:                 }
 1991:                 my $checked = '';
 1992:                 if ($option eq $curroption) {
 1993:                     $checked = ' checked="checked"';
 1994:                 } elsif ($option eq 'autolimit') {
 1995:                     if ($curroption =~ /^autolimit/) {
 1996:                         $checked = ' checked="checked"';
 1997:                     }
 1998:                 }
 1999:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2000:                                   '<input type="radio" name="crsreq_'.$item.
 2001:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2002:                                   $titles{$option}.'</label>';
 2003:                 if ($option eq 'autolimit') {
 2004:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2005:                                        $item.'_limit_default" size="1" '.
 2006:                                        'value="'.$currlimit.'" />';
 2007:                 }
 2008:                 $defcell{$item} .= '</span> ';
 2009:                 if ($option eq 'autolimit') {
 2010:                     $defcell{$item} .= $titles{'unlimited'};
 2011:                 }
 2012:             }
 2013:         } elsif ($context eq 'requestauthor') {
 2014:             my $curroption;
 2015:             if (ref($settings) eq 'HASH') {
 2016:                 $curroption = $settings->{'default'};
 2017:             }
 2018:             if (!$curroption) {
 2019:                 $curroption = 'norequest';
 2020:             }
 2021:             foreach my $option (@options) {
 2022:                 my $val = $option;
 2023:                 if ($option eq 'norequest') {
 2024:                     $val = 0;
 2025:                 }
 2026:                 my $checked = '';
 2027:                 if ($option eq $curroption) {
 2028:                     $checked = ' checked="checked"';
 2029:                 }
 2030:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2031:                               '<input type="radio" name="authorreq_default"'.
 2032:                               ' value="'.$val.'"'.$checked.' />'.
 2033:                               $titles{$option}.'</label></span>&nbsp; ';
 2034:             }
 2035:         } else {
 2036:             my $checked = 'checked="checked" ';
 2037:             if (ref($settings) eq 'HASH') {
 2038:                 if (ref($settings->{$item}) eq 'HASH') {
 2039:                     if ($settings->{$item}->{'default'} == 0) {
 2040:                         $checked = '';
 2041:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2042:                         $checked = 'checked="checked" ';
 2043:                     }
 2044:                 }
 2045:             }
 2046:             $datatable .= '<span class="LC_nobreak"><label>'.
 2047:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2048:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2049:                           '</label></span>&nbsp; ';
 2050:         }
 2051:     }
 2052:     if ($context eq 'requestcourses') {
 2053:         $datatable .= '</tr><tr>';
 2054:         foreach my $item (@usertools) {
 2055:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2056:         }
 2057:         $datatable .= '</tr></table>';
 2058:     }
 2059:     $datatable .= '</td>';
 2060:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2061:         $datatable .= '<td class="LC_right_item">'.
 2062:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2063:                       '<input type="text" name="defaultquota" value="'.
 2064:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2065:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2066:                       '<input type="text" name="authorquota" value="'.
 2067:                       $authorquota.'" size="5" /></span></td>';
 2068:     }
 2069:     $datatable .= '</tr>';
 2070:     $typecount ++;
 2071:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2072:     $datatable .= '<tr'.$css_class.'>'.
 2073:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2074:     if ($context eq 'requestcourses') {
 2075:         $datatable .= &mt('(overrides affiliation, if set)').
 2076:                       '</td>'.
 2077:                       '<td class="LC_left_item">'.
 2078:                       '<table><tr>';
 2079:     } else {
 2080:         $datatable .= &mt('(overrides affiliation, if checked)').
 2081:                       '</td>'.
 2082:                       '<td class="LC_left_item" colspan="2">'.
 2083:                       '<br />';
 2084:     }
 2085:     my %advcell;
 2086:     foreach my $item (@usertools) {
 2087:         if ($context eq 'requestcourses') {
 2088:             my ($curroption,$currlimit);
 2089:             if (ref($settings) eq 'HASH') {
 2090:                 if (ref($settings->{$item}) eq 'HASH') {
 2091:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2092:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2093:                         $currlimit = $1;
 2094:                     }
 2095:                 }
 2096:             }
 2097:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2098:             my $checked = '';
 2099:             if ($curroption eq '') {
 2100:                 $checked = ' checked="checked"';
 2101:             }
 2102:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2103:                                '<input type="radio" name="crsreq_'.$item.
 2104:                                '__LC_adv" value=""'.$checked.' />'.
 2105:                                &mt('No override set').'</label></span>&nbsp; ';
 2106:             foreach my $option (@options) {
 2107:                 my $val = $option;
 2108:                 if ($option eq 'norequest') {
 2109:                     $val = 0;
 2110:                 }
 2111:                 if ($option eq 'validate') {
 2112:                     my $canvalidate = 0;
 2113:                     if (ref($validations{$item}) eq 'HASH') {
 2114:                         if ($validations{$item}{'_LC_adv'}) {
 2115:                             $canvalidate = 1;
 2116:                         }
 2117:                     }
 2118:                     next if (!$canvalidate);
 2119:                 }
 2120:                 my $checked = '';
 2121:                 if ($val eq $curroption) {
 2122:                     $checked = ' checked="checked"';
 2123:                 } elsif ($option eq 'autolimit') {
 2124:                     if ($curroption =~ /^autolimit/) {
 2125:                         $checked = ' checked="checked"';
 2126:                     }
 2127:                 }
 2128:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2129:                                   '<input type="radio" name="crsreq_'.$item.
 2130:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2131:                                   $titles{$option}.'</label>';
 2132:                 if ($option eq 'autolimit') {
 2133:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2134:                                        $item.'_limit__LC_adv" size="1" '.
 2135:                                        'value="'.$currlimit.'" />';
 2136:                 }
 2137:                 $advcell{$item} .= '</span> ';
 2138:                 if ($option eq 'autolimit') {
 2139:                     $advcell{$item} .= $titles{'unlimited'};
 2140:                 }
 2141:             }
 2142:         } elsif ($context eq 'requestauthor') {
 2143:             my $curroption;
 2144:             if (ref($settings) eq 'HASH') {
 2145:                 $curroption = $settings->{'_LC_adv'};
 2146:             }
 2147:             my $checked = '';
 2148:             if ($curroption eq '') {
 2149:                 $checked = ' checked="checked"';
 2150:             }
 2151:             $datatable .= '<span class="LC_nobreak"><label>'.
 2152:                           '<input type="radio" name="authorreq__LC_adv"'.
 2153:                           ' value=""'.$checked.' />'.
 2154:                           &mt('No override set').'</label></span>&nbsp; ';
 2155:             foreach my $option (@options) {
 2156:                 my $val = $option;
 2157:                 if ($option eq 'norequest') {
 2158:                     $val = 0;
 2159:                 }
 2160:                 my $checked = '';
 2161:                 if ($val eq $curroption) {
 2162:                     $checked = ' checked="checked"';
 2163:                 }
 2164:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2165:                               '<input type="radio" name="authorreq__LC_adv"'.
 2166:                               ' value="'.$val.'"'.$checked.' />'.
 2167:                               $titles{$option}.'</label></span>&nbsp; ';
 2168:             }
 2169:         } else {
 2170:             my $checked = 'checked="checked" ';
 2171:             if (ref($settings) eq 'HASH') {
 2172:                 if (ref($settings->{$item}) eq 'HASH') {
 2173:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2174:                         $checked = '';
 2175:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2176:                         $checked = 'checked="checked" ';
 2177:                     }
 2178:                 }
 2179:             }
 2180:             $datatable .= '<span class="LC_nobreak"><label>'.
 2181:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2182:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2183:                           '</label></span>&nbsp; ';
 2184:         }
 2185:     }
 2186:     if ($context eq 'requestcourses') {
 2187:         $datatable .= '</tr><tr>';
 2188:         foreach my $item (@usertools) {
 2189:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2190:         }
 2191:         $datatable .= '</tr></table>';
 2192:     }
 2193:     $datatable .= '</td></tr>';
 2194:     $$rowtotal += $typecount;
 2195:     return $datatable;
 2196: }
 2197: 
 2198: sub print_requestmail {
 2199:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2200:     my ($now,$datatable,%currapp);
 2201:     $now = time;
 2202:     if (ref($settings) eq 'HASH') {
 2203:         if (ref($settings->{'notify'}) eq 'HASH') {
 2204:             if ($settings->{'notify'}{'approval'} ne '') {
 2205:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2206:             }
 2207:         }
 2208:     }
 2209:     my $numinrow = 2;
 2210:     my $css_class;
 2211:     if ($$rowtotal%2) {
 2212:         $css_class = 'LC_odd_row';
 2213:     }
 2214:     if ($customcss) {
 2215:         $css_class .= " $customcss";
 2216:     }
 2217:     $css_class =~ s/^\s+//;
 2218:     if ($css_class) {
 2219:         $css_class = ' class="'.$css_class.'"';
 2220:     }
 2221:     if ($rowstyle) {
 2222:         $css_class .= ' style="'.$rowstyle.'"';
 2223:     }
 2224:     my $text;
 2225:     if ($action eq 'requestcourses') {
 2226:         $text = &mt('Receive notification of course requests requiring approval');
 2227:     } elsif ($action eq 'requestauthor') {
 2228:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2229:     } else {
 2230:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2231:     }
 2232:     $datatable = '<tr'.$css_class.'>'.
 2233:                  ' <td>'.$text.'</td>'.
 2234:                  ' <td class="LC_left_item">';
 2235:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2236:                                                  $action.'notifyapproval',%currapp);
 2237:     if ($numdc > 0) {
 2238:         $datatable .= $table;
 2239:     } else {
 2240:         $datatable .= &mt('There are no active Domain Coordinators');
 2241:     }
 2242:     $datatable .='</td></tr>';
 2243:     return $datatable;
 2244: }
 2245: 
 2246: sub print_studentcode {
 2247:     my ($settings,$rowtotal) = @_;
 2248:     my $rownum = 0; 
 2249:     my ($output,%current);
 2250:     my @crstypes = ('official','unofficial','community','textbook');
 2251:     if (ref($settings) eq 'HASH') {
 2252:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2253:             foreach my $type (@crstypes) {
 2254:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2255:             }
 2256:         }
 2257:     }
 2258:     $output .= '<tr>'.
 2259:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2260:                '<td class="LC_left_item">';
 2261:     foreach my $type (@crstypes) {
 2262:         my $check = ' ';
 2263:         if ($current{$type}) {
 2264:             $check = ' checked="checked" ';
 2265:         }
 2266:         $output .= '<span class="LC_nobreak"><label>'.
 2267:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2268:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2269:     }
 2270:     $output .= '</td></tr>';
 2271:     $$rowtotal ++;
 2272:     return $output;
 2273: }
 2274: 
 2275: sub print_textbookcourses {
 2276:     my ($dom,$type,$settings,$rowtotal) = @_;
 2277:     my $rownum = 0;
 2278:     my $css_class;
 2279:     my $itemcount = 1;
 2280:     my $maxnum = 0;
 2281:     my $bookshash;
 2282:     if (ref($settings) eq 'HASH') {
 2283:         $bookshash = $settings->{$type};
 2284:     }
 2285:     my %ordered;
 2286:     if (ref($bookshash) eq 'HASH') {
 2287:         foreach my $item (keys(%{$bookshash})) {
 2288:             if (ref($bookshash->{$item}) eq 'HASH') {
 2289:                 my $num = $bookshash->{$item}{'order'};
 2290:                 $ordered{$num} = $item;
 2291:             }
 2292:         }
 2293:     }
 2294:     my $confname = $dom.'-domainconfig';
 2295:     my $switchserver = &check_switchserver($dom,$confname);
 2296:     my $maxnum = scalar(keys(%ordered));
 2297:     my $datatable;
 2298:     if (keys(%ordered)) {
 2299:         my @items = sort { $a <=> $b } keys(%ordered);
 2300:         for (my $i=0; $i<@items; $i++) {
 2301:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2302:             my $key = $ordered{$items[$i]};
 2303:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2304:             my $coursetitle = $coursehash{'description'};
 2305:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2306:             if (ref($bookshash->{$key}) eq 'HASH') {
 2307:                 $subject = $bookshash->{$key}->{'subject'};
 2308:                 $title = $bookshash->{$key}->{'title'};
 2309:                 if ($type eq 'textbooks') {
 2310:                     $publisher = $bookshash->{$key}->{'publisher'};
 2311:                     $author = $bookshash->{$key}->{'author'};
 2312:                     $image = $bookshash->{$key}->{'image'};
 2313:                     if ($image ne '') {
 2314:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2315:                         my $imagethumb = "$path/tn-".$imagefile;
 2316:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2317:                     }
 2318:                 }
 2319:             }
 2320:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2321:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2322:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2323:             for (my $k=0; $k<=$maxnum; $k++) {
 2324:                 my $vpos = $k+1;
 2325:                 my $selstr;
 2326:                 if ($k == $i) {
 2327:                     $selstr = ' selected="selected" ';
 2328:                 }
 2329:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2330:             }
 2331:             $datatable .= '</select>'.('&nbsp;'x2).
 2332:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2333:                 &mt('Delete?').'</label></span></td>'.
 2334:                 '<td colspan="2">'.
 2335:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2336:                 ('&nbsp;'x2).
 2337:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2338:             if ($type eq 'textbooks') {
 2339:                 $datatable .= ('&nbsp;'x2).
 2340:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2341:                               ('&nbsp;'x2).
 2342:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2343:                               ('&nbsp;'x2).
 2344:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2345:                 if ($image) {
 2346:                     $datatable .= '<span class="LC_nobreak">'.
 2347:                                   $imgsrc.
 2348:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2349:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2350:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2351:                 }
 2352:                 if ($switchserver) {
 2353:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2354:                 } else {
 2355:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2356:                 }
 2357:             }
 2358:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2359:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2360:                           $coursetitle.'</span></td></tr>'."\n";
 2361:             $itemcount ++;
 2362:         }
 2363:     }
 2364:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2365:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2366:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2367:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2368:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2369:     for (my $k=0; $k<$maxnum+1; $k++) {
 2370:         my $vpos = $k+1;
 2371:         my $selstr;
 2372:         if ($k == $maxnum) {
 2373:             $selstr = ' selected="selected" ';
 2374:         }
 2375:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2376:     }
 2377:     $datatable .= '</select>&nbsp;'."\n".
 2378:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2379:                   '<td colspan="2">'.
 2380:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2381:                   ('&nbsp;'x2).
 2382:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2383:                   ('&nbsp;'x2);
 2384:     if ($type eq 'textbooks') {
 2385:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2386:                       ('&nbsp;'x2).
 2387:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2388:                       ('&nbsp;'x2).
 2389:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2390:         if ($switchserver) {
 2391:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2392:         } else {
 2393:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2394:         }
 2395:         $datatable .= '</span>'."\n";
 2396:     }
 2397:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2398:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2399:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2400:                   &Apache::loncommon::selectcourse_link
 2401:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2402:                   '</span></td>'."\n".
 2403:                   '</tr>'."\n";
 2404:     $itemcount ++;
 2405:     return $datatable;
 2406: }
 2407: 
 2408: sub textbookcourses_javascript {
 2409:     my ($settings) = @_;
 2410:     return unless(ref($settings) eq 'HASH');
 2411:     my (%ordered,%total,%jstext);
 2412:     foreach my $type ('textbooks','templates') {
 2413:         $total{$type} = 0;
 2414:         if (ref($settings->{$type}) eq 'HASH') {
 2415:             foreach my $item (keys(%{$settings->{$type}})) {
 2416:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2417:                     my $num = $settings->{$type}->{$item}{'order'};
 2418:                     $ordered{$type}{$num} = $item;
 2419:                 }
 2420:             }
 2421:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2422:         }
 2423:         my @jsarray = ();
 2424:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 2425:             push(@jsarray,$ordered{$type}{$item});
 2426:         }
 2427:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 2428:     }
 2429:     return <<"ENDSCRIPT";
 2430: <script type="text/javascript">
 2431: // <![CDATA[
 2432: function reorderBooks(form,item,caller) {
 2433:     var changedVal;
 2434: $jstext{'textbooks'};
 2435: $jstext{'templates'};
 2436:     var newpos;
 2437:     var maxh;
 2438:     if (caller == 'textbooks') {  
 2439:         newpos = 'textbooks_addbook_pos';
 2440:         maxh = 1 + $total{'textbooks'};
 2441:     } else {
 2442:         newpos = 'templates_addbook_pos';
 2443:         maxh = 1 + $total{'templates'};
 2444:     }
 2445:     var current = new Array;
 2446:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2447:     if (item == newpos) {
 2448:         changedVal = newitemVal;
 2449:     } else {
 2450:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2451:         current[newitemVal] = newpos;
 2452:     }
 2453:     if (caller == 'textbooks') {
 2454:         for (var i=0; i<textbooks.length; i++) {
 2455:             var elementName = 'textbooks_'+textbooks[i];
 2456:             if (elementName != item) {
 2457:                 if (form.elements[elementName]) {
 2458:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2459:                     current[currVal] = elementName;
 2460:                 }
 2461:             }
 2462:         }
 2463:     }
 2464:     if (caller == 'templates') {
 2465:         for (var i=0; i<templates.length; i++) {
 2466:             var elementName = 'templates_'+templates[i];
 2467:             if (elementName != item) {
 2468:                 if (form.elements[elementName]) {
 2469:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2470:                     current[currVal] = elementName;
 2471:                 }
 2472:             }
 2473:         }
 2474:     }
 2475:     var oldVal;
 2476:     for (var j=0; j<maxh; j++) {
 2477:         if (current[j] == undefined) {
 2478:             oldVal = j;
 2479:         }
 2480:     }
 2481:     if (oldVal < changedVal) {
 2482:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2483:            var elementName = current[k];
 2484:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2485:         }
 2486:     } else {
 2487:         for (var k=changedVal; k<oldVal; k++) {
 2488:             var elementName = current[k];
 2489:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2490:         }
 2491:     }
 2492:     return;
 2493: }
 2494: 
 2495: // ]]>
 2496: </script>
 2497: 
 2498: ENDSCRIPT
 2499: }
 2500: 
 2501: sub print_autoenroll {
 2502:     my ($dom,$settings,$rowtotal) = @_;
 2503:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 2504:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,$failsafe);
 2505:     if (ref($settings) eq 'HASH') {
 2506:         if (exists($settings->{'run'})) {
 2507:             if ($settings->{'run'} eq '0') {
 2508:                 $runoff = ' checked="checked" ';
 2509:                 $runon = ' ';
 2510:             } else {
 2511:                 $runon = ' checked="checked" ';
 2512:                 $runoff = ' ';
 2513:             }
 2514:         } else {
 2515:             if ($autorun) {
 2516:                 $runon = ' checked="checked" ';
 2517:                 $runoff = ' ';
 2518:             } else {
 2519:                 $runoff = ' checked="checked" ';
 2520:                 $runon = ' ';
 2521:             }
 2522:         }
 2523:         if (exists($settings->{'co-owners'})) {
 2524:             if ($settings->{'co-owners'} eq '0') {
 2525:                 $coownersoff = ' checked="checked" ';
 2526:                 $coownerson = ' ';
 2527:             } else {
 2528:                 $coownerson = ' checked="checked" ';
 2529:                 $coownersoff = ' ';
 2530:             }
 2531:         } else {
 2532:             $coownersoff = ' checked="checked" ';
 2533:             $coownerson = ' ';
 2534:         }
 2535:         if (exists($settings->{'sender_domain'})) {
 2536:             $defdom = $settings->{'sender_domain'};
 2537:         }
 2538:         if (exists($settings->{'autofailsafe'})) {
 2539:             $failsafe = $settings->{'autofailsafe'};
 2540:         }
 2541:     } else {
 2542:         if ($autorun) {
 2543:             $runon = ' checked="checked" ';
 2544:             $runoff = ' ';
 2545:         } else {
 2546:             $runoff = ' checked="checked" ';
 2547:             $runon = ' ';
 2548:         }
 2549:     }
 2550:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 2551:     my $notif_sender;
 2552:     if (ref($settings) eq 'HASH') {
 2553:         $notif_sender = $settings->{'sender_uname'};
 2554:     }
 2555:     my $datatable='<tr class="LC_odd_row">'.
 2556:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 2557:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2558:                   '<input type="radio" name="autoenroll_run"'.
 2559:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2560:                   '<label><input type="radio" name="autoenroll_run"'.
 2561:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 2562:                   '</tr><tr>'.
 2563:                   '<td>'.&mt('Notification messages - sender').
 2564:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 2565:                   &mt('username').':&nbsp;'.
 2566:                   '<input type="text" name="sender_uname" value="'.
 2567:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 2568:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 2569:                   '<tr class="LC_odd_row">'.
 2570:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 2571:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2572:                   '<input type="radio" name="autoassign_coowners"'.
 2573:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2574:                   '<label><input type="radio" name="autoassign_coowners"'.
 2575:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 2576:                   '</tr><tr>'.
 2577:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 2578:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 2579:                   '<input type="text" name="autoenroll_failsafe"'.
 2580:                   ' value="'.$failsafe.'" size="4" /></span></td></tr>';
 2581:     $$rowtotal += 4;
 2582:     return $datatable;
 2583: }
 2584: 
 2585: sub print_autoupdate {
 2586:     my ($position,$dom,$settings,$rowtotal) = @_;
 2587:     my $datatable;
 2588:     if ($position eq 'top') {
 2589:         my $updateon = ' ';
 2590:         my $updateoff = ' checked="checked" ';
 2591:         my $classlistson = ' ';
 2592:         my $classlistsoff = ' checked="checked" ';
 2593:         if (ref($settings) eq 'HASH') {
 2594:             if ($settings->{'run'} eq '1') {
 2595:                 $updateon = $updateoff;
 2596:                 $updateoff = ' ';
 2597:             }
 2598:             if ($settings->{'classlists'} eq '1') {
 2599:                 $classlistson = $classlistsoff;
 2600:                 $classlistsoff = ' ';
 2601:             }
 2602:         }
 2603:         my %title = (
 2604:                    run => 'Auto-update active?',
 2605:                    classlists => 'Update information in classlists?',
 2606:                     );
 2607:         $datatable = '<tr class="LC_odd_row">'. 
 2608:                   '<td>'.&mt($title{'run'}).'</td>'.
 2609:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2610:                   '<input type="radio" name="autoupdate_run"'.
 2611:                   $updateon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2612:                   '<label><input type="radio" name="autoupdate_run"'.
 2613:                   $updateoff.'value="0" />'.&mt('No').'</label></span></td>'.
 2614:                   '</tr><tr>'.
 2615:                   '<td>'.&mt($title{'classlists'}).'</td>'.
 2616:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 2617:                   '<label><input type="radio" name="classlists"'.
 2618:                   $classlistson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2619:                   '<label><input type="radio" name="classlists"'.
 2620:                   $classlistsoff.'value="0" />'.&mt('No').'</label></span></td>'.
 2621:                   '</tr>';
 2622:         $$rowtotal += 2;
 2623:     } elsif ($position eq 'middle') {
 2624:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2625:         my $numinrow = 3;
 2626:         my $locknamesettings;
 2627:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 2628:                                      $dom,$numinrow,$othertitle,
 2629:                                     'lockablenames',$rowtotal);
 2630:         $$rowtotal ++;
 2631:     } else {
 2632:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2633:         my @fields = ('lastname','firstname','middlename','generation',
 2634:                       'permanentemail','id');
 2635:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 2636:         my $numrows = 0;
 2637:         if (ref($types) eq 'ARRAY') {
 2638:             if (@{$types} > 0) {
 2639:                 $datatable = 
 2640:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 2641:                                          \@fields,$types,\$numrows);
 2642:                     $$rowtotal += @{$types}; 
 2643:             }
 2644:         }
 2645:         $datatable .= 
 2646:             &usertype_update_row($settings,{'default' => $othertitle},
 2647:                                  \%fieldtitles,\@fields,['default'],
 2648:                                  \$numrows);
 2649:         $$rowtotal ++;     
 2650:     }
 2651:     return $datatable;
 2652: }
 2653: 
 2654: sub print_autocreate {
 2655:     my ($dom,$settings,$rowtotal) = @_;
 2656:     my (%createon,%createoff,%currhash);
 2657:     my @types = ('xml','req');
 2658:     if (ref($settings) eq 'HASH') {
 2659:         foreach my $item (@types) {
 2660:             $createoff{$item} = ' checked="checked" ';
 2661:             $createon{$item} = ' ';
 2662:             if (exists($settings->{$item})) {
 2663:                 if ($settings->{$item}) {
 2664:                     $createon{$item} = ' checked="checked" ';
 2665:                     $createoff{$item} = ' ';
 2666:                 }
 2667:             }
 2668:         }
 2669:         if ($settings->{'xmldc'} ne '') {
 2670:             $currhash{$settings->{'xmldc'}} = 1;
 2671:         }
 2672:     } else {
 2673:         foreach my $item (@types) {
 2674:             $createoff{$item} = ' checked="checked" ';
 2675:             $createon{$item} = ' ';
 2676:         }
 2677:     }
 2678:     $$rowtotal += 2;
 2679:     my $numinrow = 2;
 2680:     my $datatable='<tr class="LC_odd_row">'.
 2681:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 2682:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2683:                   '<input type="radio" name="autocreate_xml"'.
 2684:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2685:                   '<label><input type="radio" name="autocreate_xml"'.
 2686:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 2687:                   '</td></tr><tr>'.
 2688:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 2689:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2690:                   '<input type="radio" name="autocreate_req"'.
 2691:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2692:                   '<label><input type="radio" name="autocreate_req"'.
 2693:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 2694:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 2695:                                                    'autocreate_xmldc',%currhash);
 2696:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 2697:     if ($numdc > 1) {
 2698:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 2699:                       '</td><td class="LC_left_item">';
 2700:     } else {
 2701:         $datatable .= &mt('Course creation processed as:').
 2702:                       '</td><td class="LC_right_item">';
 2703:     }
 2704:     $datatable .= $dctable.'</td></tr>';
 2705:     $$rowtotal += $rows;
 2706:     return $datatable;
 2707: }
 2708: 
 2709: sub print_directorysrch {
 2710:     my ($position,$dom,$settings,$rowtotal) = @_;
 2711:     my $datatable;
 2712:     if ($position eq 'top') {
 2713:         my $instsrchon = ' ';
 2714:         my $instsrchoff = ' checked="checked" ';
 2715:         my ($exacton,$containson,$beginson);
 2716:         my $instlocalon = ' ';
 2717:         my $instlocaloff = ' checked="checked" ';
 2718:         if (ref($settings) eq 'HASH') {
 2719:             if ($settings->{'available'} eq '1') {
 2720:                 $instsrchon = $instsrchoff;
 2721:                 $instsrchoff = ' ';
 2722:             }
 2723:             if ($settings->{'localonly'} eq '1') {
 2724:                 $instlocalon = $instlocaloff;
 2725:                 $instlocaloff = ' ';
 2726:             }
 2727:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 2728:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 2729:                     if ($type eq 'exact') {
 2730:                         $exacton = ' checked="checked" ';
 2731:                     } elsif ($type eq 'contains') {
 2732:                         $containson = ' checked="checked" ';
 2733:                     } elsif ($type eq 'begins') {
 2734:                         $beginson = ' checked="checked" ';
 2735:                     }
 2736:                 }
 2737:             } else {
 2738:                 if ($settings->{'searchtypes'} eq 'exact') {
 2739:                     $exacton = ' checked="checked" ';
 2740:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 2741:                     $containson = ' checked="checked" ';
 2742:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 2743:                     $exacton = ' checked="checked" ';
 2744:                     $containson = ' checked="checked" ';
 2745:                 }
 2746:             }
 2747:         }
 2748:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 2749:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2750: 
 2751:         my $numinrow = 4;
 2752:         my $cansrchrow = 0;
 2753:         $datatable='<tr class="LC_odd_row">'.
 2754:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 2755:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2756:                    '<input type="radio" name="dirsrch_available"'.
 2757:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2758:                    '<label><input type="radio" name="dirsrch_available"'.
 2759:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 2760:                    '</tr><tr>'.
 2761:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 2762:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2763:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 2764:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 2765:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 2766:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 2767:                    '</tr>';
 2768:         $$rowtotal += 2;
 2769:         if (ref($usertypes) eq 'HASH') {
 2770:             if (keys(%{$usertypes}) > 0) {
 2771:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 2772:                                              $numinrow,$othertitle,'cansearch',
 2773:                                              $rowtotal);
 2774:                 $cansrchrow = 1;
 2775:             }
 2776:         }
 2777:         if ($cansrchrow) {
 2778:             $$rowtotal ++;
 2779:             $datatable .= '<tr>';
 2780:         } else {
 2781:             $datatable .= '<tr class="LC_odd_row">';
 2782:         }
 2783:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 2784:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 2785:         foreach my $title (@{$titleorder}) {
 2786:             if (defined($searchtitles->{$title})) {
 2787:                 my $check = ' ';
 2788:                 if (ref($settings) eq 'HASH') {
 2789:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 2790:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 2791:                             $check = ' checked="checked" ';
 2792:                         }
 2793:                     }
 2794:                 }
 2795:                 $datatable .= '<td class="LC_left_item">'.
 2796:                               '<span class="LC_nobreak"><label>'.
 2797:                               '<input type="checkbox" name="searchby" '.
 2798:                               'value="'.$title.'"'.$check.'/>'.
 2799:                               $searchtitles->{$title}.'</label></span></td>';
 2800:             }
 2801:         }
 2802:         $datatable .= '</tr></table></td></tr>';
 2803:         $$rowtotal ++;
 2804:         if ($cansrchrow) {
 2805:             $datatable .= '<tr class="LC_odd_row">';
 2806:         } else {
 2807:             $datatable .= '<tr>';
 2808:         }
 2809:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 2810:                       '<td class="LC_left_item" colspan="2">'.
 2811:                       '<span class="LC_nobreak"><label>'.
 2812:                       '<input type="checkbox" name="searchtypes" '.
 2813:                       $exacton.' value="exact" />'.&mt('Exact match').
 2814:                       '</label>&nbsp;'.
 2815:                       '<label><input type="checkbox" name="searchtypes" '.
 2816:                       $beginson.' value="begins" />'.&mt('Begins with').
 2817:                       '</label>&nbsp;'.
 2818:                       '<label><input type="checkbox" name="searchtypes" '.
 2819:                       $containson.' value="contains" />'.&mt('Contains').
 2820:                       '</label></span></td></tr>';
 2821:         $$rowtotal ++;
 2822:     } else {
 2823:         my $domsrchon = ' checked="checked" ';
 2824:         my $domsrchoff = ' ';
 2825:         my $domlocalon = ' ';
 2826:         my $domlocaloff = ' checked="checked" ';
 2827:         if (ref($settings) eq 'HASH') {
 2828:             if ($settings->{'lclocalonly'} eq '1') {
 2829:                 $domlocalon = $domlocaloff;
 2830:                 $domlocaloff = ' ';
 2831:             }
 2832:             if ($settings->{'lcavailable'} eq '0') {
 2833:                 $domsrchoff = $domsrchon;
 2834:                 $domsrchon = ' ';
 2835:             }
 2836:         }
 2837:         $datatable='<tr class="LC_odd_row">'.
 2838:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 2839:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2840:                       '<input type="radio" name="dirsrch_domavailable"'.
 2841:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 2842:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 2843:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 2844:                       '</tr><tr>'.
 2845:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 2846:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 2847:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 2848:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 2849:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 2850:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 2851:                       '</tr>';
 2852:         $$rowtotal += 2;
 2853:     }
 2854:     return $datatable;
 2855: }
 2856: 
 2857: sub print_contacts {
 2858:     my ($position,$dom,$settings,$rowtotal) = @_;
 2859:     my $datatable;
 2860:     my @contacts = ('adminemail','supportemail');
 2861:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 2862:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings);
 2863:     if ($position eq 'top') {
 2864:         if (ref($settings) eq 'HASH') {
 2865:             foreach my $item (@contacts) {
 2866:                 if (exists($settings->{$item})) {
 2867:                     $to{$item} = $settings->{$item};
 2868:                 }
 2869:             }
 2870:         }
 2871:     } elsif ($position eq 'middle') {
 2872:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 2873:                      'updatesmail','idconflictsmail','hostipmail');
 2874:         foreach my $type (@mailings) {
 2875:             $otheremails{$type} = '';
 2876:         }
 2877:     } else {
 2878:         @mailings = ('helpdeskmail','otherdomsmail');
 2879:         foreach my $type (@mailings) {
 2880:             $otheremails{$type} = '';
 2881:         }
 2882:         $bccemails{'helpdeskmail'} = '';
 2883:         $bccemails{'otherdomsmail'} = '';
 2884:         $includestr{'helpdeskmail'} = '';
 2885:         $includestr{'otherdomsmail'} = '';
 2886:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 2887:     }
 2888:     if (ref($settings) eq 'HASH') {
 2889:         unless ($position eq 'top') {
 2890:             foreach my $type (@mailings) {
 2891:                 if (exists($settings->{$type})) {
 2892:                     if (ref($settings->{$type}) eq 'HASH') {
 2893:                         foreach my $item (@contacts) {
 2894:                             if ($settings->{$type}{$item}) {
 2895:                                 $checked{$type}{$item} = ' checked="checked" ';
 2896:                             }
 2897:                         }
 2898:                         $otheremails{$type} = $settings->{$type}{'others'};
 2899:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 2900:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 2901:                             if ($settings->{$type}{'include'} ne '') {
 2902:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 2903:                                 $includestr{$type} = &unescape($includestr{$type});
 2904:                             }
 2905:                         }
 2906:                     }
 2907:                 } elsif ($type eq 'lonstatusmail') {
 2908:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 2909:                 }
 2910:             }
 2911:         }
 2912:         if ($position eq 'bottom') {
 2913:             foreach my $type (@mailings) {
 2914:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 2915:                 if ($settings->{$type}{'include'} ne '') {
 2916:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 2917:                     $includestr{$type} = &unescape($includestr{$type});
 2918:                 }
 2919:             }
 2920:             if (ref($settings->{'helpform'}) eq 'HASH') {
 2921:                 if (ref($fields) eq 'ARRAY') {
 2922:                     foreach my $field (@{$fields}) {
 2923:                         $currfield{$field} = $settings->{'helpform'}{$field};
 2924:                     }
 2925:                 }
 2926:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 2927:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 2928:                 } else {
 2929:                     $maxsize = '1.0';
 2930:                 }
 2931:             } else {
 2932:                 if (ref($fields) eq 'ARRAY') {
 2933:                     foreach my $field (@{$fields}) {
 2934:                         $currfield{$field} = 'yes';
 2935:                     }
 2936:                 }
 2937:                 $maxsize = '1.0';
 2938:             }
 2939:         }
 2940:     } else {
 2941:         if ($position eq 'top') {
 2942:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 2943:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 2944:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 2945:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 2946:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 2947:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 2948:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 2949:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 2950:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 2951:         } elsif ($position eq 'bottom') {
 2952:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 2953:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 2954:             if (ref($fields) eq 'ARRAY') {
 2955:                 foreach my $field (@{$fields}) {
 2956:                     $currfield{$field} = 'yes';
 2957:                 }
 2958:             }
 2959:             $maxsize = '1.0';
 2960:         }
 2961:     }
 2962:     my ($titles,$short_titles) = &contact_titles();
 2963:     my $rownum = 0;
 2964:     my $css_class;
 2965:     if ($position eq 'top') {
 2966:         foreach my $item (@contacts) {
 2967:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 2968:             $datatable .= '<tr'.$css_class.'>'. 
 2969:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 2970:                           '</span></td><td class="LC_right_item">'.
 2971:                           '<input type="text" name="'.$item.'" value="'.
 2972:                           $to{$item}.'" /></td></tr>';
 2973:             $rownum ++;
 2974:         }
 2975:     } elsif ($position eq 'bottom') {
 2976:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 2977:         $datatable .= '<tr'.$css_class.'>'.
 2978:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 2979:                       &mt('(e-mail, subject, and description always shown)').
 2980:                       '</td><td class="LC_left_item">';
 2981:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 2982:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 2983:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 2984:             foreach my $field (@{$fields}) {
 2985:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 2986:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 2987:                     $datatable .= ' '.&mt('(logged-in users)');
 2988:                 }
 2989:                 $datatable .='</td><td>';
 2990:                 my $clickaction;
 2991:                 if ($field eq 'screenshot') {
 2992:                     $clickaction = ' onclick="screenshotSize(this);"';
 2993:                 }
 2994:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 2995:                     foreach my $option (@{$possoptions->{$field}}) {
 2996:                         my $checked;
 2997:                         if ($currfield{$field} eq $option) {
 2998:                             $checked = ' checked="checked"';
 2999:                         }
 3000:                         $datatable .= '<span class="LC_nobreak"><label>'.
 3001:                                       '<input type="radio" name="helpform_'.$field.'" '.
 3002:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 3003:                                       '</label></span>'.('&nbsp;'x2);
 3004:                     }
 3005:                 }
 3006:                 if ($field eq 'screenshot') {
 3007:                     my $display;
 3008:                     if ($currfield{$field} eq 'no') {
 3009:                         $display = ' style="display:none"';
 3010:                     }
 3011:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 3012:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 3013:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 3014:                 }
 3015:                 $datatable .= '</td></tr>';
 3016:             }
 3017:             $datatable .= '</table>';
 3018:         }
 3019:         $datatable .= '</td></tr>'."\n";
 3020:         $rownum ++;
 3021:     }
 3022:     unless ($position eq 'top') {
 3023:         foreach my $type (@mailings) {
 3024:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3025:             $datatable .= '<tr'.$css_class.'>'.
 3026:                           '<td><span class="LC_nobreak">'.
 3027:                           $titles->{$type}.': </span></td>'.
 3028:                           '<td class="LC_left_item">';
 3029:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3030:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 3031:             }
 3032:             $datatable .= '<span class="LC_nobreak">';
 3033:             foreach my $item (@contacts) {
 3034:                 $datatable .= '<label>'.
 3035:                               '<input type="checkbox" name="'.$type.'"'.
 3036:                               $checked{$type}{$item}.
 3037:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 3038:                               '</label>&nbsp;';
 3039:             }
 3040:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 3041:                           '<input type="text" name="'.$type.'_others" '.
 3042:                           'value="'.$otheremails{$type}.'"  />';
 3043:             my %locchecked;
 3044:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3045:                 foreach my $loc ('s','b') {
 3046:                     if ($includeloc{$type} eq $loc) {
 3047:                         $locchecked{$loc} = ' checked="checked"';
 3048:                         last;
 3049:                     }
 3050:                 }
 3051:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 3052:                               '<input type="text" name="'.$type.'_bcc" '.
 3053:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 3054:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 3055:                               &mt('Text automatically added to e-mail:').' '.
 3056:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 3057:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 3058:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 3059:                               ('&nbsp;'x2).
 3060:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 3061:                               '</span></fieldset>';
 3062:             }
 3063:             $datatable .= '</td></tr>'."\n";
 3064:             $rownum ++;
 3065:         }
 3066:     }
 3067:     if ($position eq 'middle') {
 3068:         my %choices;
 3069:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',
 3070:                                        &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 3071:                                        &mt('LON-CAPA core group - MSU'),600,500));
 3072:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 3073:                                         &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 3074:                                         &mt('LON-CAPA core group - MSU'),600,500));
 3075:         my @toggles = ('reporterrors','reportupdates');
 3076:         my %defaultchecked = ('reporterrors'  => 'on',
 3077:                               'reportupdates' => 'on');
 3078:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3079:                                                    \%choices,$rownum);
 3080:         $datatable .= $reports;
 3081:     } elsif ($position eq 'bottom') {
 3082:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3083:         my (@posstypes,%usertypeshash);
 3084:         if (ref($types) eq 'ARRAY') {
 3085:             @posstypes = @{$types};
 3086:         }
 3087:         if (@posstypes) {
 3088:             if (ref($usertypes) eq 'HASH') {
 3089:                 %usertypeshash = %{$usertypes};
 3090:             }
 3091:             my @overridden;
 3092:             my $numinrow = 4;
 3093:             if (ref($settings) eq 'HASH') {
 3094:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 3095:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 3096:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 3097:                             push(@overridden,$key);
 3098:                             foreach my $item (@contacts) {
 3099:                                 if ($settings->{'overrides'}{$key}{$item}) {
 3100:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 3101:                                 }
 3102:                             }
 3103:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 3104:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 3105:                             $includeloc{'override_'.$key} = '';
 3106:                             $includestr{'override_'.$key} = '';
 3107:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 3108:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) =
 3109:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 3110:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 3111:                             }
 3112:                         }
 3113:                     }
 3114:                 }
 3115:             }
 3116:             my $customclass = 'LC_helpdesk_override';
 3117:             my $optionsprefix = 'LC_options_helpdesk_';
 3118: 
 3119:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 3120: 
 3121:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 3122:                                          $numinrow,$othertitle,'overrides',
 3123:                                          \$rownum,$onclicktypes,$customclass);
 3124:             $rownum ++;
 3125:             $usertypeshash{'default'} = $othertitle;
 3126:             foreach my $status (@posstypes) {
 3127:                 my $css_class;
 3128:                 if ($rownum%2) {
 3129:                     $css_class = 'LC_odd_row ';
 3130:                 }
 3131:                 $css_class .= $customclass;
 3132:                 my $rowid = $optionsprefix.$status;
 3133:                 my $hidden = 1;
 3134:                 my $currstyle = 'display:none';
 3135:                 if (grep(/^\Q$status\E$/,@overridden)) {
 3136:                     $currstyle = 'display:table-row';
 3137:                     $hidden = 0;
 3138:                 }
 3139:                 my $key = 'override_'.$status;
 3140:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 3141:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 3142:                                                   $usertypeshash{$status},$css_class,$currstyle,
 3143:                                                   \@contacts,$short_titles);
 3144:                 unless ($hidden) {
 3145:                     $rownum ++;
 3146:                 }
 3147:             }
 3148:         }
 3149:     }
 3150:     $$rowtotal += $rownum;
 3151:     return $datatable;
 3152: }
 3153: 
 3154: sub overridden_helpdesk {
 3155:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 3156:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 3157:     my $class = 'LC_left_item';
 3158:     if ($css_class) {
 3159:         $css_class = ' class="'.$css_class.'"';
 3160:     }
 3161:     if ($rowid) {
 3162:         $rowid = ' id="'.$rowid.'"';
 3163:     }
 3164:     if ($rowstyle) {
 3165:         $rowstyle = ' style="'.$rowstyle.'"';
 3166:     }
 3167:     my ($output,$description);
 3168:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 3169:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 3170:               "<td>$description</td>\n".
 3171:               '<td class="'.$class.'" colspan="2">'.
 3172:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 3173:               '<span class="LC_nobreak">';
 3174:     if (ref($contacts) eq 'ARRAY') {
 3175:         foreach my $item (@{$contacts}) {
 3176:             my $check;
 3177:             if (ref($checked) eq 'HASH') {
 3178:                $check = $checked->{$item};
 3179:             }
 3180:             my $title;
 3181:             if (ref($short_titles) eq 'HASH') {
 3182:                 $title = $short_titles->{$item};
 3183:             }
 3184:             $output .= '<label>'.
 3185:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 3186:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 3187:         }
 3188:     }
 3189:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 3190:                '<input type="text" name="override_'.$type.'_others" '.
 3191:                'value="'.$otheremails.'"  />';
 3192:     my %locchecked;
 3193:     foreach my $loc ('s','b') {
 3194:         if ($includeloc eq $loc) {
 3195:             $locchecked{$loc} = ' checked="checked"';
 3196:             last;
 3197:         }
 3198:     }
 3199:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 3200:                '<input type="text" name="override_'.$type.'_bcc" '.
 3201:                'value="'.$bccemails.'"  /></fieldset>'.
 3202:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 3203:                &mt('Text automatically added to e-mail:').' '.
 3204:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 3205:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 3206:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 3207:                ('&nbsp;'x2).
 3208:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 3209:                '</span></fieldset>'.
 3210:                '</td></tr>'."\n";
 3211:     return $output;
 3212: }
 3213: 
 3214: sub contacts_javascript {
 3215:     return <<"ENDSCRIPT";
 3216: 
 3217: <script type="text/javascript">
 3218: // <![CDATA[
 3219: 
 3220: function screenshotSize(field) {
 3221:     if (document.getElementById('help_screenshotsize')) {
 3222:         if (field.value == 'no') {
 3223:             document.getElementById('help_screenshotsize').style.display="none";
 3224:         } else {
 3225:             document.getElementById('help_screenshotsize').style.display="";
 3226:         }
 3227:     }
 3228:     return;
 3229: }
 3230: 
 3231: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 3232:     if (form.elements[checkbox].length != undefined) {
 3233:         var count = 0;
 3234:         if (docount) {
 3235:             for (var i=0; i<form.elements[checkbox].length; i++) {
 3236:                 if (form.elements[checkbox][i].checked) {
 3237:                     count ++;
 3238:                 }
 3239:             }
 3240:         }
 3241:         for (var i=0; i<form.elements[checkbox].length; i++) {
 3242:             var type = form.elements[checkbox][i].value;
 3243:             if (document.getElementById(prefix+type)) {
 3244:                 if (form.elements[checkbox][i].checked) {
 3245:                     document.getElementById(prefix+type).style.display = 'table-row';
 3246:                     if (count % 2 == 1) {
 3247:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 3248:                     } else {
 3249:                         document.getElementById(prefix+type).className = target;
 3250:                     }
 3251:                     count ++;
 3252:                 } else {
 3253:                     document.getElementById(prefix+type).style.display = 'none';
 3254:                 }
 3255:             }
 3256:         }
 3257:     }
 3258:     return;
 3259: }
 3260: 
 3261: // ]]>
 3262: </script>
 3263: 
 3264: ENDSCRIPT
 3265: }
 3266: 
 3267: sub print_helpsettings {
 3268:     my ($position,$dom,$settings,$rowtotal) = @_;
 3269:     my $confname = $dom.'-domainconfig';
 3270:     my $formname = 'display';
 3271:     my ($datatable,$itemcount);
 3272:     if ($position eq 'top') {
 3273:         $itemcount = 1;
 3274:         my (%choices,%defaultchecked,@toggles);
 3275:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 3276:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 3277:                                      &mt('LON-CAPA bug tracker'),600,500));
 3278:         %defaultchecked = ('submitbugs' => 'on');
 3279:         @toggles = ('submitbugs');
 3280:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3281:                                                      \%choices,$itemcount);
 3282:         $$rowtotal ++;
 3283:     } else {
 3284:         my $css_class;
 3285:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 3286:         my (%customroles,%ordered,%current);
 3287:         if (ref($settings) eq 'HASH') {
 3288:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 3289:                 %current = %{$settings->{'adhoc'}};
 3290:             }
 3291:         }
 3292:         my $count = 0;
 3293:         foreach my $key (sort(keys(%existing))) {
 3294:             if ($key=~/^rolesdef\_(\w+)$/) {
 3295:                 my $rolename = $1;
 3296:                 my (%privs,$order);
 3297:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 3298:                 $customroles{$rolename} = \%privs;
 3299:                 if (ref($current{$rolename}) eq 'HASH') {
 3300:                     $order = $current{$rolename}{'order'};
 3301:                 }
 3302:                 if ($order eq '') {
 3303:                     $order = $count;
 3304:                 }
 3305:                 $ordered{$order} = $rolename;
 3306:                 $count++;
 3307:             }
 3308:         }
 3309:         my $maxnum = scalar(keys(%ordered));
 3310:         my @roles_by_num = ();
 3311:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3312:             push(@roles_by_num,$item);
 3313:         }
 3314:         my $context = 'domprefs';
 3315:         my $crstype = 'Course';
 3316:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3317:         my @accesstypes = ('all','dh','da','none');
 3318:         my ($numstatustypes,@jsarray);
 3319:         if (ref($types) eq 'ARRAY') {
 3320:             if (@{$types} > 0) {
 3321:                 $numstatustypes = scalar(@{$types});
 3322:                 push(@accesstypes,'status');
 3323:                 @jsarray = ('bystatus');
 3324:             }
 3325:         }
 3326:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 3327:         if (keys(%domhelpdesk)) {
 3328:             push(@accesstypes,('inc','exc'));
 3329:             push(@jsarray,('notinc','notexc'));
 3330:         }
 3331:         my $hiddenstr = join("','",@jsarray);
 3332:         $datatable .= &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname);
 3333:         my $context = 'domprefs';
 3334:         my $crstype = 'Course';
 3335:         my $prefix = 'helproles_';
 3336:         my $add_class = 'LC_hidden';
 3337:         foreach my $num (@roles_by_num) {
 3338:             my $role = $ordered{$num};
 3339:             my ($desc,$access,@statuses);
 3340:             if (ref($current{$role}) eq 'HASH') {
 3341:                 $desc = $current{$role}{'desc'};
 3342:                 $access = $current{$role}{'access'};
 3343:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 3344:                     @statuses = @{$current{$role}{'insttypes'}};
 3345:                 }
 3346:             }
 3347:             if ($desc eq '') {
 3348:                 $desc = $role;
 3349:             }
 3350:             my $identifier = 'custhelp'.$num;
 3351:             my %full=();
 3352:             my %levels= (
 3353:                          course => {},
 3354:                          domain => {},
 3355:                          system => {},
 3356:                         );
 3357:             my %levelscurrent=(
 3358:                                course => {},
 3359:                                domain => {},
 3360:                                system => {},
 3361:                               );
 3362:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 3363:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 3364:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3365:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 3366:             $datatable .= '<tr '.$css_class.'><td valign="top"><b>'.$role.'</b><br />'.
 3367:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 3368:             for (my $k=0; $k<=$maxnum; $k++) {
 3369:                 my $vpos = $k+1;
 3370:                 my $selstr;
 3371:                 if ($k == $num) {
 3372:                     $selstr = ' selected="selected" ';
 3373:                 }
 3374:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 3375:             }
 3376:             $datatable .= '</select>'.('&nbsp;'x2).
 3377:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 3378:                           '</td>'.
 3379:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 3380:                           &mt('Name shown to users:').
 3381:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 3382:                           '</fieldset>'.
 3383:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 3384:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 3385:                           '<fieldset>'.
 3386:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 3387:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 3388:                                                                    \%levelscurrent,$identifier,
 3389:                                                                    'LC_hidden',$prefix.$num.'_privs').
 3390:                           '</fieldset></td>';
 3391:             $itemcount ++;
 3392:         }
 3393:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3394:         my $newcust = 'custhelp'.$count;
 3395:         my (%privs,%levelscurrent);
 3396:         my %full=();
 3397:         my %levels= (
 3398:                      course => {},
 3399:                      domain => {},
 3400:                      system => {},
 3401:                     );
 3402:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 3403:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 3404:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 3405:         $datatable .= '<tr '.$css_class.'><td valign="top"><span class="LC_nobreak"><label>'.
 3406:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 3407:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 3408:         for (my $k=0; $k<$maxnum+1; $k++) {
 3409:             my $vpos = $k+1;
 3410:             my $selstr;
 3411:             if ($k == $maxnum) {
 3412:                 $selstr = ' selected="selected" ';
 3413:             }
 3414:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 3415:         }
 3416:         $datatable .= '</select>&nbsp;'."\n".
 3417:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 3418:                       '</label></span></td>'.
 3419:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 3420:                       '<span class="LC_nobreak">'.
 3421:                       &mt('Internal name:').
 3422:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 3423:                       '</span>'.('&nbsp;'x4).
 3424:                       '<span class="LC_nobreak">'.
 3425:                       &mt('Name shown to users:').
 3426:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 3427:                       '</span></fieldset>'.
 3428:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 3429:                                              $usertypes,$types,\%domhelpdesk).
 3430:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 3431:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 3432:                                                                 \@templateroles,$newcust).
 3433:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 3434:                                                                \%levelscurrent,$newcust).
 3435:                       '</fieldset>'.
 3436:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 3437:                       '</td></tr>';
 3438:         $count ++;
 3439:         $$rowtotal += $count;
 3440:     }
 3441:     return $datatable;
 3442: }
 3443: 
 3444: sub adhocbutton {
 3445:     my ($prefix,$num,$field,$visibility) = @_;
 3446:     my %lt = &Apache::lonlocal::texthash(
 3447:                                           show => 'Show details',
 3448:                                           hide => 'Hide details',
 3449:                                         );
 3450:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 3451:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 3452:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 3453:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 3454: }
 3455: 
 3456: sub helpsettings_javascript {
 3457:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 3458:     return unless(ref($roles_by_num) eq 'ARRAY');
 3459:     my %html_js_lt = &Apache::lonlocal::texthash(
 3460:                                           show => 'Show details',
 3461:                                           hide => 'Hide details',
 3462:                                         );
 3463:     &html_escape(\%html_js_lt);
 3464:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 3465:     return <<"ENDSCRIPT";
 3466: <script type="text/javascript">
 3467: // <![CDATA[
 3468: 
 3469: function reorderHelpRoles(form,item) {
 3470:     var changedVal;
 3471: $jstext
 3472:     var newpos = 'helproles_${total}_pos';
 3473:     var maxh = 1 + $total;
 3474:     var current = new Array();
 3475:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3476:     if (item == newpos) {
 3477:         changedVal = newitemVal;
 3478:     } else {
 3479:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3480:         current[newitemVal] = newpos;
 3481:     }
 3482:     for (var i=0; i<helproles.length; i++) {
 3483:         var elementName = 'helproles_'+helproles[i]+'_pos';
 3484:         if (elementName != item) {
 3485:             if (form.elements[elementName]) {
 3486:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3487:                 current[currVal] = elementName;
 3488:             }
 3489:         }
 3490:     }
 3491:     var oldVal;
 3492:     for (var j=0; j<maxh; j++) {
 3493:         if (current[j] == undefined) {
 3494:             oldVal = j;
 3495:         }
 3496:     }
 3497:     if (oldVal < changedVal) {
 3498:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3499:            var elementName = current[k];
 3500:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3501:         }
 3502:     } else {
 3503:         for (var k=changedVal; k<oldVal; k++) {
 3504:             var elementName = current[k];
 3505:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3506:         }
 3507:     }
 3508:     return;
 3509: }
 3510: 
 3511: function helpdeskAccess(num) {
 3512:     var curraccess = null;
 3513:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 3514:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 3515:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 3516:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 3517:             }
 3518:         }
 3519:     }
 3520:     var shown = Array();
 3521:     var hidden = Array();
 3522:     if (curraccess == 'none') {
 3523:         hidden = Array('$hiddenstr');
 3524:     } else {
 3525:         if (curraccess == 'status') {
 3526:             shown = Array('bystatus');
 3527:             hidden = Array('notinc','notexc');
 3528:         } else {
 3529:             if (curraccess == 'exc') {
 3530:                 shown = Array('notexc');
 3531:                 hidden = Array('notinc','bystatus');
 3532:             }
 3533:             if (curraccess == 'inc') {
 3534:                 shown = Array('notinc');
 3535:                 hidden = Array('notexc','bystatus');
 3536:             }
 3537:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 3538:                 hidden = Array('notinc','notexc','bystatus');
 3539:             }
 3540:         }
 3541:     }
 3542:     if (hidden.length > 0) {
 3543:         for (var i=0; i<hidden.length; i++) {
 3544:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 3545:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 3546:             }
 3547:         }
 3548:     }
 3549:     if (shown.length > 0) {
 3550:         for (var i=0; i<shown.length; i++) {
 3551:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 3552:                 if (shown[i] == 'privs') {
 3553:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 3554:                 } else {
 3555:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 3556:                 }
 3557:             }
 3558:         }
 3559:     }
 3560:     return;
 3561: }
 3562: 
 3563: function toggleHelpdeskItem(num,field) {
 3564:     if (document.getElementById('helproles_'+num+'_'+field)) {
 3565:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 3566:             document.getElementById('helproles_'+num+'_'+field).className =
 3567:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 3568:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 3569:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 3570:             }
 3571:         } else {
 3572:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 3573:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 3574:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 3575:             }
 3576:         }
 3577:     }
 3578:     return;
 3579: }
 3580: 
 3581: // ]]>
 3582: </script>
 3583: 
 3584: ENDSCRIPT
 3585: }
 3586: 
 3587: sub helpdeskroles_access {
 3588:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 3589:         $usertypes,$types,$domhelpdesk) = @_;
 3590:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 3591:     my %lt = &Apache::lonlocal::texthash(
 3592:                     'rou'    => 'Role usage',
 3593:                     'whi'    => 'Which helpdesk personnel may use this role?',
 3594:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 3595:                     'dh'     => 'All with domain helpdesk role',
 3596:                     'da'     => 'All with domain helpdesk assistant role',
 3597:                     'none'   => 'None',
 3598:                     'status' => 'Determined based on institutional status',
 3599:                     'inc'    => 'Include all, but exclude specific personnel',
 3600:                     'exc'    => 'Exclude all, but include specific personnel',
 3601:                   );
 3602:     my %usecheck = (
 3603:                      all => ' checked="checked"',
 3604:                    );
 3605:     my %displaydiv = (
 3606:                       status => 'none',
 3607:                       inc    => 'none',
 3608:                       exc    => 'none',
 3609:                       priv   => 'block',
 3610:                      );
 3611:     my $output;
 3612:     if (ref($current) eq 'HASH') {
 3613:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 3614:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 3615:                 $usecheck{$current->{access}} = $usecheck{'all'};
 3616:                 delete($usecheck{'all'});
 3617:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 3618:                     my $access = $1;
 3619:                     $displaydiv{$access} = 'inline';
 3620:                 } elsif ($current->{access} eq 'none') {
 3621:                     $displaydiv{'priv'} = 'none';
 3622:                 }
 3623:             }
 3624:         }
 3625:     }
 3626:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 3627:               '<p>'.$lt{'whi'}.'</p>';
 3628:     foreach my $access (@{$accesstypes}) {
 3629:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 3630:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 3631:                    $lt{$access}.'</label>';
 3632:         if ($access eq 'status') {
 3633:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 3634:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 3635:                                                                  $othertitle,$usertypes,$types).
 3636:                        '</div>';
 3637:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 3638:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 3639:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 3640:                        '</div>';
 3641:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 3642:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 3643:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 3644:                        '</div>';
 3645:         }
 3646:         $output .= '</p>';
 3647:     }
 3648:     $output .= '</fieldset>';
 3649:     return $output;
 3650: }
 3651: 
 3652: sub radiobutton_prefs {
 3653:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 3654:         $additional,$align) = @_;
 3655:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 3656:                    (ref($choices) eq 'HASH'));
 3657: 
 3658:     my (%checkedon,%checkedoff,$datatable,$css_class);
 3659: 
 3660:     foreach my $item (@{$toggles}) {
 3661:         if ($defaultchecked->{$item} eq 'on') {
 3662:             $checkedon{$item} = ' checked="checked" ';
 3663:             $checkedoff{$item} = ' ';
 3664:         } elsif ($defaultchecked->{$item} eq 'off') {
 3665:             $checkedoff{$item} = ' checked="checked" ';
 3666:             $checkedon{$item} = ' ';
 3667:         }
 3668:     }
 3669:     if (ref($settings) eq 'HASH') {
 3670:         foreach my $item (@{$toggles}) {
 3671:             if ($settings->{$item} eq '1') {
 3672:                 $checkedon{$item} =  ' checked="checked" ';
 3673:                 $checkedoff{$item} = ' ';
 3674:             } elsif ($settings->{$item} eq '0') {
 3675:                 $checkedoff{$item} =  ' checked="checked" ';
 3676:                 $checkedon{$item} = ' ';
 3677:             }
 3678:         }
 3679:     }
 3680:     if ($onclick) {
 3681:         $onclick = ' onclick="'.$onclick.'"';
 3682:     }
 3683:     foreach my $item (@{$toggles}) {
 3684:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3685:         $datatable .=
 3686:             '<tr'.$css_class.'><td valign="top">'.
 3687:             '<span class="LC_nobreak">'.$choices->{$item}.
 3688:             '</span></td>';
 3689:         if ($align eq 'left') {
 3690:             $datatable .= '<td class="LC_left_item">';
 3691:         } else {
 3692:             $datatable .= '<td class="LC_right_item">';
 3693:         }
 3694:         $datatable .=
 3695:             '<span class="LC_nobreak">'.
 3696:             '<label><input type="radio" name="'.
 3697:             $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 3698:             '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 3699:             $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>'.
 3700:             '</span>'.$additional.
 3701:             '</td>'.
 3702:             '</tr>';
 3703:         $itemcount ++;
 3704:     }
 3705:     return ($datatable,$itemcount);
 3706: }
 3707: 
 3708: sub print_coursedefaults {
 3709:     my ($position,$dom,$settings,$rowtotal) = @_;
 3710:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 3711:     my $itemcount = 1;
 3712:     my %choices =  &Apache::lonlocal::texthash (
 3713:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 3714:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 3715:         coursecredits        => 'Credits can be specified for courses',
 3716:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 3717:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 3718:         texengine            => 'Default method to display mathematics',
 3719:         postsubmit           => 'Disable submit button/keypress following student submission',
 3720:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 3721:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 3722:     );
 3723:     my %staticdefaults = (
 3724:                            anonsurvey_threshold => 10,
 3725:                            uploadquota          => 500,
 3726:                            postsubmit           => 60,
 3727:                            mysqltables          => 172800,
 3728:                          );
 3729:     if ($position eq 'top') {
 3730:         %defaultchecked = (
 3731:                             'uselcmath'       => 'on',
 3732:                             'usejsme'         => 'on',
 3733:                             'canclone'        => 'none',
 3734:                           );
 3735:         @toggles = ('uselcmath','usejsme');
 3736:         my $deftex = $Apache::lonnet::deftex;
 3737:         if (ref($settings) eq 'HASH') {
 3738:             if ($settings->{'texengine'}) {
 3739:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 3740:                     $deftex = $settings->{'texengine'};
 3741:                 }
 3742:             }
 3743:         }
 3744:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3745:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 3746:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 3747:                        '</span></td><td class="LC_right_item">'.
 3748:                        '<select name="texengine">'."\n";
 3749:         my %texoptions = (
 3750:                             MathJax  => 'MathJax',
 3751:                             mimetex  => &mt('Convert to Images'),
 3752:                             tth      => &mt('TeX to HTML'),
 3753:                          );
 3754:         foreach my $renderer ('MathJax','mimetex','tth') {
 3755:             my $selected = '';
 3756:             if ($renderer eq $deftex) {
 3757:                 $selected = ' selected="selected"';
 3758:             }
 3759:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 3760:         }
 3761:         $mathdisp .= '</select></td></tr>'."\n";
 3762:         $itemcount ++;
 3763:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3764:                                                      \%choices,$itemcount);
 3765:         $datatable = $mathdisp.$datatable;
 3766:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 3767:         $datatable .=
 3768:             '<tr'.$css_class.'><td valign="top">'.
 3769:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 3770:             '</span></td><td class="LC_left_item">';
 3771:         my $currcanclone = 'none';
 3772:         my $onclick;
 3773:         my @cloneoptions = ('none','domain');
 3774:         my %clonetitles = (
 3775:                              none     => 'No additional course requesters',
 3776:                              domain   => "Any course requester in course's domain",
 3777:                              instcode => 'Course requests for official courses ...',
 3778:                           );
 3779:         my (%codedefaults,@code_order,@posscodes);
 3780:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 3781:                                                     \@code_order) eq 'ok') {
 3782:             if (@code_order > 0) {
 3783:                 push(@cloneoptions,'instcode');
 3784:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 3785:             }
 3786:         }
 3787:         if (ref($settings) eq 'HASH') {
 3788:             if ($settings->{'canclone'}) {
 3789:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 3790:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 3791:                         if (@code_order > 0) {
 3792:                             $currcanclone = 'instcode';
 3793:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 3794:                         }
 3795:                     }
 3796:                 } elsif ($settings->{'canclone'} eq 'domain') {
 3797:                     $currcanclone = $settings->{'canclone'};
 3798:                 }
 3799:             }
 3800:         }
 3801:         foreach my $option (@cloneoptions) {
 3802:             my ($checked,$additional);
 3803:             if ($currcanclone eq $option) {
 3804:                 $checked = ' checked="checked"';
 3805:             }
 3806:             if ($option eq 'instcode') {
 3807:                 if (@code_order) {
 3808:                     my $show = 'none';
 3809:                     if ($checked) {
 3810:                         $show = 'block';
 3811:                     }
 3812:                     $additional = '<div id="cloneinstcode" style="display:'.$show.'" />'.
 3813:                                   &mt('Institutional codes for new and cloned course have identical:').
 3814:                                   '<br />';
 3815:                     foreach my $item (@code_order) {
 3816:                         my $codechk;
 3817:                         if ($checked) {
 3818:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 3819:                                 $codechk = ' checked="checked"';
 3820:                             }
 3821:                         }
 3822:                         $additional .= '<label>'.
 3823:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 3824:                                        $item.'</label>';
 3825:                     }
 3826:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 3827:                 }
 3828:             }
 3829:             $datatable .=
 3830:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 3831:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 3832:                 '</label>&nbsp;'.$additional.'</span><br />';
 3833:         }
 3834:         $datatable .= '</td>'.
 3835:                       '</tr>';
 3836:         $itemcount ++;
 3837:     } else {
 3838:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3839:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 3840:         my $currusecredits = 0;
 3841:         my $postsubmitclient = 1;
 3842:         my @types = ('official','unofficial','community','textbook');
 3843:         if (ref($settings) eq 'HASH') {
 3844:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 3845:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 3846:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 3847:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 3848:                 }
 3849:             }
 3850:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 3851:                 foreach my $type (@types) {
 3852:                     next if ($type eq 'community');
 3853:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 3854:                     if ($defcredits{$type} ne '') {
 3855:                         $currusecredits = 1;
 3856:                     }
 3857:                 }
 3858:             }
 3859:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 3860:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 3861:                     $postsubmitclient = 0;
 3862:                     foreach my $type (@types) {
 3863:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3864:                     }
 3865:                 } else {
 3866:                     foreach my $type (@types) {
 3867:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 3868:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 3869:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 3870:                             } else {
 3871:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3872:                             }
 3873:                         } else {
 3874:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3875:                         }
 3876:                     }
 3877:                 }
 3878:             } else {
 3879:                 foreach my $type (@types) {
 3880:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3881:                 }
 3882:             }
 3883:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 3884:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 3885:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 3886:                 }
 3887:             } else {
 3888:                 foreach my $type (@types) {
 3889:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 3890:                 }
 3891:             }
 3892:         } else {
 3893:             foreach my $type (@types) {
 3894:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 3895:             }
 3896:         }
 3897:         if (!$currdefresponder) {
 3898:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 3899:         } elsif ($currdefresponder < 1) {
 3900:             $currdefresponder = 1;
 3901:         }
 3902:         foreach my $type (@types) {
 3903:             if ($curruploadquota{$type} eq '') {
 3904:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 3905:             }
 3906:         }
 3907:         $datatable .=
 3908:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 3909:                 $choices{'anonsurvey_threshold'}.
 3910:                 '</span></td>'.
 3911:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 3912:                 '<input type="text" name="anonsurvey_threshold"'.
 3913:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 3914:                 '</td></tr>'."\n";
 3915:         $itemcount ++;
 3916:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3917:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 3918:                       $choices{'uploadquota'}.
 3919:                       '</span></td>'.
 3920:                       '<td align="right" class="LC_right_item">'.
 3921:                       '<table><tr>';
 3922:         foreach my $type (@types) {
 3923:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 3924:                            '<input type="text" name="uploadquota_'.$type.'"'.
 3925:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 3926:         }
 3927:         $datatable .= '</tr></table></td></tr>'."\n";
 3928:         $itemcount ++;
 3929:         my $onclick = "toggleDisplay(this.form,'credits');";
 3930:         my $display = 'none';
 3931:         if ($currusecredits) {
 3932:             $display = 'block';
 3933:         }
 3934:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 3935:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 3936:         foreach my $type (@types) {
 3937:             next if ($type eq 'community');
 3938:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 3939:                            '<input type="text" name="'.$type.'_credits"'.
 3940:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 3941:         }
 3942:         $additional .= '</tr></table></div>'."\n";
 3943:         %defaultchecked = ('coursecredits' => 'off');
 3944:         @toggles = ('coursecredits');
 3945:         my $current = {
 3946:                         'coursecredits' => $currusecredits,
 3947:                       };
 3948:         (my $table,$itemcount) =
 3949:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 3950:                                \%choices,$itemcount,$onclick,$additional,'left');
 3951:         $datatable .= $table;
 3952:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 3953:         my $display = 'none';
 3954:         if ($postsubmitclient) {
 3955:             $display = 'block';
 3956:         }
 3957:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 3958:                       &mt('Number of seconds submit is disabled').'<br />'.
 3959:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 3960:                       '<table><tr>';
 3961:         foreach my $type (@types) {
 3962:             $additional .= '<td align="center">'.&mt($type).'<br />'.
 3963:                            '<input type="text" name="'.$type.'_timeout" value="'.
 3964:                            $deftimeout{$type}.'" size="5" /></td>';
 3965:         }
 3966:         $additional .= '</tr></table></div>'."\n";
 3967:         %defaultchecked = ('postsubmit' => 'on');
 3968:         @toggles = ('postsubmit');
 3969:         $current = {
 3970:                        'postsubmit' => $postsubmitclient,
 3971:                    };
 3972:         ($table,$itemcount) =
 3973:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 3974:                                \%choices,$itemcount,$onclick,$additional,'left');
 3975:         $datatable .= $table;
 3976:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 3977:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 3978:                       $choices{'mysqltables'}.
 3979:                       '</span></td>'.
 3980:                       '<td align="right" class="LC_right_item">'.
 3981:                       '<table><tr>';
 3982:         foreach my $type (@types) {
 3983:             $datatable .= '<td align="center">'.&mt($type).'<br />'.
 3984:                            '<input type="text" name="mysqltables_'.$type.'"'.
 3985:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 3986:         }
 3987:         $datatable .= '</tr></table></td></tr>'."\n";
 3988:         $itemcount ++;
 3989: 
 3990:     }
 3991:     $$rowtotal += $itemcount;
 3992:     return $datatable;
 3993: }
 3994: 
 3995: sub print_selfenrollment {
 3996:     my ($position,$dom,$settings,$rowtotal) = @_;
 3997:     my ($css_class,$datatable);
 3998:     my $itemcount = 1;
 3999:     my @types = ('official','unofficial','community','textbook');
 4000:     if (($position eq 'top') || ($position eq 'middle')) {
 4001:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 4002:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 4003:         my @rows;
 4004:         my $key;
 4005:         if ($position eq 'top') {
 4006:             $key = 'admin'; 
 4007:             if (ref($rowsref) eq 'ARRAY') {
 4008:                 @rows = @{$rowsref};
 4009:             }
 4010:         } elsif ($position eq 'middle') {
 4011:             $key = 'default';
 4012:             @rows = ('types','registered','approval','limit');
 4013:         }
 4014:         foreach my $row (@rows) {
 4015:             if (defined($titlesref->{$row})) {
 4016:                 $itemcount ++;
 4017:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4018:                 $datatable .= '<tr'.$css_class.'>'.
 4019:                               '<td>'.$titlesref->{$row}.'</td>'.
 4020:                               '<td class="LC_left_item">'.
 4021:                               '<table><tr>';
 4022:                 my (%current,%currentcap);
 4023:                 if (ref($settings) eq 'HASH') {
 4024:                     if (ref($settings->{$key}) eq 'HASH') {
 4025:                         foreach my $type (@types) {
 4026:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 4027:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 4028:                             }
 4029:                             if (($row eq 'limit') && ($key eq 'default')) {
 4030:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 4031:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 4032:                                 }
 4033:                             }
 4034:                         }
 4035:                     }
 4036:                 }
 4037:                 my %roles = (
 4038:                              '0' => &Apache::lonnet::plaintext('dc'),
 4039:                             ); 
 4040:             
 4041:                 foreach my $type (@types) {
 4042:                     unless (($row eq 'registered') && ($key eq 'default')) {
 4043:                         $datatable .= '<th>'.&mt($type).'</th>';
 4044:                     }
 4045:                 }
 4046:                 unless (($row eq 'registered') && ($key eq 'default')) {
 4047:                     $datatable .= '</tr><tr>';
 4048:                 }
 4049:                 foreach my $type (@types) {
 4050:                     if ($type eq 'community') {
 4051:                         $roles{'1'} = &mt('Community personnel');
 4052:                     } else {
 4053:                         $roles{'1'} = &mt('Course personnel');
 4054:                     }
 4055:                     $datatable .= '<td style="vertical-align: top">';
 4056:                     if ($position eq 'top') {
 4057:                         my %checked;
 4058:                         if ($current{$type} eq '0') {
 4059:                             $checked{'0'} = ' checked="checked"';
 4060:                         } else {
 4061:                             $checked{'1'} = ' checked="checked"';
 4062:                         }
 4063:                         foreach my $role ('1','0') {
 4064:                             $datatable .= '<span class="LC_nobreak"><label>'.
 4065:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 4066:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 4067:                                           $roles{$role}.'</label></span> ';
 4068:                         }
 4069:                     } else {
 4070:                         if ($row eq 'types') {
 4071:                             my %checked;
 4072:                             if ($current{$type} =~ /^(all|dom)$/) {
 4073:                                 $checked{$1} = ' checked="checked"';
 4074:                             } else {
 4075:                                 $checked{''} = ' checked="checked"';
 4076:                             }
 4077:                             foreach my $val ('','dom','all') {
 4078:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 4079:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 4080:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 4081:                             }
 4082:                         } elsif ($row eq 'registered') {
 4083:                             my %checked;
 4084:                             if ($current{$type} eq '1') {
 4085:                                 $checked{'1'} = ' checked="checked"';
 4086:                             } else {
 4087:                                 $checked{'0'} = ' checked="checked"';
 4088:                             }
 4089:                             foreach my $val ('0','1') {
 4090:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 4091:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 4092:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 4093:                             }
 4094:                         } elsif ($row eq 'approval') {
 4095:                             my %checked;
 4096:                             if ($current{$type} =~ /^([12])$/) {
 4097:                                 $checked{$1} = ' checked="checked"';
 4098:                             } else {
 4099:                                 $checked{'0'} = ' checked="checked"';
 4100:                             }
 4101:                             for my $val (0..2) {
 4102:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 4103:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 4104:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 4105:                             }
 4106:                         } elsif ($row eq 'limit') {
 4107:                             my %checked;
 4108:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 4109:                                 $checked{$1} = ' checked="checked"';
 4110:                             } else {
 4111:                                 $checked{'none'} = ' checked="checked"';
 4112:                             }
 4113:                             my $cap;
 4114:                             if ($currentcap{$type} =~ /^\d+$/) {
 4115:                                 $cap = $currentcap{$type};
 4116:                             }
 4117:                             foreach my $val ('none','allstudents','selfenrolled') {
 4118:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 4119:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 4120:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 4121:                             }
 4122:                             $datatable .= '<br />'.
 4123:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 4124:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 4125:                                           '</span>'; 
 4126:                         }
 4127:                     }
 4128:                     $datatable .= '</td>';
 4129:                 }
 4130:                 $datatable .= '</tr>';
 4131:             }
 4132:             $datatable .= '</table></td></tr>';
 4133:         }
 4134:     } elsif ($position eq 'bottom') {
 4135:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 4136:     }
 4137:     $$rowtotal += $itemcount;
 4138:     return $datatable;
 4139: }
 4140: 
 4141: sub print_validation_rows {
 4142:     my ($caller,$dom,$settings,$rowtotal) = @_;
 4143:     my ($itemsref,$namesref,$fieldsref);
 4144:     if ($caller eq 'selfenroll') { 
 4145:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 4146:     } elsif ($caller eq 'requestcourses') {
 4147:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 4148:     }
 4149:     my %currvalidation;
 4150:     if (ref($settings) eq 'HASH') {
 4151:         if (ref($settings->{'validation'}) eq 'HASH') {
 4152:             %currvalidation = %{$settings->{'validation'}};
 4153:         }
 4154:     }
 4155:     my $datatable;
 4156:     my $itemcount = 0;
 4157:     foreach my $item (@{$itemsref}) {
 4158:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4159:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 4160:                       $namesref->{$item}.
 4161:                       '</span></td>'.
 4162:                       '<td class="LC_left_item">';
 4163:         if (($item eq 'url') || ($item eq 'button')) {
 4164:             $datatable .= '<span class="LC_nobreak">'.
 4165:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 4166:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 4167:         } elsif ($item eq 'fields') {
 4168:             my @currfields;
 4169:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 4170:                 @currfields = @{$currvalidation{$item}};
 4171:             }
 4172:             foreach my $field (@{$fieldsref}) {
 4173:                 my $check = '';
 4174:                 if (grep(/^\Q$field\E$/,@currfields)) {
 4175:                     $check = ' checked="checked"';
 4176:                 }
 4177:                 $datatable .= '<span class="LC_nobreak"><label>'.
 4178:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 4179:                               ' value="'.$field.'"'.$check.' />'.$field.
 4180:                               '</label></span> ';
 4181:             }
 4182:         } elsif ($item eq 'markup') {
 4183:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 4184:                            $currvalidation{$item}.
 4185:                               '</textarea>';
 4186:         }
 4187:         $datatable .= '</td></tr>'."\n";
 4188:         if (ref($rowtotal)) {
 4189:             $itemcount ++;
 4190:         }
 4191:     }
 4192:     if ($caller eq 'requestcourses') {
 4193:         my %currhash;
 4194:         if (ref($settings) eq 'HASH') {
 4195:             if (ref($settings->{'validation'}) eq 'HASH') {
 4196:                 if ($settings->{'validation'}{'dc'} ne '') {
 4197:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 4198:                 }
 4199:             }
 4200:         }
 4201:         my $numinrow = 2;
 4202:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 4203:                                                        'validationdc',%currhash);
 4204:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4205:         $datatable .= '<tr'.$css_class.'><td>';
 4206:         if ($numdc > 1) {
 4207:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 4208:         } else {
 4209:             $datatable .=  &mt('Course creation processed as: ');
 4210:         }
 4211:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 4212:         $itemcount ++;
 4213:     }
 4214:     if (ref($rowtotal)) {
 4215:         $$rowtotal += $itemcount;
 4216:     }
 4217:     return $datatable;
 4218: }
 4219: 
 4220: sub print_passwords {
 4221:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 4222:     my ($datatable,$css_class);
 4223:     my $itemcount = 0;
 4224:     my %titles = &Apache::lonlocal::texthash (
 4225:         captcha        => '"Forgot Password" CAPTCHA validation',
 4226:         link           => 'Reset link expiration (hours)',
 4227:         case           => 'Case-sensitive usernames/e-mail',
 4228:         prelink        => 'Information required (form 1)',
 4229:         postlink       => 'Information required (form 2)',
 4230:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 4231:         customtext     => 'Domain specific text (HTML)',
 4232:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 4233:         intauth_check  => 'Check bcrypt cost if authenticated',
 4234:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 4235:         permanent      => 'Permanent e-mail address',
 4236:         critical       => 'Critical notification address',
 4237:         notify         => 'Notification address',
 4238:         min            => 'Minimum password length',
 4239:         max            => 'Maximum password length',
 4240:         chars          => 'Required characters',
 4241:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 4242:     );
 4243:     if ($position eq 'top') {
 4244:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4245:         my $shownlinklife = 2;
 4246:         my $prelink = 'both';
 4247:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 4248:         if (ref($settings) eq 'HASH') {
 4249:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 4250:                 $shownlinklife = $settings->{resetlink};
 4251:             }
 4252:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 4253:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 4254:             }
 4255:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 4256:                 $prelink = $settings->{resetprelink};
 4257:             }
 4258:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 4259:                 %postlink = %{$settings->{resetpostlink}};
 4260:             }
 4261:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 4262:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 4263:             }
 4264:             if ($settings->{resetremove}) {
 4265:                 $nostdtext = 1;
 4266:             }
 4267:             if ($settings->{resetcustom}) {
 4268:                 $customurl = $settings->{resetcustom};
 4269:             }
 4270:         } else {
 4271:             if (ref($types) eq 'ARRAY') {
 4272:                 foreach my $item (@{$types}) {
 4273:                     $casesens{$item} = 1;
 4274:                     $postlink{$item} = ['username','email'];
 4275:                 }
 4276:             }
 4277:             $casesens{'default'} = 1;
 4278:             $postlink{'default'} = ['username','email'];
 4279:             $prelink = 'both';
 4280:             %emailsrc = (
 4281:                           permanent => 1,
 4282:                           critical  => 1,
 4283:                           notify    => 1,
 4284:             );
 4285:         }
 4286:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 4287:         $itemcount ++;
 4288:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4289:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 4290:                       '<td class="LC_left_item">'.
 4291:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 4292:                       'name="passwords_link" size="3" /></td></tr>';
 4293:         $itemcount ++;
 4294:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4295:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 4296:                       '<td class="LC_left_item">';
 4297:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 4298:             foreach my $item (@{$types}) {
 4299:                 my $checkedcase;
 4300:                 if ($casesens{$item}) {
 4301:                     $checkedcase = ' checked="checked"';
 4302:                 }
 4303:                 $datatable .= '<span class="LC_nobreak"><label>'.
 4304:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 4305:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 4306:                               '</span>&nbsp;&nbsp; ';
 4307:             }
 4308:         }
 4309:         my $checkedcase;
 4310:         if ($casesens{'default'}) {
 4311:             $checkedcase = ' checked="checked"';
 4312:         }
 4313:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 4314:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 4315:                       $othertitle.'</label></span></td>';
 4316:         $itemcount ++;
 4317:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4318:         my %checkedpre = (
 4319:                              both => ' checked="checked"',
 4320:                              either => '',
 4321:                          );
 4322:         if ($prelink eq 'either') {
 4323:             $checkedpre{either} = ' checked="checked"';
 4324:             $checkedpre{both} = '';
 4325:         }
 4326:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 4327:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 4328:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 4329:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 4330:                       '<span class="LC_nobreak"><label>'.
 4331:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 4332:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 4333:         $itemcount ++;
 4334:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4335:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 4336:                       '<td class="LC_left_item">';
 4337:         my %postlinked;
 4338:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 4339:             foreach my $item (@{$types}) {
 4340:                 undef(%postlinked);
 4341:                 $datatable .= '<fieldset style="display: inline-block;">'.
 4342:                               '<legend>'.$usertypes->{$item}.'</legend>';
 4343:                 if (ref($postlink{$item}) eq 'ARRAY') {
 4344:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 4345:                 }
 4346:                 foreach my $field ('email','username') {
 4347:                     my $checked;
 4348:                     if ($postlinked{$field}) {
 4349:                         $checked = ' checked="checked"';
 4350:                     }
 4351:                     $datatable .= '<span class="LC_nobreak"><label>'.
 4352:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 4353:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 4354:                                   '<span>&nbsp;&nbsp; ';
 4355:                 }
 4356:                 $datatable .= '</fieldset>';
 4357:             }
 4358:         }
 4359:         if (ref($postlink{'default'}) eq 'ARRAY') {
 4360:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 4361:         }
 4362:         $datatable .= '<fieldset style="display: inline-block;">'.
 4363:                       '<legend>'.$othertitle.'</legend>';
 4364:         foreach my $field ('email','username') {
 4365:             my $checked;
 4366:             if ($postlinked{$field}) {
 4367:                 $checked = ' checked="checked"';
 4368:             }
 4369:             $datatable .= '<span class="LC_nobreak"><label>'.
 4370:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 4371:                           $field.'"'.$checked.' />'.$field.'</label>'.
 4372:                           '<span>&nbsp;&nbsp; ';
 4373:         }
 4374:         $datatable .= '</fieldset></td></tr>';
 4375:         $itemcount ++;
 4376:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4377:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 4378:                       '<td class="LC_left_item">';
 4379:         foreach my $type ('permanent','critical','notify') {
 4380:             my $checkedemail;
 4381:             if ($emailsrc{$type}) {
 4382:                 $checkedemail = ' checked="checked"';
 4383:             }
 4384:             $datatable .= '<span class="LC_nobreak"><label>'.
 4385:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 4386:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 4387:                           '<span>&nbsp;&nbsp; ';
 4388:         }
 4389:         $datatable .= '</td></tr>';
 4390:         $itemcount ++;
 4391:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4392:         my $switchserver = &check_switchserver($dom,$confname);
 4393:         my ($showstd,$noshowstd);
 4394:         if ($nostdtext) {
 4395:             $noshowstd = ' checked="checked"';
 4396:         } else {
 4397:             $showstd = ' checked="checked"';
 4398:         }
 4399:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 4400:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 4401:                       &mt('Retain standard text:').
 4402:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 4403:                       &mt('Yes').'</label>'.'&nbsp;'.
 4404:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 4405:                       &mt('No').'</label></span><br />'.
 4406:                       '<span class="LC_fontsize_small">'.
 4407:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 4408:                       &mt('Include custom text:');
 4409:         if ($customurl) {
 4410:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('custom text'),600,500,
 4411:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 4412:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 4413:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 4414:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 4415:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 4416:         }
 4417:         if ($switchserver) {
 4418:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 4419:         } else {
 4420:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 4421:                          '<input type="file" name="passwords_customfile" /></span>';
 4422:         }
 4423:         $datatable .= '</td></tr>';
 4424:     } elsif ($position eq 'middle') {
 4425:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 4426:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 4427:         my %defaults;
 4428:         if (ref($domconf{'defaults'}) eq 'HASH') {
 4429:             %defaults = %{$domconf{'defaults'}};
 4430:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 4431:                 $defaults{'intauth_cost'} = 10;
 4432:             }
 4433:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 4434:                 $defaults{'intauth_check'} = 0;
 4435:             }
 4436:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 4437:                 $defaults{'intauth_switch'} = 0;
 4438:             }
 4439:         } else {
 4440:             %defaults = (
 4441:                           'intauth_cost'   => 10,
 4442:                           'intauth_check'  => 0,
 4443:                           'intauth_switch' => 0,
 4444:                         );
 4445:         }
 4446:         foreach my $item (@items) {
 4447:             if ($itemcount%2) {
 4448:                 $css_class = '';
 4449:             } else {
 4450:                 $css_class = ' class="LC_odd_row" ';
 4451:             }
 4452:             $datatable .= '<tr'.$css_class.'>'.
 4453:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 4454:                           '</span></td><td class="LC_left_item" colspan="3">';
 4455:             if ($item eq 'intauth_switch') {
 4456:                 my @options = (0,1,2);
 4457:                 my %optiondesc = &Apache::lonlocal::texthash (
 4458:                                    0 => 'No',
 4459:                                    1 => 'Yes',
 4460:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 4461:                                  );
 4462:                 $datatable .= '<table width="100%">';
 4463:                 foreach my $option (@options) {
 4464:                     my $checked = ' ';
 4465:                     if ($defaults{$item} eq $option) {
 4466:                         $checked = ' checked="checked"';
 4467:                     }
 4468:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 4469:                                   '<label><input type="radio" name="'.$item.
 4470:                                   '" value="'.$option.'"'.$checked.' />'.
 4471:                                   $optiondesc{$option}.'</label></span></td></tr>';
 4472:                 }
 4473:                 $datatable .= '</table>';
 4474:             } elsif ($item eq 'intauth_check') {
 4475:                 my @options = (0,1,2);
 4476:                 my %optiondesc = &Apache::lonlocal::texthash (
 4477:                                    0 => 'No',
 4478:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 4479:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 4480:                                  );
 4481:                 $datatable .= '<table width="100%">';
 4482:                 foreach my $option (@options) {
 4483:                     my $checked = ' ';
 4484:                     my $onclick;
 4485:                     if ($defaults{$item} eq $option) {
 4486:                         $checked = ' checked="checked"';
 4487:                     }
 4488:                     if ($option == 2) {
 4489:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 4490:                     }
 4491:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 4492:                                   '<label><input type="radio" name="'.$item.
 4493:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 4494:                                   $optiondesc{$option}.'</label></span></td></tr>';
 4495:                 }
 4496:                 $datatable .= '</table>';
 4497:             } else {
 4498:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 4499:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 4500:             }
 4501:             $datatable .= '</td></tr>';
 4502:             $itemcount ++;
 4503:         }
 4504:     } elsif ($position eq 'lower') {
 4505:         my ($min,$max,%chars,$numsaved);
 4506:         $min = $Apache::lonnet::passwdmin;
 4507:         if (ref($settings) eq 'HASH') {
 4508:             if ($settings->{min}) {
 4509:                 $min = $settings->{min};
 4510:             }
 4511:             if ($settings->{max}) {
 4512:                 $max = $settings->{max};
 4513:             }
 4514:             if (ref($settings->{chars}) eq 'ARRAY') {
 4515:                 map { $chars{$_} = 1; } (@{$settings->{chars}});
 4516:             }
 4517:             if ($settings->{numsaved}) {
 4518:                 $numsaved = $settings->{numsaved};
 4519:             }
 4520:         }
 4521:         my %rulenames = &Apache::lonlocal::texthash(
 4522:                                                      uc => 'At least one upper case letter',
 4523:                                                      lc => 'At least one lower case letter',
 4524:                                                      num => 'At least one number',
 4525:                                                      spec => 'At least one non-alphanumeric',
 4526:                                                    );
 4527:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4528:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 4529:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 4530:                       '<input type="text" name="passwords_min" value="'.$min.'" size="3" '.
 4531:                       'onblur="javascript:warnIntPass(this);" />'.
 4532:                       '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
 4533:                       '</span></td></tr>';
 4534:         $itemcount ++;
 4535:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4536:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 4537:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 4538:                       '<input type="text" name="passwords_max" value="'.$max.'" size="3" '.
 4539:                       'onblur="javascript:warnIntPass(this);" />'.
 4540:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 4541:                       '</span></td></tr>';
 4542:         $itemcount ++;
 4543:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4544:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 4545:                       '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 4546:                       '</span></td>';
 4547:         my $numinrow = 2;
 4548:         my @possrules = ('uc','lc','num','spec');
 4549:         $datatable .= '<td class="LC_left_item"><table>';
 4550:         for (my $i=0; $i<@possrules; $i++) {
 4551:             my ($rem,$checked);
 4552:             if ($chars{$possrules[$i]}) {
 4553:                 $checked = ' checked="checked"';
 4554:             }
 4555:             $rem = $i%($numinrow);
 4556:             if ($rem == 0) {
 4557:                 if ($i > 0) {
 4558:                     $datatable .= '</tr>';
 4559:                 }
 4560:                 $datatable .= '<tr>';
 4561:             }
 4562:             $datatable .= '<td><span class="LC_nobreak"><label>'.
 4563:                           '<input type="checkbox" name="passwords_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 4564:                           $rulenames{$possrules[$i]}.'</label></span></td>';
 4565:         }
 4566:         my $rem = @possrules%($numinrow);
 4567:         my $colsleft = $numinrow - $rem;
 4568:         if ($colsleft > 1 ) {
 4569:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4570:                           '&nbsp;</td>';
 4571:         } elsif ($colsleft == 1) {
 4572:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 4573:         }
 4574:         $datatable .='</table></td></tr>';
 4575:         $itemcount ++;
 4576:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4577:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 4578:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 4579:                       '<input type="text" name="passwords_numsaved" value="'.$numsaved.'" size="3" '.
 4580:                       'onblur="javascript:warnIntPass(this);" />'.
 4581:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 4582:                       '</span></td></tr>';
 4583:     } else {
 4584:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4585:         my %ownerchg = (
 4586:                           by  => {},
 4587:                           for => {},
 4588:                        );
 4589:         my %ownertitles = &Apache::lonlocal::texthash (
 4590:                             by  => 'Course owner status(es) allowed',
 4591:                             for => 'Student status(es) allowed',
 4592:                           );
 4593:         if (ref($settings) eq 'HASH') {
 4594:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 4595:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 4596:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 4597:                 }
 4598:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 4599:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 4600:                 }
 4601:             }
 4602:         }
 4603:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4604:         $datatable .= '<tr '.$css_class.'>'.
 4605:                       '<td>'.
 4606:                       &mt('Requirements').'<ul>'.
 4607:                       '<li>'.&mt("Course 'type' is not a Community").'</li>'.
 4608:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 4609:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 4610:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 4611:                       '</ul>'.
 4612:                       '</td>'.
 4613:                       '<td class="LC_left_item">';
 4614:         foreach my $item ('by','for') {
 4615:             $datatable .= '<fieldset style="display: inline-block;">'.
 4616:                           '<legend>'.$ownertitles{$item}.'</legend>';
 4617:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 4618:                 foreach my $type (@{$types}) {
 4619:                     my $checked;
 4620:                     if ($ownerchg{$item}{$type}) {
 4621:                         $checked = ' checked="checked"';
 4622:                     }
 4623:                     $datatable .= '<span class="LC_nobreak"><label>'.
 4624:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 4625:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 4626:                                   '</span>&nbsp;&nbsp; ';
 4627:                 }
 4628:             }
 4629:             my $checked;
 4630:             if ($ownerchg{$item}{'default'}) {
 4631:                 $checked = ' checked="checked"';
 4632:             }
 4633:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 4634:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 4635:                           $othertitle.'</label></span></fieldset>';
 4636:         }
 4637:         $datatable .= '</td></tr>';
 4638:     }
 4639:     return $datatable;
 4640: }
 4641: 
 4642: sub print_usersessions {
 4643:     my ($position,$dom,$settings,$rowtotal) = @_;
 4644:     my ($css_class,$datatable,%checked,%choices);
 4645:     my (%by_ip,%by_location,@intdoms);
 4646:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
 4647: 
 4648:     my @alldoms = &Apache::lonnet::all_domains();
 4649:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 4650:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 4651:     my %altids = &id_for_thisdom(%servers);
 4652:     my $itemcount = 1;
 4653:     if ($position eq 'top') {
 4654:         if (keys(%serverhomes) > 1) {
 4655:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 4656:             my ($curroffloadnow,$curroffloadoth);
 4657:             if (ref($settings) eq 'HASH') {
 4658:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 4659:                     $curroffloadnow = $settings->{'offloadnow'};
 4660:                 }
 4661:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 4662:                     $curroffloadoth = $settings->{'offloadoth'};
 4663:                 }
 4664:             }
 4665:             my $other_insts = scalar(keys(%by_location));
 4666:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 4667:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 4668:         } else {
 4669:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 4670:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.');
 4671:         }
 4672:     } else {
 4673:         if (keys(%by_location) == 0) {
 4674:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 4675:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.');
 4676:         } else {
 4677:             my %lt = &usersession_titles();
 4678:             my $numinrow = 5;
 4679:             my $prefix;
 4680:             my @types;
 4681:             if ($position eq 'bottom') {
 4682:                 $prefix = 'remote';
 4683:                 @types = ('version','excludedomain','includedomain');
 4684:             } else {
 4685:                 $prefix = 'hosted';
 4686:                 @types = ('excludedomain','includedomain');
 4687:             }
 4688:             my (%current,%checkedon,%checkedoff);
 4689:             my @lcversions = &Apache::lonnet::all_loncaparevs();
 4690:             my @locations = sort(keys(%by_location));
 4691:             foreach my $type (@types) {
 4692:                 $checkedon{$type} = '';
 4693:                 $checkedoff{$type} = ' checked="checked"';
 4694:             }
 4695:             if (ref($settings) eq 'HASH') {
 4696:                 if (ref($settings->{$prefix}) eq 'HASH') {
 4697:                     foreach my $key (keys(%{$settings->{$prefix}})) {
 4698:                         $current{$key} = $settings->{$prefix}{$key};
 4699:                         if ($key eq 'version') {
 4700:                             if ($current{$key} ne '') {
 4701:                                 $checkedon{$key} = ' checked="checked"';
 4702:                                 $checkedoff{$key} = '';
 4703:                             }
 4704:                         } elsif (ref($current{$key}) eq 'ARRAY') {
 4705:                             $checkedon{$key} = ' checked="checked"';
 4706:                             $checkedoff{$key} = '';
 4707:                         }
 4708:                     }
 4709:                 }
 4710:             }
 4711:             foreach my $type (@types) {
 4712:                 next if ($type ne 'version' && !@locations);
 4713:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4714:                 $datatable .= '<tr'.$css_class.'>
 4715:                                <td><span class="LC_nobreak">'.$lt{$type}.'</span><br />
 4716:                                <span class="LC_nobreak">&nbsp;
 4717:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 4718:                                <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 4719:                 if ($type eq 'version') {
 4720:                     my $selector = '<select name="'.$prefix.'_version">';
 4721:                     foreach my $version (@lcversions) {
 4722:                         my $selected = '';
 4723:                         if ($current{'version'} eq $version) {
 4724:                             $selected = ' selected="selected"';
 4725:                         }
 4726:                         $selector .= ' <option value="'.$version.'"'.
 4727:                                      $selected.'>'.$version.'</option>';
 4728:                     }
 4729:                     $selector .= '</select> ';
 4730:                     $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 4731:                 } else {
 4732:                     $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 4733:                                  'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 4734:                                  ' />'.('&nbsp;'x2).
 4735:                                  '<input type="button" value="'.&mt('uncheck all').'" '.
 4736:                                  'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 4737:                                  "\n".
 4738:                                  '</div><div><table>';
 4739:                     my $rem;
 4740:                     for (my $i=0; $i<@locations; $i++) {
 4741:                         my ($showloc,$value,$checkedtype);
 4742:                         if (ref($by_location{$locations[$i]}) eq 'ARRAY') {
 4743:                             my $ip = $by_location{$locations[$i]}->[0];
 4744:                             if (ref($by_ip{$ip}) eq 'ARRAY') {
 4745:                                  $value = join(':',@{$by_ip{$ip}});
 4746:                                 $showloc = join(', ',@{$by_ip{$ip}});
 4747:                                 if (ref($current{$type}) eq 'ARRAY') {
 4748:                                     foreach my $loc (@{$by_ip{$ip}}) {  
 4749:                                         if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 4750:                                             $checkedtype = ' checked="checked"';
 4751:                                             last;
 4752:                                         }
 4753:                                     }
 4754:                                 }
 4755:                             }
 4756:                         }
 4757:                         $rem = $i%($numinrow);
 4758:                         if ($rem == 0) {
 4759:                             if ($i > 0) {
 4760:                                 $datatable .= '</tr>';
 4761:                             }
 4762:                             $datatable .= '<tr>';
 4763:                         }
 4764:                         $datatable .= '<td class="LC_left_item">'.
 4765:                                       '<span class="LC_nobreak"><label>'.
 4766:                                       '<input type="checkbox" name="'.$prefix.'_'.$type.
 4767:                                       '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 4768:                                       '</label></span></td>';
 4769:                     }
 4770:                     $rem = @locations%($numinrow);
 4771:                     my $colsleft = $numinrow - $rem;
 4772:                     if ($colsleft > 1 ) {
 4773:                         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4774:                                       '&nbsp;</td>';
 4775:                     } elsif ($colsleft == 1) {
 4776:                         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 4777:                     }
 4778:                     $datatable .= '</tr></table>';
 4779:                 }
 4780:                 $datatable .= '</td></tr>';
 4781:                 $itemcount ++;
 4782:             }
 4783:         }
 4784:     }
 4785:     $$rowtotal += $itemcount;
 4786:     return $datatable;
 4787: }
 4788: 
 4789: sub build_location_hashes {
 4790:     my ($intdoms,$by_ip,$by_location) = @_;
 4791:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 4792:                   (ref($by_location) eq 'HASH')); 
 4793:     my %iphost = &Apache::lonnet::get_iphost();
 4794:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 4795:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 4796:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 4797:         foreach my $id (@{$iphost{$primary_ip}}) {
 4798:             my $intdom = &Apache::lonnet::internet_dom($id);
 4799:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 4800:                 push(@{$intdoms},$intdom);
 4801:             }
 4802:         }
 4803:     }
 4804:     foreach my $ip (keys(%iphost)) {
 4805:         if (ref($iphost{$ip}) eq 'ARRAY') {
 4806:             foreach my $id (@{$iphost{$ip}}) {
 4807:                 my $location = &Apache::lonnet::internet_dom($id);
 4808:                 if ($location) {
 4809:                     next if (grep(/^\Q$location\E$/,@{$intdoms}));
 4810:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 4811:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 4812:                             push(@{$by_ip->{$ip}},$location);
 4813:                         }
 4814:                     } else {
 4815:                         $by_ip->{$ip} = [$location];
 4816:                     }
 4817:                 }
 4818:             }
 4819:         }
 4820:     }
 4821:     foreach my $ip (sort(keys(%{$by_ip}))) {
 4822:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 4823:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 4824:             my $first = $by_ip->{$ip}->[0];
 4825:             if (ref($by_location->{$first}) eq 'ARRAY') {
 4826:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 4827:                     push(@{$by_location->{$first}},$ip);
 4828:                 }
 4829:             } else {
 4830:                 $by_location->{$first} = [$ip];
 4831:             }
 4832:         }
 4833:     }
 4834:     return;
 4835: }
 4836: 
 4837: sub current_offloads_to {
 4838:     my ($dom,$settings,$servers) = @_;
 4839:     my (%spareid,%otherdomconfigs);
 4840:     if (ref($servers) eq 'HASH') {
 4841:         foreach my $lonhost (sort(keys(%{$servers}))) {
 4842:             my $gotspares;
 4843:             if (ref($settings) eq 'HASH') {
 4844:                 if (ref($settings->{'spares'}) eq 'HASH') {
 4845:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 4846:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 4847:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 4848:                         $gotspares = 1;
 4849:                     }
 4850:                 }
 4851:             }
 4852:             unless ($gotspares) {
 4853:                 my $gotspares;
 4854:                 my $serverhomeID =
 4855:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 4856:                 my $serverhomedom =
 4857:                     &Apache::lonnet::host_domain($serverhomeID);
 4858:                 if ($serverhomedom ne $dom) {
 4859:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 4860:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 4861:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 4862:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 4863:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 4864:                                 $gotspares = 1;
 4865:                             }
 4866:                         }
 4867:                     } else {
 4868:                         $otherdomconfigs{$serverhomedom} =
 4869:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 4870:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 4871:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 4872:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 4873:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 4874:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 4875:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 4876:                                         $gotspares = 1;
 4877:                                     }
 4878:                                 }
 4879:                             }
 4880:                         }
 4881:                     }
 4882:                 }
 4883:             }
 4884:             unless ($gotspares) {
 4885:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 4886:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 4887:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 4888:                } else {
 4889:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 4890:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 4891:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 4892:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 4893:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 4894:                     } else {
 4895:                         my %what = (
 4896:                              spareid => 1,
 4897:                         );
 4898:                         my ($result,$returnhash) = 
 4899:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 4900:                         if ($result eq 'ok') { 
 4901:                             if (ref($returnhash) eq 'HASH') {
 4902:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 4903:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 4904:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 4905:                                 }
 4906:                             }
 4907:                         }
 4908:                     }
 4909:                 }
 4910:             }
 4911:         }
 4912:     }
 4913:     return %spareid;
 4914: }
 4915: 
 4916: sub spares_row {
 4917:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 4918:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 4919:     my $css_class;
 4920:     my $numinrow = 4;
 4921:     my $itemcount = 1;
 4922:     my $datatable;
 4923:     my %typetitles = &sparestype_titles();
 4924:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 4925:         foreach my $server (sort(keys(%{$servers}))) {
 4926:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 4927:             my ($othercontrol,$serverdom);
 4928:             if ($serverhome ne $server) {
 4929:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 4930:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 4931:             } else {
 4932:                 $serverdom = &Apache::lonnet::host_domain($server);
 4933:                 if ($serverdom ne $dom) {
 4934:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 4935:                 }
 4936:             }
 4937:             next unless (ref($spareid->{$server}) eq 'HASH');
 4938:             my ($checkednow,$checkedoth);
 4939:             if (ref($curroffloadnow) eq 'HASH') {
 4940:                 if ($curroffloadnow->{$server}) {
 4941:                     $checkednow = ' checked="checked"';
 4942:                 }
 4943:             }
 4944:             if (ref($curroffloadoth) eq 'HASH') {
 4945:                 if ($curroffloadoth->{$server}) {
 4946:                     $checkedoth = ' checked="checked"';
 4947:                 }
 4948:             }
 4949:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 4950:             $datatable .= '<tr'.$css_class.'>
 4951:                            <td rowspan="2">
 4952:                             <span class="LC_nobreak">'.
 4953:                           &mt('[_1] when busy, offloads to:'
 4954:                               ,'<b>'.$server.'</b>').'</span><br />'.
 4955:                           '<span class="LC_nobreak">'."\n".
 4956:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 4957:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 4958:                           "\n";
 4959:             if ($other_insts) {
 4960:                 $datatable .= '<br />'.
 4961:                               '<span class="LC_nobreak">'."\n".
 4962:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 4963:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 4964:                           "\n";
 4965:             }
 4966:             my (%current,%canselect);
 4967:             my @choices = 
 4968:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 4969:             foreach my $type ('primary','default') {
 4970:                 if (ref($spareid->{$server}) eq 'HASH') {
 4971:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 4972:                         my @spares = @{$spareid->{$server}{$type}};
 4973:                         if (@spares > 0) {
 4974:                             if ($othercontrol) {
 4975:                                 $current{$type} = join(', ',@spares);
 4976:                             } else {
 4977:                                 $current{$type} .= '<table>';
 4978:                                 my $numspares = scalar(@spares);
 4979:                                 for (my $i=0;  $i<@spares; $i++) {
 4980:                                     my $rem = $i%($numinrow);
 4981:                                     if ($rem == 0) {
 4982:                                         if ($i > 0) {
 4983:                                             $current{$type} .= '</tr>';
 4984:                                         }
 4985:                                         $current{$type} .= '<tr>';
 4986:                                     }
 4987:                                     $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;'.
 4988:                                                        $spareid->{$server}{$type}[$i].
 4989:                                                        '</label></td>'."\n";
 4990:                                 }
 4991:                                 my $rem = @spares%($numinrow);
 4992:                                 my $colsleft = $numinrow - $rem;
 4993:                                 if ($colsleft > 1 ) {
 4994:                                     $current{$type} .= '<td colspan="'.$colsleft.
 4995:                                                        '" class="LC_left_item">'.
 4996:                                                        '&nbsp;</td>';
 4997:                                 } elsif ($colsleft == 1) {
 4998:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 4999:                                 }
 5000:                                 $current{$type} .= '</tr></table>';
 5001:                             }
 5002:                         }
 5003:                     }
 5004:                     if ($current{$type} eq '') {
 5005:                         $current{$type} = &mt('None specified');
 5006:                     }
 5007:                     if ($othercontrol) {
 5008:                         if ($type eq 'primary') {
 5009:                             $canselect{$type} = $othercontrol;
 5010:                         }
 5011:                     } else {
 5012:                         $canselect{$type} = 
 5013:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 5014:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 5015:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 5016:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 5017:                         if (@choices > 0) {
 5018:                             foreach my $lonhost (@choices) {
 5019:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 5020:                             }
 5021:                         }
 5022:                         $canselect{$type} .= '</select>'."\n";
 5023:                     }
 5024:                 } else {
 5025:                     $current{$type} = &mt('Could not be determined');
 5026:                     if ($type eq 'primary') {
 5027:                         $canselect{$type} =  $othercontrol;
 5028:                     }
 5029:                 }
 5030:                 if ($type eq 'default') {
 5031:                     $datatable .= '<tr'.$css_class.'>';
 5032:                 }
 5033:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 5034:                               '<td>'.$current{$type}.'</td>'."\n".
 5035:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 5036:             }
 5037:             $itemcount ++;
 5038:         }
 5039:     }
 5040:     $$rowtotal += $itemcount;
 5041:     return $datatable;
 5042: }
 5043: 
 5044: sub possible_newspares {
 5045:     my ($server,$currspares,$serverhomes,$altids) = @_;
 5046:     my $serverhostname = &Apache::lonnet::hostname($server);
 5047:     my %excluded;
 5048:     if ($serverhostname ne '') {
 5049:         %excluded = (
 5050:                        $serverhostname => 1,
 5051:                     );
 5052:     }
 5053:     if (ref($currspares) eq 'HASH') {
 5054:         foreach my $type (keys(%{$currspares})) {
 5055:             if (ref($currspares->{$type}) eq 'ARRAY') {
 5056:                 if (@{$currspares->{$type}} > 0) {
 5057:                     foreach my $curr (@{$currspares->{$type}}) {
 5058:                         my $hostname = &Apache::lonnet::hostname($curr);
 5059:                         $excluded{$hostname} = 1;
 5060:                     }
 5061:                 }
 5062:             }
 5063:         }
 5064:     }
 5065:     my @choices;
 5066:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 5067:         if (keys(%{$serverhomes}) > 1) {
 5068:             foreach my $name (sort(keys(%{$serverhomes}))) {
 5069:                 unless ($excluded{$name}) {
 5070:                     if (exists($altids->{$serverhomes->{$name}})) {
 5071:                         push(@choices,$altids->{$serverhomes->{$name}});
 5072:                     } else {
 5073:                         push(@choices,$serverhomes->{$name});
 5074:                     }
 5075:                 }
 5076:             }
 5077:         }
 5078:     }
 5079:     return sort(@choices);
 5080: }
 5081: 
 5082: sub print_loadbalancing {
 5083:     my ($dom,$settings,$rowtotal) = @_;
 5084:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 5085:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 5086:     my $numinrow = 1;
 5087:     my $datatable;
 5088:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 5089:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 5090:     if (ref($settings) eq 'HASH') {
 5091:         %existing = %{$settings};
 5092:     }
 5093:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 5094:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 5095:                                   \%currtargets,\%currrules,\%currcookies);
 5096:     } else {
 5097:         return;
 5098:     }
 5099:     my ($othertitle,$usertypes,$types) =
 5100:         &Apache::loncommon::sorted_inst_types($dom);
 5101:     my $rownum = 8;
 5102:     if (ref($types) eq 'ARRAY') {
 5103:         $rownum += scalar(@{$types});
 5104:     }
 5105:     my @css_class = ('LC_odd_row','LC_even_row');
 5106:     my $balnum = 0;
 5107:     my $islast;
 5108:     my (@toshow,$disabledtext);
 5109:     if (keys(%currbalancer) > 0) {
 5110:         @toshow = sort(keys(%currbalancer));
 5111:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 5112:             push(@toshow,'');
 5113:         }
 5114:     } else {
 5115:         @toshow = ('');
 5116:         $disabledtext = &mt('No existing load balancer');
 5117:     }
 5118:     foreach my $lonhost (@toshow) {
 5119:         if ($balnum == scalar(@toshow)-1) {
 5120:             $islast = 1;
 5121:         } else {
 5122:             $islast = 0;
 5123:         }
 5124:         my $cssidx = $balnum%2;
 5125:         my $targets_div_style = 'display: none';
 5126:         my $disabled_div_style = 'display: block';
 5127:         my $homedom_div_style = 'display: none';
 5128:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 5129:                       '<td rowspan="'.$rownum.'" valign="top">'.
 5130:                       '<p>';
 5131:         if ($lonhost eq '') {
 5132:             $datatable .= '<span class="LC_nobreak">';
 5133:             if (keys(%currbalancer) > 0) {
 5134:                 $datatable .= &mt('Add balancer:');
 5135:             } else {
 5136:                 $datatable .= &mt('Enable balancer:');
 5137:             }
 5138:             $datatable .= '&nbsp;'.
 5139:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 5140:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 5141:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 5142:                           '<option value="" selected="selected">'.&mt('None').
 5143:                           '</option>'."\n";
 5144:             foreach my $server (sort(keys(%servers))) {
 5145:                 next if ($currbalancer{$server});
 5146:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 5147:             }
 5148:             $datatable .=
 5149:                 '</select>'."\n".
 5150:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 5151:         } else {
 5152:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 5153:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 5154:                            &mt('Stop balancing').'</label>'.
 5155:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 5156:             $targets_div_style = 'display: block';
 5157:             $disabled_div_style = 'display: none';
 5158:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 5159:                 $homedom_div_style = 'display: block';
 5160:             }
 5161:         }
 5162:         $datatable .= '</p></td><td rowspan="'.$rownum.'" valign="top">'.
 5163:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 5164:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 5165:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 5166:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 5167:         my @sparestypes = ('primary','default');
 5168:         my %typetitles = &sparestype_titles();
 5169:         my %hostherechecked = (
 5170:                                   no => ' checked="checked"',
 5171:                               );
 5172:         my %balcookiechecked = (
 5173:                                   no => ' checked="checked"',
 5174:                                );
 5175:         foreach my $sparetype (@sparestypes) {
 5176:             my $targettable;
 5177:             for (my $i=0; $i<$numspares; $i++) {
 5178:                 my $checked;
 5179:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 5180:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 5181:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 5182:                             $checked = ' checked="checked"';
 5183:                         }
 5184:                     }
 5185:                 }
 5186:                 my ($chkboxval,$disabled);
 5187:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 5188:                     $chkboxval = $spares[$i];
 5189:                 }
 5190:                 if (exists($currbalancer{$spares[$i]})) {
 5191:                     $disabled = ' disabled="disabled"';
 5192:                 }
 5193:                 $targettable .=
 5194:                     '<td><span class="LC_nobreak"><label>'.
 5195:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 5196:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 5197:                     '</span></label></span></td>';
 5198:                 my $rem = $i%($numinrow);
 5199:                 if ($rem == 0) {
 5200:                     if (($i > 0) && ($i < $numspares-1)) {
 5201:                         $targettable .= '</tr>';
 5202:                     }
 5203:                     if ($i < $numspares-1) {
 5204:                         $targettable .= '<tr>';
 5205:                     }
 5206:                 }
 5207:             }
 5208:             if ($targettable ne '') {
 5209:                 my $rem = $numspares%($numinrow);
 5210:                 my $colsleft = $numinrow - $rem;
 5211:                 if ($colsleft > 1 ) {
 5212:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 5213:                                     '&nbsp;</td>';
 5214:                 } elsif ($colsleft == 1) {
 5215:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 5216:                 }
 5217:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 5218:                                '<table><tr>'.$targettable.'</tr></table><br />';
 5219:             }
 5220:             $hostherechecked{$sparetype} = '';
 5221:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 5222:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 5223:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 5224:                         $hostherechecked{$sparetype} = ' checked="checked"';
 5225:                         $hostherechecked{'no'} = '';
 5226:                     }
 5227:                 }
 5228:             }
 5229:         }
 5230:         if ($currcookies{$lonhost}) {
 5231:             %balcookiechecked = (
 5232:                                     yes => ' checked="checked"',
 5233:                                 );
 5234:         }
 5235:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 5236:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 5237:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 5238:         foreach my $sparetype (@sparestypes) {
 5239:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 5240:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 5241:                           '</i></label><br />';
 5242:         }
 5243:         $datatable .= &mt('Use balancer cookie').'<br />'.
 5244:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 5245:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 5246:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 5247:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 5248:                       '</div></td></tr>'.
 5249:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 5250:                                            $othertitle,$usertypes,$types,\%servers,
 5251:                                            \%currbalancer,$lonhost,
 5252:                                            $targets_div_style,$homedom_div_style,
 5253:                                            $css_class[$cssidx],$balnum,$islast);
 5254:         $$rowtotal += $rownum;
 5255:         $balnum ++;
 5256:     }
 5257:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 5258:     return $datatable;
 5259: }
 5260: 
 5261: sub get_loadbalancers_config {
 5262:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 5263:     return unless ((ref($servers) eq 'HASH') &&
 5264:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 5265:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 5266:                    (ref($currcookies) eq 'HASH'));
 5267:     if (keys(%{$existing}) > 0) {
 5268:         my $oldlonhost;
 5269:         foreach my $key (sort(keys(%{$existing}))) {
 5270:             if ($key eq 'lonhost') {
 5271:                 $oldlonhost = $existing->{'lonhost'};
 5272:                 $currbalancer->{$oldlonhost} = 1;
 5273:             } elsif ($key eq 'targets') {
 5274:                 if ($oldlonhost) {
 5275:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 5276:                 }
 5277:             } elsif ($key eq 'rules') {
 5278:                 if ($oldlonhost) {
 5279:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 5280:                 }
 5281:             } elsif (ref($existing->{$key}) eq 'HASH') {
 5282:                 $currbalancer->{$key} = 1;
 5283:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 5284:                 $currrules->{$key} = $existing->{$key}{'rules'};
 5285:                 if ($existing->{$key}{'cookie'}) {
 5286:                     $currcookies->{$key} = 1;
 5287:                 }
 5288:             }
 5289:         }
 5290:     } else {
 5291:         my ($balancerref,$targetsref) =
 5292:                 &Apache::lonnet::get_lonbalancer_config($servers);
 5293:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 5294:             foreach my $server (sort(keys(%{$balancerref}))) {
 5295:                 $currbalancer->{$server} = 1;
 5296:                 $currtargets->{$server} = $targetsref->{$server};
 5297:             }
 5298:         }
 5299:     }
 5300:     return;
 5301: }
 5302: 
 5303: sub loadbalancing_rules {
 5304:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 5305:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 5306:         $css_class,$balnum,$islast) = @_;
 5307:     my $output;
 5308:     my $num = 0;
 5309:     my ($alltypes,$othertypes,$titles) =
 5310:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 5311:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 5312:         foreach my $type (@{$alltypes}) {
 5313:             $num ++;
 5314:             my $current;
 5315:             if (ref($currrules) eq 'HASH') {
 5316:                 $current = $currrules->{$type};
 5317:             }
 5318:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 5319:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 5320:                     $current = '';
 5321:                 }
 5322:             }
 5323:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 5324:                                              $servers,$currbalancer,$lonhost,$dom,
 5325:                                              $targets_div_style,$homedom_div_style,
 5326:                                              $css_class,$balnum,$num,$islast);
 5327:         }
 5328:     }
 5329:     return $output;
 5330: }
 5331: 
 5332: sub loadbalancing_titles {
 5333:     my ($dom,$intdom,$usertypes,$types) = @_;
 5334:     my %othertypes = (
 5335:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 5336:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 5337:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 5338:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 5339:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 5340:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 5341:                      );
 5342:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 5343:     my @available;
 5344:     if (ref($types) eq 'ARRAY') {
 5345:         @available = @{$types};
 5346:     }
 5347:     unless (grep(/^default$/,@available)) {
 5348:         push(@available,'default');
 5349:     }
 5350:     unshift(@alltypes,@available);
 5351:     my %titles;
 5352:     foreach my $type (@alltypes) {
 5353:         if ($type =~ /^_LC_/) {
 5354:             $titles{$type} = $othertypes{$type};
 5355:         } elsif ($type eq 'default') {
 5356:             $titles{$type} = &mt('All users from [_1]',$dom);
 5357:             if (ref($types) eq 'ARRAY') {
 5358:                 if (@{$types} > 0) {
 5359:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 5360:                 }
 5361:             }
 5362:         } elsif (ref($usertypes) eq 'HASH') {
 5363:             $titles{$type} = $usertypes->{$type};
 5364:         }
 5365:     }
 5366:     return (\@alltypes,\%othertypes,\%titles);
 5367: }
 5368: 
 5369: sub loadbalance_rule_row {
 5370:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 5371:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 5372:     my @rulenames;
 5373:     my %ruletitles = &offloadtype_text();
 5374:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 5375:         @rulenames = ('balancer','offloadedto','specific');
 5376:     } else {
 5377:         @rulenames = ('default','homeserver');
 5378:         if ($type eq '_LC_external') {
 5379:             push(@rulenames,'externalbalancer');
 5380:         } else {
 5381:             push(@rulenames,'specific');
 5382:         }
 5383:         push(@rulenames,'none');
 5384:     }
 5385:     my $style = $targets_div_style;
 5386:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 5387:         $style = $homedom_div_style;
 5388:     }
 5389:     my $space;
 5390:     if ($islast && $num == 1) {
 5391:         $space = '<div display="inline-block">&nbsp;</div>';
 5392:     }
 5393:     my $output =
 5394:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td valign="top">'.$space.
 5395:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 5396:         '<td valaign="top">'.$space.
 5397:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 5398:     for (my $i=0; $i<@rulenames; $i++) {
 5399:         my $rule = $rulenames[$i];
 5400:         my ($checked,$extra);
 5401:         if ($rulenames[$i] eq 'default') {
 5402:             $rule = '';
 5403:         }
 5404:         if ($rulenames[$i] eq 'specific') {
 5405:             if (ref($servers) eq 'HASH') {
 5406:                 my $default;
 5407:                 if (($current ne '') && (exists($servers->{$current}))) {
 5408:                     $checked = ' checked="checked"';
 5409:                 }
 5410:                 unless ($checked) {
 5411:                     $default = ' selected="selected"';
 5412:                 }
 5413:                 $extra =
 5414:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 5415:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 5416:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 5417:                     '<option value=""'.$default.'></option>'."\n";
 5418:                 foreach my $server (sort(keys(%{$servers}))) {
 5419:                     if (ref($currbalancer) eq 'HASH') {
 5420:                         next if (exists($currbalancer->{$server}));
 5421:                     }
 5422:                     my $selected;
 5423:                     if ($server eq $current) {
 5424:                         $selected = ' selected="selected"';
 5425:                     }
 5426:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 5427:                 }
 5428:                 $extra .= '</select>';
 5429:             }
 5430:         } elsif ($rule eq $current) {
 5431:             $checked = ' checked="checked"';
 5432:         }
 5433:         $output .= '<span class="LC_nobreak"><label>'.
 5434:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 5435:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 5436:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 5437:                    ')"'.$checked.' />&nbsp;';
 5438:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 5439:             $output .= $ruletitles{'particular'};
 5440:         } else {
 5441:             $output .= $ruletitles{$rulenames[$i]};
 5442:         }
 5443:         $output .= '</label>'.$extra.'</span><br />'."\n";
 5444:     }
 5445:     $output .= '</div></td></tr>'."\n";
 5446:     return $output;
 5447: }
 5448: 
 5449: sub offloadtype_text {
 5450:     my %ruletitles = &Apache::lonlocal::texthash (
 5451:            'default'          => 'Offloads to default destinations',
 5452:            'homeserver'       => "Offloads to user's home server",
 5453:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 5454:            'specific'         => 'Offloads to specific server',
 5455:            'none'             => 'No offload',
 5456:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 5457:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 5458:            'particular'       => 'Session hosted (after re-auth) on server:',
 5459:     );
 5460:     return %ruletitles;
 5461: }
 5462: 
 5463: sub sparestype_titles {
 5464:     my %typestitles = &Apache::lonlocal::texthash (
 5465:                           'primary' => 'primary',
 5466:                           'default' => 'default',
 5467:                       );
 5468:     return %typestitles;
 5469: }
 5470: 
 5471: sub contact_titles {
 5472:     my %titles = &Apache::lonlocal::texthash (
 5473:                    'supportemail'    => 'Support E-mail address',
 5474:                    'adminemail'      => 'Default Server Admin E-mail address',
 5475:                    'errormail'       => 'Error reports to be e-mailed to',
 5476:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 5477:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 5478:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 5479:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 5480:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 5481:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 5482:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 5483:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 5484:                  );
 5485:     my %short_titles = &Apache::lonlocal::texthash (
 5486:                            adminemail   => 'Admin E-mail address',
 5487:                            supportemail => 'Support E-mail',
 5488:                        );   
 5489:     return (\%titles,\%short_titles);
 5490: }
 5491: 
 5492: sub helpform_fields {
 5493:     my %titles =  &Apache::lonlocal::texthash (
 5494:                        'username'   => 'Name',
 5495:                        'user'       => 'Username/domain',
 5496:                        'phone'      => 'Phone',
 5497:                        'cc'         => 'Cc e-mail',
 5498:                        'course'     => 'Course Details',
 5499:                        'section'    => 'Sections',
 5500:                        'screenshot' => 'File upload',
 5501:     );
 5502:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 5503:     my %possoptions = (
 5504:                         username     => ['yes','no','req'],
 5505:                         phone        => ['yes','no','req'],
 5506:                         user         => ['yes','no'],
 5507:                         cc           => ['yes','no'],
 5508:                         course       => ['yes','no'],
 5509:                         section      => ['yes','no'],
 5510:                         screenshot   => ['yes','no'],
 5511:                       );
 5512:     my %fieldoptions = &Apache::lonlocal::texthash (
 5513:                          'yes'  => 'Optional',
 5514:                          'req'  => 'Required',
 5515:                          'no'   => "Not shown",
 5516:     );
 5517:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 5518: }
 5519: 
 5520: sub tool_titles {
 5521:     my %titles = &Apache::lonlocal::texthash (
 5522:                      aboutme    => 'Personal web page',
 5523:                      blog       => 'Blog',
 5524:                      webdav     => 'WebDAV',
 5525:                      portfolio  => 'Portfolio',
 5526:                      official   => 'Official courses (with institutional codes)',
 5527:                      unofficial => 'Unofficial courses',
 5528:                      community  => 'Communities',
 5529:                      textbook   => 'Textbook courses',
 5530:                  );
 5531:     return %titles;
 5532: }
 5533: 
 5534: sub courserequest_titles {
 5535:     my %titles = &Apache::lonlocal::texthash (
 5536:                                    official   => 'Official',
 5537:                                    unofficial => 'Unofficial',
 5538:                                    community  => 'Communities',
 5539:                                    textbook   => 'Textbook',
 5540:                                    norequest  => 'Not allowed',
 5541:                                    approval   => 'Approval by Dom. Coord.',
 5542:                                    validate   => 'With validation',
 5543:                                    autolimit  => 'Numerical limit',
 5544:                                    unlimited  => '(blank for unlimited)',
 5545:                  );
 5546:     return %titles;
 5547: }
 5548: 
 5549: sub authorrequest_titles {
 5550:     my %titles = &Apache::lonlocal::texthash (
 5551:                                    norequest  => 'Not allowed',
 5552:                                    approval   => 'Approval by Dom. Coord.',
 5553:                                    automatic  => 'Automatic approval',
 5554:                  );
 5555:     return %titles;
 5556: }
 5557: 
 5558: sub courserequest_conditions {
 5559:     my %conditions = &Apache::lonlocal::texthash (
 5560:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 5561:        validate   => '(Processing of request subject to institutional validation).',
 5562:                  );
 5563:     return %conditions;
 5564: }
 5565: 
 5566: 
 5567: sub print_usercreation {
 5568:     my ($position,$dom,$settings,$rowtotal) = @_;
 5569:     my $numinrow = 4;
 5570:     my $datatable;
 5571:     if ($position eq 'top') {
 5572:         $$rowtotal ++;
 5573:         my $rowcount = 0;
 5574:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 5575:         if (ref($rules) eq 'HASH') {
 5576:             if (keys(%{$rules}) > 0) {
 5577:                 $datatable .= &user_formats_row('username',$settings,$rules,
 5578:                                                 $ruleorder,$numinrow,$rowcount);
 5579:                 $$rowtotal ++;
 5580:                 $rowcount ++;
 5581:             }
 5582:         }
 5583:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 5584:         if (ref($idrules) eq 'HASH') {
 5585:             if (keys(%{$idrules}) > 0) {
 5586:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 5587:                                                 $idruleorder,$numinrow,$rowcount);
 5588:                 $$rowtotal ++;
 5589:                 $rowcount ++;
 5590:             }
 5591:         }
 5592:         if ($rowcount == 0) {
 5593:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 5594:             $$rowtotal ++;
 5595:             $rowcount ++;
 5596:         }
 5597:     } elsif ($position eq 'middle') {
 5598:         my @creators = ('author','course','requestcrs');
 5599:         my ($rules,$ruleorder) =
 5600:             &Apache::lonnet::inst_userrules($dom,'username');
 5601:         my %lt = &usercreation_types();
 5602:         my %checked;
 5603:         if (ref($settings) eq 'HASH') {
 5604:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 5605:                 foreach my $item (@creators) {
 5606:                     $checked{$item} = $settings->{'cancreate'}{$item};
 5607:                 }
 5608:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 5609:                 foreach my $item (@creators) {
 5610:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 5611:                         $checked{$item} = 'none';
 5612:                     }
 5613:                 }
 5614:             }
 5615:         }
 5616:         my $rownum = 0;
 5617:         foreach my $item (@creators) {
 5618:             $rownum ++;
 5619:             if ($checked{$item} eq '') {
 5620:                 $checked{$item} = 'any';
 5621:             }
 5622:             my $css_class;
 5623:             if ($rownum%2) {
 5624:                 $css_class = '';
 5625:             } else {
 5626:                 $css_class = ' class="LC_odd_row" ';
 5627:             }
 5628:             $datatable .= '<tr'.$css_class.'>'.
 5629:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 5630:                          '</span></td><td align="right">';
 5631:             my @options = ('any');
 5632:             if (ref($rules) eq 'HASH') {
 5633:                 if (keys(%{$rules}) > 0) {
 5634:                     push(@options,('official','unofficial'));
 5635:                 }
 5636:             }
 5637:             push(@options,'none');
 5638:             foreach my $option (@options) {
 5639:                 my $type = 'radio';
 5640:                 my $check = ' ';
 5641:                 if ($checked{$item} eq $option) {
 5642:                     $check = ' checked="checked" ';
 5643:                 } 
 5644:                 $datatable .= '<span class="LC_nobreak"><label>'.
 5645:                               '<input type="'.$type.'" name="can_createuser_'.
 5646:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 5647:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 5648:             }
 5649:             $datatable .= '</td></tr>';
 5650:         }
 5651:     } else {
 5652:         my @contexts = ('author','course','domain');
 5653:         my @authtypes = ('int','krb4','krb5','loc');
 5654:         my %checked;
 5655:         if (ref($settings) eq 'HASH') {
 5656:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 5657:                 foreach my $item (@contexts) {
 5658:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 5659:                         foreach my $auth (@authtypes) {
 5660:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 5661:                                 $checked{$item}{$auth} = ' checked="checked" ';
 5662:                             }
 5663:                         }
 5664:                     }
 5665:                 }
 5666:             }
 5667:         } else {
 5668:             foreach my $item (@contexts) {
 5669:                 foreach my $auth (@authtypes) {
 5670:                     $checked{$item}{$auth} = ' checked="checked" ';
 5671:                 }
 5672:             }
 5673:         }
 5674:         my %title = &context_names();
 5675:         my %authname = &authtype_names();
 5676:         my $rownum = 0;
 5677:         my $css_class; 
 5678:         foreach my $item (@contexts) {
 5679:             if ($rownum%2) {
 5680:                 $css_class = '';
 5681:             } else {
 5682:                 $css_class = ' class="LC_odd_row" ';
 5683:             }
 5684:             $datatable .=   '<tr'.$css_class.'>'.
 5685:                             '<td>'.$title{$item}.
 5686:                             '</td><td class="LC_left_item">'.
 5687:                             '<span class="LC_nobreak">';
 5688:             foreach my $auth (@authtypes) {
 5689:                 $datatable .= '<label>'. 
 5690:                               '<input type="checkbox" name="'.$item.'_auth" '.
 5691:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 5692:                               $authname{$auth}.'</label>&nbsp;';
 5693:             }
 5694:             $datatable .= '</span></td></tr>';
 5695:             $rownum ++;
 5696:         }
 5697:         $$rowtotal += $rownum;
 5698:     }
 5699:     return $datatable;
 5700: }
 5701: 
 5702: sub print_selfcreation {
 5703:     my ($position,$dom,$settings,$rowtotal) = @_;
 5704:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 5705:         $emaildomain,$datatable);
 5706:     if (ref($settings) eq 'HASH') {
 5707:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 5708:             $createsettings = $settings->{'cancreate'};
 5709:             if (ref($createsettings) eq 'HASH') {
 5710:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 5711:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 5712:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 5713:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 5714:                         @selfcreate = ('email','login','sso');
 5715:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 5716:                         @selfcreate = ($createsettings->{'selfcreate'});
 5717:                     }
 5718:                 }
 5719:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 5720:                     $processing = $createsettings->{'selfcreateprocessing'};
 5721:                 }
 5722:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 5723:                     $emailoptions = $createsettings->{'emailoptions'};
 5724:                 }
 5725:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 5726:                     $emailverified = $createsettings->{'emailverified'};
 5727:                 }
 5728:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 5729:                     $emaildomain = $createsettings->{'emaildomain'};
 5730:                 }
 5731:             }
 5732:         }
 5733:     }
 5734:     my %radiohash;
 5735:     my $numinrow = 4;
 5736:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 5737:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5738:     if ($position eq 'top') {
 5739:         my %choices = &Apache::lonlocal::texthash (
 5740:                                                       cancreate_login      => 'Institutional Login',
 5741:                                                       cancreate_sso        => 'Institutional Single Sign On',
 5742:                                                   );
 5743:         my @toggles = sort(keys(%choices));
 5744:         my %defaultchecked = (
 5745:                                'cancreate_login' => 'off',
 5746:                                'cancreate_sso'   => 'off',
 5747:                              );
 5748:         my ($onclick,$itemcount);
 5749:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 5750:                                                      \%choices,$itemcount,$onclick);
 5751:         $$rowtotal += $itemcount;
 5752: 
 5753:         if (ref($usertypes) eq 'HASH') {
 5754:             if (keys(%{$usertypes}) > 0) {
 5755:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 5756:                                              $dom,$numinrow,$othertitle,
 5757:                                              'statustocreate',$rowtotal);
 5758:                 $$rowtotal ++;
 5759:             }
 5760:         }
 5761:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 5762:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 5763:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 5764:         my $rem;
 5765:         my $numperrow = 2;
 5766:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 5767:         $datatable .= '<tr'.$css_class.'>'.
 5768:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 5769:                      '<td class="LC_left_item">'."\n".
 5770:                      '<table>'."\n";
 5771:         for (my $i=0; $i<@fields; $i++) {
 5772:             $rem = $i%($numperrow);
 5773:             if ($rem == 0) {
 5774:                 if ($i > 0) {
 5775:                     $datatable .= '</tr>';
 5776:                 }
 5777:                 $datatable .= '<tr>';
 5778:             }
 5779:             my $currval;
 5780:             if (ref($createsettings) eq 'HASH') {
 5781:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 5782:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 5783:                 }
 5784:             }
 5785:             $datatable .= '<td class="LC_left_item">'.
 5786:                           '<span class="LC_nobreak">'.
 5787:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 5788:                           'value="'.$currval.'" size="10" />&nbsp;'.
 5789:                           $fieldtitles{$fields[$i]}.'</span></td>';
 5790:         }
 5791:         my $colsleft = $numperrow - $rem;
 5792:         if ($colsleft > 1 ) {
 5793:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 5794:                          '&nbsp;</td>';
 5795:         } elsif ($colsleft == 1) {
 5796:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 5797:         }
 5798:         $datatable .= '</tr></table></td></tr>';
 5799:         $$rowtotal ++;
 5800:     } elsif ($position eq 'middle') {
 5801:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 5802:         my @posstypes;
 5803:         if (ref($types) eq 'ARRAY') {
 5804:             @posstypes = @{$types};
 5805:         }
 5806:         unless (grep(/^default$/,@posstypes)) {
 5807:             push(@posstypes,'default');
 5808:         }
 5809:         my %usertypeshash;
 5810:         if (ref($usertypes) eq 'HASH') {
 5811:             %usertypeshash = %{$usertypes};
 5812:         }
 5813:         $usertypeshash{'default'} = $othertitle;
 5814:         foreach my $status (@posstypes) {
 5815:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 5816:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 5817:             $$rowtotal ++;
 5818:         }
 5819:     } else {
 5820:         my %choices = &Apache::lonlocal::texthash (
 5821:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 5822:                                                   );
 5823:         my @toggles = sort(keys(%choices));
 5824:         my %defaultchecked = (
 5825:                                'cancreate_email' => 'off',
 5826:                              );
 5827:         my $customclass = 'LC_selfcreate_email';
 5828:         my $classprefix = 'LC_canmodify_emailusername_';
 5829:         my $optionsprefix = 'LC_options_emailusername_';
 5830:         my $display = 'none';
 5831:         my $rowstyle = 'display:none';
 5832:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 5833:             $display = 'block';
 5834:             $rowstyle = 'display:table-row';
 5835:         }
 5836:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
 5837:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 5838:                                                      \%choices,$$rowtotal,$onclick);
 5839:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
 5840:                                          $rowstyle);
 5841:         $$rowtotal ++;
 5842:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
 5843:                                       $rowstyle);
 5844:         $$rowtotal ++;
 5845:         my (@ordered,@posstypes,%usertypeshash);
 5846:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 5847:         my ($emailrules,$emailruleorder) =
 5848:             &Apache::lonnet::inst_userrules($dom,'email');
 5849:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 5850:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 5851:         if (ref($types) eq 'ARRAY') {
 5852:             @posstypes = @{$types};
 5853:         }
 5854:         if (@posstypes) {
 5855:             unless (grep(/^default$/,@posstypes)) {
 5856:                 push(@posstypes,'default');
 5857:             }
 5858:             if (ref($usertypes) eq 'HASH') {
 5859:                 %usertypeshash = %{$usertypes};
 5860:             }
 5861:             my $currassign;
 5862:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
 5863:                 $currassign = {
 5864:                                   selfassign => $domdefaults{'inststatusguest'},
 5865:                               };
 5866:                 @ordered = @{$domdefaults{'inststatusguest'}};
 5867:             } else {
 5868:                 $currassign = { selfassign => [] };
 5869:             }
 5870:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
 5871:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
 5872:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
 5873:                                          $numinrow,$othertitle,'selfassign',
 5874:                                          $rowtotal,$onclicktypes,$customclass,
 5875:                                          $rowstyle);
 5876:             $$rowtotal ++;
 5877:             $usertypeshash{'default'} = $othertitle;
 5878:             foreach my $status (@posstypes) {
 5879:                 my $css_class;
 5880:                 if ($$rowtotal%2) {
 5881:                     $css_class = 'LC_odd_row ';
 5882:                 }
 5883:                 $css_class .= $customclass;
 5884:                 my $rowid = $optionsprefix.$status;
 5885:                 my $hidden = 1;
 5886:                 my $currstyle = 'display:none';
 5887:                 if (grep(/^\Q$status\E$/,@ordered)) {
 5888:                     $currstyle = $rowstyle;
 5889:                     $hidden = 0;
 5890:                 }
 5891:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 5892:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
 5893:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
 5894:                 unless ($hidden) {
 5895:                     $$rowtotal ++;
 5896:                 }
 5897:             }
 5898:         } else {
 5899:             my $css_class;
 5900:             if ($$rowtotal%2) {
 5901:                 $css_class = 'LC_odd_row ';
 5902:             }
 5903:             $css_class .= $customclass;
 5904:             $usertypeshash{'default'} = $othertitle;
 5905:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 5906:                                          $emailrules,$emailruleorder,$settings,'default','',
 5907:                                          $othertitle,$css_class,$rowstyle,$intdom);
 5908:             $$rowtotal ++;
 5909:         }
 5910:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 5911:         $numinrow = 1;
 5912:         if (@posstypes) {
 5913:             foreach my $status (@posstypes) {
 5914:                 my $rowid = $classprefix.$status;
 5915:                 my $datarowstyle = 'display:none';
 5916:                 if (grep(/^\Q$status\E$/,@ordered)) {
 5917:                     $datarowstyle = $rowstyle;
 5918:                 }
 5919:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 5920:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 5921:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
 5922:                 unless ($datarowstyle eq 'display:none') {
 5923:                     $$rowtotal ++;
 5924:                 }
 5925:             }
 5926:         } else {
 5927:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
 5928:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 5929:                                                    $infotitles,'',$customclass,$rowstyle);
 5930:         }
 5931:     }
 5932:     return $datatable;
 5933: }
 5934: 
 5935: sub selfcreate_javascript {
 5936:     return <<"ENDSCRIPT";
 5937: 
 5938: <script type="text/javascript">
 5939: // <![CDATA[
 5940: 
 5941: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
 5942:     var x = document.getElementsByClassName(target);
 5943:     var insttypes = 0;
 5944:     var insttypeRegExp = new RegExp(prefix);
 5945:     if ((x.length != undefined) && (x.length > 0)) {
 5946:         if (form.elements[radio].length != undefined) {
 5947:             for (var i=0; i<form.elements[radio].length; i++) {
 5948:                 if (form.elements[radio][i].checked) {
 5949:                     if (form.elements[radio][i].value == 1) {
 5950:                         for (var j=0; j<x.length; j++) {
 5951:                             if (x[j].id == 'undefined') {
 5952:                                 x[j].style.display = 'table-row';
 5953:                             } else if (insttypeRegExp.test(x[j].id)) {
 5954:                                 insttypes ++;
 5955:                             } else {
 5956:                                 x[j].style.display = 'table-row';
 5957:                             }
 5958:                         }
 5959:                     } else {
 5960:                         for (var j=0; j<x.length; j++) {
 5961:                             x[j].style.display = 'none';
 5962:                         }
 5963:                     }
 5964:                     break;
 5965:                 }
 5966:             }
 5967:             if (insttypes > 0) {
 5968:                 toggleDataRow(form,checkbox,target,altprefix);
 5969:                 toggleDataRow(form,checkbox,target,prefix,1);
 5970:             }
 5971:         }
 5972:     }
 5973:     return;
 5974: }
 5975: 
 5976: function toggleDataRow(form,checkbox,target,prefix,docount) {
 5977:     if (form.elements[checkbox].length != undefined) {
 5978:         var count = 0;
 5979:         if (docount) {
 5980:             for (var i=0; i<form.elements[checkbox].length; i++) {
 5981:                 if (form.elements[checkbox][i].checked) {
 5982:                     count ++;
 5983:                 }
 5984:             }
 5985:         }
 5986:         for (var i=0; i<form.elements[checkbox].length; i++) {
 5987:             var type = form.elements[checkbox][i].value;
 5988:             if (document.getElementById(prefix+type)) {
 5989:                 if (form.elements[checkbox][i].checked) {
 5990:                     document.getElementById(prefix+type).style.display = 'table-row';
 5991:                     if (count % 2 == 1) {
 5992:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 5993:                     } else {
 5994:                         document.getElementById(prefix+type).className = target;
 5995:                     }
 5996:                     count ++;
 5997:                 } else {
 5998:                     document.getElementById(prefix+type).style.display = 'none';
 5999:                 }
 6000:             }
 6001:         }
 6002:     }
 6003:     return;
 6004: }
 6005: 
 6006: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
 6007:     var caller = radio+'_'+status;
 6008:     if (form.elements[caller].length != undefined) {
 6009:         for (var i=0; i<form.elements[caller].length; i++) {
 6010:             if (form.elements[caller][i].checked) {
 6011:                 if (document.getElementById(altprefix+'_inst_'+status)) {
 6012:                     var curr = form.elements[caller][i].value;
 6013:                     if (prefix) {
 6014:                         document.getElementById(prefix+'_'+status).style.display = 'none';
 6015:                     }
 6016:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
 6017:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
 6018:                     if (curr == 'custom') {
 6019:                         if (prefix) {
 6020:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
 6021:                         }
 6022:                     } else if (curr == 'inst') {
 6023:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
 6024:                     } else if (curr == 'noninst') {
 6025:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
 6026:                     }
 6027:                     break;
 6028:                 }
 6029:             }
 6030:         }
 6031:     }
 6032: }
 6033: 
 6034: // ]]>
 6035: </script>
 6036: 
 6037: ENDSCRIPT
 6038: }
 6039: 
 6040: sub noninst_users {
 6041:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
 6042:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_;
 6043:     my $class = 'LC_left_item';
 6044:     if ($css_class) {
 6045:         $css_class = ' class="'.$css_class.'"';
 6046:     }
 6047:     if ($rowid) {
 6048:         $rowid = ' id="'.$rowid.'"';
 6049:     }
 6050:     if ($rowstyle) {
 6051:         $rowstyle = ' style="'.$rowstyle.'"';
 6052:     }
 6053:     my ($output,$description);
 6054:     if ($type eq 'default') {
 6055:         $description = &mt('Requests for: [_1]',$typetitle);
 6056:     } else {
 6057:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
 6058:     }
 6059:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 6060:               "<td>$description</td>\n".
 6061:               '<td class="'.$class.'" colspan="2">'.
 6062:               '<table><tr>';
 6063:     my %headers = &Apache::lonlocal::texthash(
 6064:               approve  => 'Processing',
 6065:               email    => 'E-mail',
 6066:               username => 'Username',
 6067:     );
 6068:     foreach my $item ('approve','email','username') {
 6069:         $output .= '<th>'.$headers{$item}.'</th>';
 6070:     }
 6071:     $output .= '</tr><tr>';
 6072:     foreach my $item ('approve','email','username') {
 6073:         $output .= '<td valign="top">';
 6074:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
 6075:         if ($item eq 'approve') {
 6076:             %choices = &Apache::lonlocal::texthash (
 6077:                                                      automatic => 'Automatically approved',
 6078:                                                      approval  => 'Queued for approval',
 6079:                                                    );
 6080:             @options = ('automatic','approval');
 6081:             $hashref = $processing;
 6082:             $defoption = 'automatic';
 6083:             $name = 'cancreate_emailprocess_'.$type;
 6084:         } elsif ($item eq 'email') {
 6085:             %choices = &Apache::lonlocal::texthash (
 6086:                                                      any     => 'Any e-mail',
 6087:                                                      inst    => 'Institutional only',
 6088:                                                      noninst => 'Non-institutional only',
 6089:                                                      custom  => 'Custom restrictions',
 6090:                                                    );
 6091:             @options = ('any','inst','noninst');
 6092:             my $showcustom;
 6093:             if (ref($emailrules) eq 'HASH') {
 6094:                 if (keys(%{$emailrules}) > 0) {
 6095:                     push(@options,'custom');
 6096:                     $showcustom = 'cancreate_emailrule';
 6097:                     if (ref($settings) eq 'HASH') {
 6098:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 6099:                             foreach my $rule (@{$settings->{'email_rule'}}) {
 6100:                                 if (exists($emailrules->{$rule})) {
 6101:                                     $hascustom ++;
 6102:                                 }
 6103:                             }
 6104:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
 6105:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
 6106:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
 6107:                                     if (exists($emailrules->{$rule})) {
 6108:                                         $hascustom ++;
 6109:                                     }
 6110:                                 }
 6111:                             }
 6112:                         }
 6113:                     }
 6114:                 }
 6115:             }
 6116:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
 6117:                                                      "'cancreate_emaildomain','$type'".');"';
 6118:             $hashref = $emailoptions;
 6119:             $defoption = 'any';
 6120:             $name = 'cancreate_emailoptions_'.$type;
 6121:         } elsif ($item eq 'username') {
 6122:             %choices = &Apache::lonlocal::texthash (
 6123:                                                      all    => 'Same as e-mail',
 6124:                                                      first  => 'Omit @domain',
 6125:                                                      free   => 'Free to choose',
 6126:                                                    );
 6127:             @options = ('all','first','free');
 6128:             $hashref = $emailverified;
 6129:             $defoption = 'all';
 6130:             $name = 'cancreate_usernameoptions_'.$type;
 6131:         }
 6132:         foreach my $option (@options) {
 6133:             my $checked;
 6134:             if (ref($hashref) eq 'HASH') {
 6135:                 if ($type eq '') {
 6136:                     if (!exists($hashref->{'default'})) {
 6137:                         if ($option eq $defoption) {
 6138:                             $checked = ' checked="checked"';
 6139:                         }
 6140:                     } else {
 6141:                         if ($hashref->{'default'} eq $option) {
 6142:                             $checked = ' checked="checked"';
 6143:                         }
 6144:                     }
 6145:                 } else {
 6146:                     if (!exists($hashref->{$type})) {
 6147:                         if ($option eq $defoption) {
 6148:                             $checked = ' checked="checked"';
 6149:                         }
 6150:                     } else {
 6151:                         if ($hashref->{$type} eq $option) {
 6152:                             $checked = ' checked="checked"';
 6153:                         }
 6154:                     }
 6155:                 }
 6156:             } elsif (($item eq 'email') && ($hascustom)) {
 6157:                 if ($option eq 'custom') {
 6158:                     $checked = ' checked="checked"';
 6159:                 }
 6160:             } elsif ($option eq $defoption) {
 6161:                 $checked = ' checked="checked"';
 6162:             }
 6163:             $output .= '<span class="LC_nobreak"><label>'.
 6164:                        '<input type="radio" name="'.$name.'"'.
 6165:                        $checked.' value="'.$option.'"'.$onclick.' />'.
 6166:                        $choices{$option}.'</label></span><br />';
 6167:             if ($item eq 'email') {
 6168:                 if ($option eq 'custom') {
 6169:                     my $id = 'cancreate_emailrule_'.$type;
 6170:                     my $display = 'none';
 6171:                     if ($checked) {
 6172:                         $display = 'inline';
 6173:                     }
 6174:                     my $numinrow = 2;
 6175:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
 6176:                                '<legend>'.&mt('Disallow').'</legend><table>'.
 6177:                                &user_formats_row('email',$settings,$emailrules,
 6178:                                                  $emailruleorder,$numinrow,'',$type);
 6179:                               '</table></fieldset>';
 6180:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
 6181:                     my %text = &Apache::lonlocal::texthash (
 6182:                                                              inst    => 'must end:',
 6183:                                                              noninst => 'cannot end:',
 6184:                                                            );
 6185:                     my $value;
 6186:                     if (ref($emaildomain) eq 'HASH') {
 6187:                         if (ref($emaildomain->{$type}) eq 'HASH') {
 6188:                             $value = $emaildomain->{$type}->{$option};
 6189:                         }
 6190:                     }
 6191:                     if ($value eq '') {
 6192:                         $value = '@'.$intdom;
 6193:                     }
 6194:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
 6195:                     my $display = 'none';
 6196:                     if ($checked) {
 6197:                         $display = 'inline';
 6198:                     }
 6199:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
 6200:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
 6201:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
 6202:                                '</div>';
 6203:                 }
 6204:             }
 6205:         }
 6206:         $output .= '</td>'."\n";
 6207:     }
 6208:     $output .= "</tr></table></td></tr>\n";
 6209:     return $output;
 6210: }
 6211: 
 6212: sub captcha_choice {
 6213:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
 6214:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
 6215:         $vertext,$currver); 
 6216:     my %lt = &captcha_phrases();
 6217:     $keyentry = 'hidden';
 6218:     my $colspan=2;
 6219:     if ($context eq 'cancreate') {
 6220:         $rowname = &mt('CAPTCHA validation');
 6221:     } elsif ($context eq 'login') {
 6222:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
 6223:     } elsif ($context eq 'passwords') {
 6224:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
 6225:         $colspan=1;
 6226:     }
 6227:     if (ref($settings) eq 'HASH') {
 6228:         if ($settings->{'captcha'}) {
 6229:             $checked{$settings->{'captcha'}} = ' checked="checked"';
 6230:         } else {
 6231:             $checked{'original'} = ' checked="checked"';
 6232:         }
 6233:         if ($settings->{'captcha'} eq 'recaptcha') {
 6234:             $pubtext = $lt{'pub'};
 6235:             $privtext = $lt{'priv'};
 6236:             $keyentry = 'text';
 6237:             $vertext = $lt{'ver'};
 6238:             $currver = $settings->{'recaptchaversion'};
 6239:             if ($currver ne '2') {
 6240:                 $currver = 1;
 6241:             }
 6242:         }
 6243:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
 6244:             $currpub = $settings->{'recaptchakeys'}{'public'};
 6245:             $currpriv = $settings->{'recaptchakeys'}{'private'};
 6246:         }
 6247:     } else {
 6248:         $checked{'original'} = ' checked="checked"';
 6249:     }
 6250:     my $css_class;
 6251:     if ($itemcount%2) {
 6252:         $css_class = 'LC_odd_row';
 6253:     }
 6254:     if ($customcss) {
 6255:         $css_class .= " $customcss";
 6256:     }
 6257:     $css_class =~ s/^\s+//;
 6258:     if ($css_class) {
 6259:         $css_class = ' class="'.$css_class.'"';
 6260:     }
 6261:     if ($rowstyle) {
 6262:         $css_class .= ' style="'.$rowstyle.'"';
 6263:     }
 6264:     my $output = '<tr'.$css_class.'>'.
 6265:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
 6266:                  '<table><tr><td>'."\n";
 6267:     foreach my $option ('original','recaptcha','notused') {
 6268:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
 6269:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
 6270:                    $lt{$option}.'</label></span>';
 6271:         unless ($option eq 'notused') {
 6272:             $output .= ('&nbsp;'x2)."\n";
 6273:         }
 6274:     }
 6275: #
 6276: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
 6277: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
 6278: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
 6279: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
 6280: #
 6281:     $output .= '</td></tr>'."\n".
 6282:                '<tr><td class="LC_zero_height">'."\n".
 6283:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
 6284:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
 6285:                $currpub.'" size="40" /></span><br />'."\n".
 6286:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
 6287:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
 6288:                $currpriv.'" size="40" /></span><br />'.
 6289:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
 6290:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
 6291:                $currver.'" size="3" /></span><br />'.
 6292:                '</td></tr></table>'."\n".
 6293:                '</td></tr>';
 6294:     return $output;
 6295: }
 6296: 
 6297: sub user_formats_row {
 6298:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
 6299:     my $output;
 6300:     my %text = (
 6301:                    'username' => 'new usernames',
 6302:                    'id'       => 'IDs',
 6303:                );
 6304:     unless ($type eq 'email') {
 6305:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 6306:         $output = '<tr '.$css_class.'>'.
 6307:                   '<td><span class="LC_nobreak">'.
 6308:                   &mt("Format rules to check for $text{$type}: ").
 6309:                   '</td><td class="LC_left_item" colspan="2"><table>';
 6310:     }
 6311:     my $rem;
 6312:     if (ref($ruleorder) eq 'ARRAY') {
 6313:         for (my $i=0; $i<@{$ruleorder}; $i++) {
 6314:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
 6315:                 my $rem = $i%($numinrow);
 6316:                 if ($rem == 0) {
 6317:                     if ($i > 0) {
 6318:                         $output .= '</tr>';
 6319:                     }
 6320:                     $output .= '<tr>';
 6321:                 }
 6322:                 my $check = ' ';
 6323:                 if (ref($settings) eq 'HASH') {
 6324:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
 6325:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
 6326:                             $check = ' checked="checked" ';
 6327:                         }
 6328:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
 6329:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
 6330:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
 6331:                                 $check = ' checked="checked" ';
 6332:                             }
 6333:                         }
 6334:                     }
 6335:                 }
 6336:                 my $name = $type.'_rule';
 6337:                 if ($type eq 'email') {
 6338:                     $name .= '_'.$status;
 6339:                 }
 6340:                 $output .= '<td class="LC_left_item">'.
 6341:                            '<span class="LC_nobreak"><label>'.
 6342:                            '<input type="checkbox" name="'.$name.'" '.
 6343:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
 6344:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
 6345:             }
 6346:         }
 6347:         $rem = @{$ruleorder}%($numinrow);
 6348:     }
 6349:     my $colsleft;
 6350:     if ($rem) {
 6351:         $colsleft = $numinrow - $rem;
 6352:     }
 6353:     if ($colsleft > 1 ) {
 6354:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6355:                    '&nbsp;</td>';
 6356:     } elsif ($colsleft == 1) {
 6357:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 6358:     }
 6359:     $output .= '</tr></table>';
 6360:     unless ($type eq 'email') {
 6361:         $output .= '</td></tr>';
 6362:     }
 6363:     return $output;
 6364: }
 6365: 
 6366: sub usercreation_types {
 6367:     my %lt = &Apache::lonlocal::texthash (
 6368:                     author     => 'When adding a co-author',
 6369:                     course     => 'When adding a user to a course',
 6370:                     requestcrs => 'When requesting a course',
 6371:                     any        => 'Any',
 6372:                     official   => 'Institutional only ',
 6373:                     unofficial => 'Non-institutional only',
 6374:                     none       => 'None',
 6375:     );
 6376:     return %lt;
 6377: }
 6378: 
 6379: sub selfcreation_types {
 6380:     my %lt = &Apache::lonlocal::texthash (
 6381:                     selfcreate => 'User creates own account',
 6382:                     any        => 'Any',
 6383:                     official   => 'Institutional only ',
 6384:                     unofficial => 'Non-institutional only',
 6385:                     email      => 'E-mail address',
 6386:                     login      => 'Institutional Login',
 6387:                     sso        => 'SSO',
 6388:              );
 6389: }
 6390: 
 6391: sub authtype_names {
 6392:     my %lt = &Apache::lonlocal::texthash(
 6393:                       int    => 'Internal',
 6394:                       krb4   => 'Kerberos 4',
 6395:                       krb5   => 'Kerberos 5',
 6396:                       loc    => 'Local',
 6397:                   );
 6398:     return %lt;
 6399: }
 6400: 
 6401: sub context_names {
 6402:     my %context_title = &Apache::lonlocal::texthash(
 6403:        author => 'Creating users when an Author',
 6404:        course => 'Creating users when in a course',
 6405:        domain => 'Creating users when a Domain Coordinator',
 6406:     );
 6407:     return %context_title;
 6408: }
 6409: 
 6410: sub print_usermodification {
 6411:     my ($position,$dom,$settings,$rowtotal) = @_;
 6412:     my $numinrow = 4;
 6413:     my ($context,$datatable,$rowcount);
 6414:     if ($position eq 'top') {
 6415:         $rowcount = 0;
 6416:         $context = 'author'; 
 6417:         foreach my $role ('ca','aa') {
 6418:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 6419:                                                    $numinrow,$rowcount);
 6420:             $$rowtotal ++;
 6421:             $rowcount ++;
 6422:         }
 6423:     } elsif ($position eq 'bottom') {
 6424:         $context = 'course';
 6425:         $rowcount = 0;
 6426:         foreach my $role ('st','ep','ta','in','cr') {
 6427:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 6428:                                                    $numinrow,$rowcount);
 6429:             $$rowtotal ++;
 6430:             $rowcount ++;
 6431:         }
 6432:     }
 6433:     return $datatable;
 6434: }
 6435: 
 6436: sub print_defaults {
 6437:     my ($position,$dom,$settings,$rowtotal) = @_;
 6438:     my $rownum = 0;
 6439:     my ($datatable,$css_class,$titles);
 6440:     unless ($position eq 'bottom') {
 6441:         $titles = &defaults_titles($dom);
 6442:     }
 6443:     if ($position eq 'top') {
 6444:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
 6445:                      'datelocale_def','portal_def');
 6446:         my %defaults;
 6447:         if (ref($settings) eq 'HASH') {
 6448:             %defaults = %{$settings};
 6449:         } else {
 6450:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 6451:             foreach my $item (@items) {
 6452:                 $defaults{$item} = $domdefaults{$item};
 6453:             }
 6454:         }
 6455:         foreach my $item (@items) {
 6456:             if ($rownum%2) {
 6457:                 $css_class = '';
 6458:             } else {
 6459:                 $css_class = ' class="LC_odd_row" ';
 6460:             }
 6461:             $datatable .= '<tr'.$css_class.'>'.
 6462:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 6463:                           '</span></td><td class="LC_right_item" colspan="3">';
 6464:             if ($item eq 'auth_def') {
 6465:                 my @authtypes = ('internal','krb4','krb5','localauth');
 6466:                 my %shortauth = (
 6467:                                  internal => 'int',
 6468:                                  krb4 => 'krb4',
 6469:                                  krb5 => 'krb5',
 6470:                                  localauth  => 'loc'
 6471:                                 );
 6472:                 my %authnames = &authtype_names();
 6473:                 foreach my $auth (@authtypes) {
 6474:                     my $checked = ' ';
 6475:                     if ($defaults{$item} eq $auth) {
 6476:                         $checked = ' checked="checked" ';
 6477:                     }
 6478:                     $datatable .= '<label><input type="radio" name="'.$item.
 6479:                                   '" value="'.$auth.'"'.$checked.'/>'.
 6480:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
 6481:                 }
 6482:             } elsif ($item eq 'timezone_def') {
 6483:                 my $includeempty = 1;
 6484:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
 6485:             } elsif ($item eq 'datelocale_def') {
 6486:                 my $includeempty = 1;
 6487:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
 6488:             } elsif ($item eq 'lang_def') {
 6489:                 my $includeempty = 1;
 6490:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
 6491:             } else {
 6492:                 my $size;
 6493:                 if ($item eq 'portal_def') {
 6494:                     $size = ' size="25"';
 6495:                 }
 6496:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 6497:                               $defaults{$item}.'"'.$size.' />';
 6498:             }
 6499:             $datatable .= '</td></tr>';
 6500:             $rownum ++;
 6501:         }
 6502:     } else {
 6503:         my %defaults;
 6504:         if (ref($settings) eq 'HASH') {
 6505:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 6506:                 my $maxnum = @{$settings->{'inststatusorder'}};
 6507:                 for (my $i=0; $i<$maxnum; $i++) {
 6508:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
 6509:                     my $item = $settings->{'inststatusorder'}->[$i];
 6510:                     my $title = $settings->{'inststatustypes'}->{$item};
 6511:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
 6512:                     $datatable .= '<tr'.$css_class.'>'.
 6513:                                   '<td><span class="LC_nobreak">'.
 6514:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
 6515:                     for (my $k=0; $k<=$maxnum; $k++) {
 6516:                         my $vpos = $k+1;
 6517:                         my $selstr;
 6518:                         if ($k == $i) {
 6519:                             $selstr = ' selected="selected" ';
 6520:                         }
 6521:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6522:                     }
 6523:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
 6524:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
 6525:                                   &mt('delete').'</span></td>'.
 6526:                                   '<td class="LC_left_item"><span class="LC_nobreak">'.&mt('Name displayed:').
 6527:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
 6528:                                   '</span></td></tr>';
 6529:                 }
 6530:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
 6531:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
 6532:                 $datatable .= '<tr '.$css_class.'>'.
 6533:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
 6534:                 for (my $k=0; $k<=$maxnum; $k++) {
 6535:                     my $vpos = $k+1;
 6536:                     my $selstr;
 6537:                     if ($k == $maxnum) {
 6538:                         $selstr = ' selected="selected" ';
 6539:                     }
 6540:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6541:                 }
 6542:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
 6543:                               '<input type="text" size="10" name="addinststatus" value="" />'.
 6544:                               '&nbsp;'.&mt('(new)').
 6545:                               '</span></td><td class="LC_left_item"><span class="LC_nobreak">'.
 6546:                               &mt('Name displayed:').
 6547:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
 6548:                               '</tr>'."\n";
 6549:                 $rownum ++;
 6550:             }
 6551:         }
 6552:     }
 6553:     $$rowtotal += $rownum;
 6554:     return $datatable;
 6555: }
 6556: 
 6557: sub get_languages_hash {
 6558:     my %langchoices;
 6559:     foreach my $id (&Apache::loncommon::languageids()) {
 6560:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 6561:         if ($code ne '') {
 6562:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 6563:         }
 6564:     }
 6565:     return %langchoices;
 6566: }
 6567: 
 6568: sub defaults_titles {
 6569:     my ($dom) = @_;
 6570:     my %titles = &Apache::lonlocal::texthash (
 6571:                    'auth_def'      => 'Default authentication type',
 6572:                    'auth_arg_def'  => 'Default authentication argument',
 6573:                    'lang_def'      => 'Default language',
 6574:                    'timezone_def'  => 'Default timezone',
 6575:                    'datelocale_def' => 'Default locale for dates',
 6576:                    'portal_def'     => 'Portal/Default URL',
 6577:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
 6578:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
 6579:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
 6580:                  );
 6581:     if ($dom) {
 6582:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
 6583:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 6584:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
 6585:         $protocol = 'http' if ($protocol ne 'https');
 6586:         if ($uint_dom) {
 6587:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
 6588:                                          $uint_dom);
 6589:         }
 6590:     }
 6591:     return (\%titles);
 6592: }
 6593: 
 6594: sub print_scantron {
 6595:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
 6596:     if ($position eq 'top') {
 6597:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
 6598:     } else {
 6599:         return &print_scantronconfig($dom,$settings,\$rowtotal);
 6600:     }
 6601: }
 6602: 
 6603: sub scantron_javascript {
 6604:     return <<"ENDSCRIPT";
 6605: 
 6606: <script type="text/javascript">
 6607: // <![CDATA[
 6608: 
 6609: function toggleScantron(form) {
 6610:     var csvfieldset = new Array();
 6611:     if (document.getElementById('scantroncsv_cols')) {
 6612:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
 6613:     }
 6614:     if (document.getElementById('scantroncsv_options')) {
 6615:         csvfieldset.push(document.getElementById('scantroncsv_options'));
 6616:     }
 6617:     if (csvfieldset.length) {
 6618:         if (document.getElementById('scantronconfcsv')) {
 6619:             var scantroncsv = document.getElementById('scantronconfcsv');
 6620:             if (scantroncsv.checked) {
 6621:                 for (var i=0; i<csvfieldset.length; i++) {
 6622:                     csvfieldset[i].style.display = 'block';
 6623:                 }
 6624:             } else {
 6625:                 for (var i=0; i<csvfieldset.length; i++) {
 6626:                     csvfieldset[i].style.display = 'none';
 6627:                 }
 6628:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
 6629:                 if (csvselects.length) {
 6630:                     for (var j=0; j<csvselects.length; j++) {
 6631:                         csvselects[j].selectedIndex = 0;
 6632:                     }
 6633:                 }
 6634:             }
 6635:         }
 6636:     }
 6637:     return;
 6638: }
 6639: // ]]>
 6640: </script>
 6641: 
 6642: ENDSCRIPT
 6643: 
 6644: }
 6645: 
 6646: sub print_scantronformat {
 6647:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
 6648:     my $itemcount = 1;
 6649:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
 6650:         %confhash);
 6651:     my $switchserver = &check_switchserver($dom,$confname);
 6652:     my %lt = &Apache::lonlocal::texthash (
 6653:                 default => 'Default bubblesheet format file error',
 6654:                 custom  => 'Custom bubblesheet format file error',
 6655:              );
 6656:     my %scantronfiles = (
 6657:         default => 'default.tab',
 6658:         custom => 'custom.tab',
 6659:     );
 6660:     foreach my $key (keys(%scantronfiles)) {
 6661:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
 6662:                               .$scantronfiles{$key};
 6663:     }
 6664:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
 6665:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
 6666:         if (!$switchserver) {
 6667:             my $servadm = $r->dir_config('lonAdmEMail');
 6668:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
 6669:             if ($configuserok eq 'ok') {
 6670:                 if ($author_ok eq 'ok') {
 6671:                     my %legacyfile = (
 6672:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
 6673:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
 6674:                     );
 6675:                     my %md5chk;
 6676:                     foreach my $type (keys(%legacyfile)) {
 6677:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
 6678:                         chomp($md5chk{$type});
 6679:                     }
 6680:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
 6681:                         foreach my $type (keys(%legacyfile)) {
 6682:                             ($scantronurls{$type},my $error) =
 6683:                                 &legacy_scantronformat($r,$dom,$confname,
 6684:                                                  $type,$legacyfile{$type},
 6685:                                                  $scantronurls{$type},
 6686:                                                  $scantronfiles{$type});
 6687:                             if ($error ne '') {
 6688:                                 $error{$type} = $error;
 6689:                             }
 6690:                         }
 6691:                         if (keys(%error) == 0) {
 6692:                             $is_custom = 1;
 6693:                             $confhash{'scantron'}{'scantronformat'} =
 6694:                                 $scantronurls{'custom'};
 6695:                             my $putresult =
 6696:                                 &Apache::lonnet::put_dom('configuration',
 6697:                                                          \%confhash,$dom);
 6698:                             if ($putresult ne 'ok') {
 6699:                                 $error{'custom'} =
 6700:                                     '<span class="LC_error">'.
 6701:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 6702:                             }
 6703:                         }
 6704:                     } else {
 6705:                         ($scantronurls{'default'},my $error) =
 6706:                             &legacy_scantronformat($r,$dom,$confname,
 6707:                                           'default',$legacyfile{'default'},
 6708:                                           $scantronurls{'default'},
 6709:                                           $scantronfiles{'default'});
 6710:                         if ($error eq '') {
 6711:                             $confhash{'scantron'}{'scantronformat'} = ''; 
 6712:                             my $putresult =
 6713:                                 &Apache::lonnet::put_dom('configuration',
 6714:                                                          \%confhash,$dom);
 6715:                             if ($putresult ne 'ok') {
 6716:                                 $error{'default'} =
 6717:                                     '<span class="LC_error">'.
 6718:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 6719:                             }
 6720:                         } else {
 6721:                             $error{'default'} = $error;
 6722:                         }
 6723:                     }
 6724:                 }
 6725:             }
 6726:         } else {
 6727:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
 6728:         }
 6729:     }
 6730:     if (ref($settings) eq 'HASH') {
 6731:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
 6732:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
 6733:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
 6734:                 $scantronurl = '';
 6735:             } else {
 6736:                 $scantronurl = $settings->{'scantronformat'};
 6737:             }
 6738:             $is_custom = 1;
 6739:         } else {
 6740:             $scantronurl = $scantronurls{'default'};
 6741:         }
 6742:     } else {
 6743:         if ($is_custom) {
 6744:             $scantronurl = $scantronurls{'custom'};
 6745:         } else {
 6746:             $scantronurl = $scantronurls{'default'};
 6747:         }
 6748:     }
 6749:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6750:     $datatable .= '<tr'.$css_class.'>';
 6751:     if (!$is_custom) {
 6752:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
 6753:                       '<span class="LC_nobreak">';
 6754:         if ($scantronurl) {
 6755:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
 6756:                                                          undef,undef,undef,undef,'background-color:#ffffff');
 6757:         } else {
 6758:             $datatable = &mt('File unavailable for display');
 6759:         }
 6760:         $datatable .= '</span></td>';
 6761:         if (keys(%error) == 0) { 
 6762:             $datatable .= '<td valign="bottom">';
 6763:             if (!$switchserver) {
 6764:                 $datatable .= &mt('Upload:').'<br />';
 6765:             }
 6766:         } else {
 6767:             my $errorstr;
 6768:             foreach my $key (sort(keys(%error))) {
 6769:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 6770:             }
 6771:             $datatable .= '<td>'.$errorstr;
 6772:         }
 6773:     } else {
 6774:         if (keys(%error) > 0) {
 6775:             my $errorstr;
 6776:             foreach my $key (sort(keys(%error))) {
 6777:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 6778:             } 
 6779:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
 6780:         } elsif ($scantronurl) {
 6781:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
 6782:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 6783:             $datatable .= '<td><span class="LC_nobreak">'.
 6784:                           $link.
 6785:                           '<label><input type="checkbox" name="scantronformat_del"'.
 6786:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
 6787:                           '<td><span class="LC_nobreak">&nbsp;'.
 6788:                           &mt('Replace:').'</span><br />';
 6789:         }
 6790:     }
 6791:     if (keys(%error) == 0) {
 6792:         if ($switchserver) {
 6793:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 6794:         } else {
 6795:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 6796:                          '<input type="file" name="scantronformat" /></span>';
 6797:         }
 6798:     }
 6799:     $datatable .= '</td></tr>';
 6800:     $$rowtotal ++;
 6801:     return $datatable;
 6802: }
 6803: 
 6804: sub legacy_scantronformat {
 6805:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
 6806:     my ($url,$error);
 6807:     my @statinfo = &Apache::lonnet::stat_file($newurl);
 6808:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
 6809:         (my $result,$url) =
 6810:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
 6811:                          '','',$newfile);
 6812:         if ($result ne 'ok') {
 6813:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
 6814:         }
 6815:     }
 6816:     return ($url,$error);
 6817: }
 6818: 
 6819: sub print_scantronconfig {
 6820:     my ($dom,$settings,$rowtotal) = @_;
 6821:     my $itemcount = 2;
 6822:     my $is_checked = ' checked="checked"';
 6823:     my %optionson = (
 6824:                      hdr => ' checked="checked"',
 6825:                      pad => ' checked="checked"',
 6826:                      rem => ' checked="checked"',
 6827:                     );
 6828:     my %optionsoff = (
 6829:                       hdr => '',
 6830:                       pad => '',
 6831:                       rem => '',
 6832:                      );
 6833:     my $currcsvsty = 'none';
 6834:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
 6835:     my @fields = &scantroncsv_fields();
 6836:     my %titles = &scantronconfig_titles();
 6837:     if (ref($settings) eq 'HASH') {
 6838:         if (ref($settings->{config}) eq 'HASH') {
 6839:             if ($settings->{config}->{dat}) {
 6840:                 $checked{'dat'} = $is_checked;
 6841:             }
 6842:             if (ref($settings->{config}->{csv}) eq 'HASH') {
 6843:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
 6844:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
 6845:                     if (keys(%csvfields) > 0) {
 6846:                         $checked{'csv'} = $is_checked;
 6847:                         $currcsvsty = 'block';
 6848:                     }
 6849:                 }
 6850:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
 6851:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
 6852:                     foreach my $option (keys(%optionson)) {
 6853:                         unless ($csvoptions{$option}) {
 6854:                             $optionsoff{$option} = $optionson{$option};
 6855:                             $optionson{$option} = '';
 6856:                         }
 6857:                     }
 6858:                 }
 6859:             }
 6860:         } else {
 6861:             $checked{'dat'} = $is_checked;
 6862:         }
 6863:     } else {
 6864:         $checked{'dat'} = $is_checked;
 6865:     }
 6866:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
 6867:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 6868:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
 6869:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
 6870:     foreach my $item ('dat','csv') {
 6871:         my $id;
 6872:         if ($item eq 'csv') {
 6873:             $id = 'id="scantronconfcsv" ';
 6874:         }
 6875:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
 6876:                       $titles{$item}.'</label>'.('&nbsp;'x3);
 6877:         if ($item eq 'csv') {
 6878:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
 6879:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
 6880:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
 6881:             foreach my $col (@fields) {
 6882:                 my $selnone;
 6883:                 if ($csvfields{$col} eq '') {
 6884:                     $selnone = ' selected="selected"';
 6885:                 }
 6886:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
 6887:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
 6888:                               '<option value=""'.$selnone.'></option>';
 6889:                 for (my $i=0; $i<20; $i++) {
 6890:                     my $shown = $i+1;
 6891:                     my $sel;
 6892:                     unless ($selnone) {
 6893:                         if (exists($csvfields{$col})) {
 6894:                             if ($csvfields{$col} == $i) {
 6895:                                 $sel = ' selected="selected"';
 6896:                             }
 6897:                         }
 6898:                     }
 6899:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
 6900:                 }
 6901:                 $datatable .= '</select></td></tr>';
 6902:            }
 6903:            $datatable .= '</table></fieldset>'.
 6904:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
 6905:                          '<legend>'.&mt('CSV Options').'</legend>';
 6906:            foreach my $option ('hdr','pad','rem') {
 6907:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
 6908:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
 6909:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
 6910:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
 6911:            }
 6912:            $datatable .= '</fieldset>';
 6913:            $itemcount ++;
 6914:         }
 6915:     }
 6916:     $datatable .= '</td></tr>';
 6917:     $$rowtotal ++;
 6918:     return $datatable;
 6919: }
 6920: 
 6921: sub scantronconfig_titles {
 6922:     return &Apache::lonlocal::texthash(
 6923:                                           dat => 'Standard format (.dat)',
 6924:                                           csv => 'Comma separated values (.csv)',
 6925:                                           hdr => 'Remove first line in file (contains column titles)',
 6926:                                           pad => 'Prepend 0s to PaperID',
 6927:                                           rem => 'Remove leading spaces (except Question Response columns)',
 6928:                                           CODE => 'CODE',
 6929:                                           ID   => 'Student ID',
 6930:                                           PaperID => 'Paper ID',
 6931:                                           FirstName => 'First Name',
 6932:                                           LastName => 'Last Name',
 6933:                                           FirstQuestion => 'First Question Response',
 6934:                                           Section => 'Section',
 6935:     );
 6936: }
 6937: 
 6938: sub scantroncsv_fields {
 6939:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
 6940: }
 6941: 
 6942: sub print_coursecategories {
 6943:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
 6944:     my $datatable;
 6945:     if ($position eq 'top') {
 6946:         my (%checked);
 6947:         my @catitems = ('unauth','auth');
 6948:         my @cattypes = ('std','domonly','codesrch','none');
 6949:         $checked{'unauth'} = 'std';
 6950:         $checked{'auth'} = 'std';
 6951:         if (ref($settings) eq 'HASH') {
 6952:             foreach my $type (@cattypes) {
 6953:                 if ($type eq $settings->{'unauth'}) {
 6954:                     $checked{'unauth'} = $type;
 6955:                 }
 6956:                 if ($type eq $settings->{'auth'}) {
 6957:                     $checked{'auth'} = $type;
 6958:                 }
 6959:             }
 6960:         }
 6961:         my %lt = &Apache::lonlocal::texthash (
 6962:                                                unauth   => 'Catalog type for unauthenticated users',
 6963:                                                auth     => 'Catalog type for authenticated users',
 6964:                                                none     => 'No catalog',
 6965:                                                std      => 'Standard catalog',
 6966:                                                domonly  => 'Domain-only catalog',
 6967:                                                codesrch => "Code search form",
 6968:                                              );
 6969:        my $itemcount = 0;
 6970:        foreach my $item (@catitems) {
 6971:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 6972:            $datatable .= '<tr '.$css_class.'>'.
 6973:                          '<td>'.$lt{$item}.'</td>'.
 6974:                          '<td class="LC_right_item"><span class="LC_nobreak">';
 6975:            foreach my $type (@cattypes) {
 6976:                my $ischecked;
 6977:                if ($checked{$item} eq $type) {
 6978:                    $ischecked=' checked="checked"';
 6979:                }
 6980:                $datatable .= '<label>'.
 6981:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
 6982:                              ' />'.$lt{$type}.'</label>&nbsp;';
 6983:            }
 6984:            $datatable .= '</span></td></tr>';
 6985:            $itemcount ++;
 6986:         }
 6987:         $$rowtotal += $itemcount;
 6988:     } elsif ($position eq 'middle') {
 6989:         my $toggle_cats_crs = ' ';
 6990:         my $toggle_cats_dom = ' checked="checked" ';
 6991:         my $can_cat_crs = ' ';
 6992:         my $can_cat_dom = ' checked="checked" ';
 6993:         my $toggle_catscomm_comm = ' ';
 6994:         my $toggle_catscomm_dom = ' checked="checked" ';
 6995:         my $can_catcomm_comm = ' ';
 6996:         my $can_catcomm_dom = ' checked="checked" ';
 6997: 
 6998:         if (ref($settings) eq 'HASH') {
 6999:             if ($settings->{'togglecats'} eq 'crs') {
 7000:                 $toggle_cats_crs = $toggle_cats_dom;
 7001:                 $toggle_cats_dom = ' ';
 7002:             }
 7003:             if ($settings->{'categorize'} eq 'crs') {
 7004:                 $can_cat_crs = $can_cat_dom;
 7005:                 $can_cat_dom = ' ';
 7006:             }
 7007:             if ($settings->{'togglecatscomm'} eq 'comm') {
 7008:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
 7009:                 $toggle_catscomm_dom = ' ';
 7010:             }
 7011:             if ($settings->{'categorizecomm'} eq 'comm') {
 7012:                 $can_catcomm_comm = $can_catcomm_dom;
 7013:                 $can_catcomm_dom = ' ';
 7014:             }
 7015:         }
 7016:         my %title = &Apache::lonlocal::texthash (
 7017:                      togglecats     => 'Show/Hide a course in catalog',
 7018:                      togglecatscomm => 'Show/Hide a community in catalog',
 7019:                      categorize     => 'Assign a category to a course',
 7020:                      categorizecomm => 'Assign a category to a community',
 7021:                     );
 7022:         my %level = &Apache::lonlocal::texthash (
 7023:                      dom  => 'Set in Domain',
 7024:                      crs  => 'Set in Course',
 7025:                      comm => 'Set in Community',
 7026:                     );
 7027:         $datatable = '<tr class="LC_odd_row">'.
 7028:                   '<td>'.$title{'togglecats'}.'</td>'.
 7029:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 7030:                   '<input type="radio" name="togglecats"'.
 7031:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 7032:                   '<label><input type="radio" name="togglecats"'.
 7033:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
 7034:                   '</tr><tr>'.
 7035:                   '<td>'.$title{'categorize'}.'</td>'.
 7036:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 7037:                   '<label><input type="radio" name="categorize"'.
 7038:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 7039:                   '<label><input type="radio" name="categorize"'.
 7040:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
 7041:                   '</tr><tr class="LC_odd_row">'.
 7042:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
 7043:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 7044:                   '<input type="radio" name="togglecatscomm"'.
 7045:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 7046:                   '<label><input type="radio" name="togglecatscomm"'.
 7047:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
 7048:                   '</tr><tr>'.
 7049:                   '<td>'.$title{'categorizecomm'}.'</td>'.
 7050:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 7051:                   '<label><input type="radio" name="categorizecomm"'.
 7052:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 7053:                   '<label><input type="radio" name="categorizecomm"'.
 7054:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
 7055:                   '</tr>';
 7056:         $$rowtotal += 4;
 7057:     } else {
 7058:         my $css_class;
 7059:         my $itemcount = 1;
 7060:         my $cathash; 
 7061:         if (ref($settings) eq 'HASH') {
 7062:             $cathash = $settings->{'cats'};
 7063:         }
 7064:         if (ref($cathash) eq 'HASH') {
 7065:             my (@cats,@trails,%allitems,%idx,@jsarray);
 7066:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
 7067:                                                    \%allitems,\%idx,\@jsarray);
 7068:             my $maxdepth = scalar(@cats);
 7069:             my $colattrib = '';
 7070:             if ($maxdepth > 2) {
 7071:                 $colattrib = ' colspan="2" ';
 7072:             }
 7073:             my @path;
 7074:             if (@cats > 0) {
 7075:                 if (ref($cats[0]) eq 'ARRAY') {
 7076:                     my $numtop = @{$cats[0]};
 7077:                     my $maxnum = $numtop;
 7078:                     my %default_names = (
 7079:                           instcode    => &mt('Official courses'),
 7080:                           communities => &mt('Communities'),
 7081:                     );
 7082: 
 7083:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
 7084:                         ($cathash->{'instcode::0'} eq '') ||
 7085:                         (!grep(/^communities$/,@{$cats[0]})) || 
 7086:                         ($cathash->{'communities::0'} eq '')) {
 7087:                         $maxnum ++;
 7088:                     }
 7089:                     my $lastidx;
 7090:                     for (my $i=0; $i<$numtop; $i++) {
 7091:                         my $parent = $cats[0][$i];
 7092:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7093:                         my $item = &escape($parent).'::0';
 7094:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
 7095:                         $lastidx = $idx{$item};
 7096:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 7097:                                       .'<select name="'.$item.'"'.$chgstr.'>';
 7098:                         for (my $k=0; $k<=$maxnum; $k++) {
 7099:                             my $vpos = $k+1;
 7100:                             my $selstr;
 7101:                             if ($k == $i) {
 7102:                                 $selstr = ' selected="selected" ';
 7103:                             }
 7104:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 7105:                         }
 7106:                         $datatable .= '</select></span></td><td>';
 7107:                         if ($parent eq 'instcode' || $parent eq 'communities') {
 7108:                             $datatable .=  '<span class="LC_nobreak">'
 7109:                                            .$default_names{$parent}.'</span>';
 7110:                             if ($parent eq 'instcode') {
 7111:                                 $datatable .= '<br /><span class="LC_nobreak">('
 7112:                                               .&mt('with institutional codes')
 7113:                                               .')</span></td><td'.$colattrib.'>';
 7114:                             } else {
 7115:                                 $datatable .= '<table><tr><td>';
 7116:                             }
 7117:                             $datatable .= '<span class="LC_nobreak">'
 7118:                                           .'<label><input type="radio" name="'
 7119:                                           .$parent.'" value="1" checked="checked" />'
 7120:                                           .&mt('Display').'</label>';
 7121:                             if ($parent eq 'instcode') {
 7122:                                 $datatable .= '&nbsp;';
 7123:                             } else {
 7124:                                 $datatable .= '</span></td></tr><tr><td>'
 7125:                                               .'<span class="LC_nobreak">';
 7126:                             }
 7127:                             $datatable .= '<label><input type="radio" name="'
 7128:                                           .$parent.'" value="0" />'
 7129:                                           .&mt('Do not display').'</label></span>';
 7130:                             if ($parent eq 'communities') {
 7131:                                 $datatable .= '</td></tr></table>';
 7132:                             }
 7133:                             $datatable .= '</td>';
 7134:                         } else {
 7135:                             $datatable .= $parent
 7136:                                           .'&nbsp;<span class="LC_nobreak"><label>'
 7137:                                           .'<input type="checkbox" name="deletecategory" '
 7138:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
 7139:                         }
 7140:                         my $depth = 1;
 7141:                         push(@path,$parent);
 7142:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
 7143:                         pop(@path);
 7144:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 7145:                         $itemcount ++;
 7146:                     }
 7147:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7148:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
 7149:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
 7150:                     for (my $k=0; $k<=$maxnum; $k++) {
 7151:                         my $vpos = $k+1;
 7152:                         my $selstr;
 7153:                         if ($k == $numtop) {
 7154:                             $selstr = ' selected="selected" ';
 7155:                         }
 7156:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 7157:                     }
 7158:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
 7159:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
 7160:                                   .'</tr>'."\n";
 7161:                     $itemcount ++;
 7162:                     foreach my $default ('instcode','communities') {
 7163:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
 7164:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7165:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
 7166:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
 7167:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
 7168:                             for (my $k=0; $k<=$maxnum; $k++) {
 7169:                                 my $vpos = $k+1;
 7170:                                 my $selstr;
 7171:                                 if ($k == $maxnum) {
 7172:                                     $selstr = ' selected="selected" ';
 7173:                                 }
 7174:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 7175:                             }
 7176:                             $datatable .= '</select></span></td>'.
 7177:                                           '<td><span class="LC_nobreak">'.
 7178:                                           $default_names{$default}.'</span>';
 7179:                             if ($default eq 'instcode') {
 7180:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
 7181:                                               .&mt('with institutional codes').')</span>';
 7182:                             }
 7183:                             $datatable .= '</td>'
 7184:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
 7185:                                           .&mt('Display').'</label>&nbsp;'
 7186:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
 7187:                                           .&mt('Do not display').'</label></span></td></tr>';
 7188:                         }
 7189:                     }
 7190:                 }
 7191:             } else {
 7192:                 $datatable .= &initialize_categories($itemcount);
 7193:             }
 7194:         } else {
 7195:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
 7196:                           .&initialize_categories($itemcount);
 7197:         }
 7198:         $$rowtotal += $itemcount;
 7199:     }
 7200:     return $datatable;
 7201: }
 7202: 
 7203: sub print_serverstatuses {
 7204:     my ($dom,$settings,$rowtotal) = @_;
 7205:     my $datatable;
 7206:     my @pages = &serverstatus_pages();
 7207:     my (%namedaccess,%machineaccess);
 7208:     foreach my $type (@pages) {
 7209:         $namedaccess{$type} = '';
 7210:         $machineaccess{$type}= '';
 7211:     }
 7212:     if (ref($settings) eq 'HASH') {
 7213:         foreach my $type (@pages) {
 7214:             if (exists($settings->{$type})) {
 7215:                 if (ref($settings->{$type}) eq 'HASH') {
 7216:                     foreach my $key (keys(%{$settings->{$type}})) {
 7217:                         if ($key eq 'namedusers') {
 7218:                             $namedaccess{$type} = $settings->{$type}->{$key};
 7219:                         } elsif ($key eq 'machines') {
 7220:                             $machineaccess{$type} = $settings->{$type}->{$key};
 7221:                         }
 7222:                     }
 7223:                 }
 7224:             }
 7225:         }
 7226:     }
 7227:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
 7228:     my $rownum = 0;
 7229:     my $css_class;
 7230:     foreach my $type (@pages) {
 7231:         $rownum ++;
 7232:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 7233:         $datatable .= '<tr'.$css_class.'>'.
 7234:                       '<td><span class="LC_nobreak">'.
 7235:                       $titles->{$type}.'</span></td>'.
 7236:                       '<td class="LC_left_item">'.
 7237:                       '<input type="text" name="'.$type.'_namedusers" '.
 7238:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
 7239:                       '<td class="LC_right_item">'.
 7240:                       '<span class="LC_nobreak">'.
 7241:                       '<input type="text" name="'.$type.'_machines" '.
 7242:                       'value="'.$machineaccess{$type}.'" size="10" />'.
 7243:                       '</span></td></tr>'."\n";
 7244:     }
 7245:     $$rowtotal += $rownum;
 7246:     return $datatable;
 7247: }
 7248: 
 7249: sub serverstatus_pages {
 7250:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
 7251:             'checksums','clusterstatus','metadata_keywords','metadata_harvest',
 7252:             'takeoffline','takeonline','showenv','toggledebug','ping','domconf',
 7253:             'uniquecodes','diskusage','coursecatalog');
 7254: }
 7255: 
 7256: sub defaults_javascript {
 7257:     my ($settings) = @_;
 7258:     return unless (ref($settings) eq 'HASH');
 7259:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 7260:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
 7261:         if ($maxnum eq '') {
 7262:             $maxnum = 0;
 7263:         }
 7264:         $maxnum ++;
 7265:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
 7266:         return <<"ENDSCRIPT";
 7267: <script type="text/javascript">
 7268: // <![CDATA[
 7269: function reorderTypes(form,caller) {
 7270:     var changedVal;
 7271: $jstext 
 7272:     var newpos = 'addinststatus_pos';
 7273:     var current = new Array;
 7274:     var maxh = $maxnum;
 7275:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 7276:     var oldVal;
 7277:     if (caller == newpos) {
 7278:         changedVal = newitemVal;
 7279:     } else {
 7280:         var curritem = 'inststatus_pos_'+caller;
 7281:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
 7282:         current[newitemVal] = newpos;
 7283:     }
 7284:     for (var i=0; i<inststatuses.length; i++) {
 7285:         if (inststatuses[i] != caller) {
 7286:             var elementName = 'inststatus_pos_'+inststatuses[i];
 7287:             if (form.elements[elementName]) {
 7288:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 7289:                 current[currVal] = elementName;
 7290:             }
 7291:         }
 7292:     }
 7293:     for (var j=0; j<maxh; j++) {
 7294:         if (current[j] == undefined) {
 7295:             oldVal = j;
 7296:         }
 7297:     }
 7298:     if (oldVal < changedVal) {
 7299:         for (var k=oldVal+1; k<=changedVal ; k++) {
 7300:            var elementName = current[k];
 7301:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 7302:         }
 7303:     } else {
 7304:         for (var k=changedVal; k<oldVal; k++) {
 7305:             var elementName = current[k];
 7306:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 7307:         }
 7308:     }
 7309:     return;
 7310: }
 7311: 
 7312: // ]]>
 7313: </script>
 7314: 
 7315: ENDSCRIPT
 7316:     }
 7317: }
 7318: 
 7319: sub passwords_javascript {
 7320:     my %intalert = &Apache::lonlocal::texthash (
 7321:         authcheck => 'Warning: disallowing login for an authenticated user if the stored cost is less than the default will require a password reset by/for the user.',
 7322:         authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
 7323:         passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
 7324:         passmax => 'Warning: maximum password length must be a positive integer (or blank).',
 7325:         passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
 7326:         passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
 7327:     );
 7328:     &js_escape(\%intalert);
 7329:     my $defmin = $Apache::lonnet::passwdmin;
 7330:     my $intauthjs = <<"ENDSCRIPT";
 7331: 
 7332: function warnIntAuth(field) {
 7333:     if (field.name == 'intauth_check') {
 7334:         if (field.value == '2') {
 7335:             alert('$intalert{authcheck}');
 7336:         }
 7337:     }
 7338:     if (field.name == 'intauth_cost') {
 7339:         field.value.replace(/\s/g,'');
 7340:         if (field.value != '') {
 7341:             var regexdigit=/^\\d+\$/;
 7342:             if (!regexdigit.test(field.value)) {
 7343:                 alert('$intalert{authcost}');
 7344:             }
 7345:         }
 7346:     }
 7347:     return;
 7348: }
 7349: 
 7350: function warnIntPass(field) {
 7351:     field.value.replace(/^\s+/,'');
 7352:     field.value.replace(/\s+\$/,'');
 7353:     var regexdigit=/^\\d+\$/;
 7354:     if (field.name == 'passwords_min') {
 7355:         if (field.value == '') {
 7356:             alert('$intalert{passmin}');
 7357:             field.value = '$defmin';
 7358:         } else {
 7359:             if (!regexdigit.test(field.value)) {
 7360:                 alert('$intalert{passmin}');
 7361:                 field.value = '$defmin';
 7362:             }
 7363:             var minval = parseInt(field.value,10);
 7364:             if (minval < $defmin) {
 7365:                 alert('$intalert{passmin}');
 7366:                 field.value = '$defmin';
 7367:             }
 7368:         }
 7369:     } else {
 7370:         if (field.value == '0') {
 7371:             field.value = '';
 7372:         }
 7373:         if (field.value != '') {
 7374:             if (field.name == 'passwords_expire') {
 7375:                 var regexpposnum=/^\\d+(|\\.\\d*)\$/;
 7376:                 if (!regexpposnum.test(field.value)) {
 7377:                     alert('$intalert{passexp}');
 7378:                     field.value = '';
 7379:                 } else {
 7380:                     var expval = parseFloat(field.value);
 7381:                     if (expval == 0) {
 7382:                         alert('$intalert{passexp}');
 7383:                         field.value = '';
 7384:                     }
 7385:                 }
 7386:             } else {
 7387:                 if (!regexdigit.test(field.value)) {
 7388:                     if (field.name == 'passwords_max') {
 7389:                         alert('$intalert{passmax}');
 7390:                     } else {
 7391:                         if (field.name == 'passwords_numsaved') {
 7392:                             alert('$intalert{passnum}');
 7393:                         }
 7394:                     }
 7395:                     field.value = '';
 7396:                 }
 7397:             }
 7398:         }
 7399:     }
 7400:     return;
 7401: }
 7402: 
 7403: ENDSCRIPT
 7404:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
 7405: }
 7406: 
 7407: sub coursecategories_javascript {
 7408:     my ($settings) = @_;
 7409:     my ($output,$jstext,$cathash);
 7410:     if (ref($settings) eq 'HASH') {
 7411:         $cathash = $settings->{'cats'};
 7412:     }
 7413:     if (ref($cathash) eq 'HASH') {
 7414:         my (@cats,@jsarray,%idx);
 7415:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
 7416:         if (@jsarray > 0) {
 7417:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
 7418:             for (my $i=0; $i<@jsarray; $i++) {
 7419:                 if (ref($jsarray[$i]) eq 'ARRAY') {
 7420:                     my $catstr = join('","',@{$jsarray[$i]});
 7421:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
 7422:                 }
 7423:             }
 7424:         }
 7425:     } else {
 7426:         $jstext  = '    var categories = Array(1);'."\n".
 7427:                    '    categories[0] = Array("instcode_pos");'."\n"; 
 7428:     }
 7429:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
 7430:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
 7431:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
 7432:     &js_escape(\$instcode_reserved);
 7433:     &js_escape(\$communities_reserved);
 7434:     &js_escape(\$choose_again);
 7435:     $output = <<"ENDSCRIPT";
 7436: <script type="text/javascript">
 7437: // <![CDATA[
 7438: function reorderCats(form,parent,item,idx) {
 7439:     var changedVal;
 7440: $jstext
 7441:     var newpos = 'addcategory_pos';
 7442:     if (parent == '') {
 7443:         var has_instcode = 0;
 7444:         var maxtop = categories[idx].length;
 7445:         for (var j=0; j<maxtop; j++) {
 7446:             if (categories[idx][j] == 'instcode::0') {
 7447:                 has_instcode == 1;
 7448:             }
 7449:         }
 7450:         if (has_instcode == 0) {
 7451:             categories[idx][maxtop] = 'instcode_pos';
 7452:         }
 7453:     } else {
 7454:         newpos += '_'+parent;
 7455:     }
 7456:     var maxh = 1 + categories[idx].length;
 7457:     var current = new Array;
 7458:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 7459:     if (item == newpos) {
 7460:         changedVal = newitemVal;
 7461:     } else {
 7462:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 7463:         current[newitemVal] = newpos;
 7464:     }
 7465:     for (var i=0; i<categories[idx].length; i++) {
 7466:         var elementName = categories[idx][i];
 7467:         if (elementName != item) {
 7468:             if (form.elements[elementName]) {
 7469:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 7470:                 current[currVal] = elementName;
 7471:             }
 7472:         }
 7473:     }
 7474:     var oldVal;
 7475:     for (var j=0; j<maxh; j++) {
 7476:         if (current[j] == undefined) {
 7477:             oldVal = j;
 7478:         }
 7479:     }
 7480:     if (oldVal < changedVal) {
 7481:         for (var k=oldVal+1; k<=changedVal ; k++) {
 7482:            var elementName = current[k];
 7483:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 7484:         }
 7485:     } else {
 7486:         for (var k=changedVal; k<oldVal; k++) {
 7487:             var elementName = current[k];
 7488:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 7489:         }
 7490:     }
 7491:     return;
 7492: }
 7493: 
 7494: function categoryCheck(form) {
 7495:     if (form.elements['addcategory_name'].value == 'instcode') {
 7496:         alert('$instcode_reserved\\n$choose_again');
 7497:         return false;
 7498:     }
 7499:     if (form.elements['addcategory_name'].value == 'communities') {
 7500:         alert('$communities_reserved\\n$choose_again');
 7501:         return false;
 7502:     }
 7503:     return true;
 7504: }
 7505: 
 7506: // ]]>
 7507: </script>
 7508: 
 7509: ENDSCRIPT
 7510:     return $output;
 7511: }
 7512: 
 7513: sub initialize_categories {
 7514:     my ($itemcount) = @_;
 7515:     my ($datatable,$css_class,$chgstr);
 7516:     my %default_names = (
 7517:                       instcode    => 'Official courses (with institutional codes)',
 7518:                       communities => 'Communities',
 7519:                         );
 7520:     my $select0 = ' selected="selected"';
 7521:     my $select1 = '';
 7522:     foreach my $default ('instcode','communities') {
 7523:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7524:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
 7525:         if ($default eq 'communities') {
 7526:             $select1 = $select0;
 7527:             $select0 = '';
 7528:         }
 7529:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 7530:                      .'<select name="'.$default.'_pos">'
 7531:                      .'<option value="0"'.$select0.'>1</option>'
 7532:                      .'<option value="1"'.$select1.'>2</option>'
 7533:                      .'<option value="2">3</option></select>&nbsp;'
 7534:                      .$default_names{$default}
 7535:                      .'</span></td><td><span class="LC_nobreak">'
 7536:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
 7537:                      .&mt('Display').'</label>&nbsp;<label>'
 7538:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
 7539:                  .'</label></span></td></tr>';
 7540:         $itemcount ++;
 7541:     }
 7542:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7543:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
 7544:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 7545:                   .'<select name="addcategory_pos"'.$chgstr.'>'
 7546:                   .'<option value="0">1</option>'
 7547:                   .'<option value="1">2</option>'
 7548:                   .'<option value="2" selected="selected">3</option></select>&nbsp;'
 7549:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
 7550:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
 7551:                   .'</td></tr>';
 7552:     return $datatable;
 7553: }
 7554: 
 7555: sub build_category_rows {
 7556:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
 7557:     my ($text,$name,$item,$chgstr);
 7558:     if (ref($cats) eq 'ARRAY') {
 7559:         my $maxdepth = scalar(@{$cats});
 7560:         if (ref($cats->[$depth]) eq 'HASH') {
 7561:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 7562:                 my $numchildren = @{$cats->[$depth]{$parent}};
 7563:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7564:                 $text .= '<td><table class="LC_data_table">';
 7565:                 my ($idxnum,$parent_name,$parent_item);
 7566:                 my $higher = $depth - 1;
 7567:                 if ($higher == 0) {
 7568:                     $parent_name = &escape($parent).'::'.$higher;
 7569:                 } else {
 7570:                     if (ref($path) eq 'ARRAY') {
 7571:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 7572:                     }
 7573:                 }
 7574:                 $parent_item = 'addcategory_pos_'.$parent_name;
 7575:                 for (my $j=0; $j<=$numchildren; $j++) {
 7576:                     if ($j < $numchildren) {
 7577:                         $name = $cats->[$depth]{$parent}[$j];
 7578:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
 7579:                         $idxnum = $idx->{$item};
 7580:                     } else {
 7581:                         $name = $parent_name;
 7582:                         $item = $parent_item;
 7583:                     }
 7584:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
 7585:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
 7586:                     for (my $i=0; $i<=$numchildren; $i++) {
 7587:                         my $vpos = $i+1;
 7588:                         my $selstr;
 7589:                         if ($j == $i) {
 7590:                             $selstr = ' selected="selected" ';
 7591:                         }
 7592:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
 7593:                     }
 7594:                     $text .= '</select>&nbsp;';
 7595:                     if ($j < $numchildren) {
 7596:                         my $deeper = $depth+1;
 7597:                         $text .= $name.'&nbsp;'
 7598:                                  .'<label><input type="checkbox" name="deletecategory" value="'
 7599:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
 7600:                         if(ref($path) eq 'ARRAY') {
 7601:                             push(@{$path},$name);
 7602:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
 7603:                             pop(@{$path});
 7604:                         }
 7605:                     } else {
 7606:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
 7607:                         if ($j == $numchildren) {
 7608:                             $text .= $name;
 7609:                         } else {
 7610:                             $text .= $item;
 7611:                         }
 7612:                         $text .= '" value="" />';
 7613:                     }
 7614:                     $text .= '</td></tr>';
 7615:                 }
 7616:                 $text .= '</table></td>';
 7617:             } else {
 7618:                 my $higher = $depth-1;
 7619:                 if ($higher == 0) {
 7620:                     $name = &escape($parent).'::'.$higher;
 7621:                 } else {
 7622:                     if (ref($path) eq 'ARRAY') {
 7623:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 7624:                     }
 7625:                 }
 7626:                 my $colspan;
 7627:                 if ($parent ne 'instcode') {
 7628:                     $colspan = $maxdepth - $depth - 1;
 7629:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
 7630:                 }
 7631:             }
 7632:         }
 7633:     }
 7634:     return $text;
 7635: }
 7636: 
 7637: sub modifiable_userdata_row {
 7638:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
 7639:         $rowid,$customcss,$rowstyle) = @_;
 7640:     my ($role,$rolename,$statustype);
 7641:     $role = $item;
 7642:     if ($context eq 'cancreate') {
 7643:         if ($item =~ /^(emailusername)_(.+)$/) {
 7644:             $role = $1;
 7645:             $statustype = $2;
 7646:             if (ref($usertypes) eq 'HASH') {
 7647:                 if ($usertypes->{$statustype}) {
 7648:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
 7649:                 } else {
 7650:                     $rolename = &mt('Data provided by user');
 7651:                 }
 7652:             }
 7653:         }
 7654:     } elsif ($context eq 'selfcreate') {
 7655:         if (ref($usertypes) eq 'HASH') {
 7656:             $rolename = $usertypes->{$role};
 7657:         } else {
 7658:             $rolename = $role;
 7659:         }
 7660:     } else {
 7661:         if ($role eq 'cr') {
 7662:             $rolename = &mt('Custom role');
 7663:         } else {
 7664:             $rolename = &Apache::lonnet::plaintext($role);
 7665:         }
 7666:     }
 7667:     my (@fields,%fieldtitles);
 7668:     if (ref($fieldsref) eq 'ARRAY') {
 7669:         @fields = @{$fieldsref};
 7670:     } else {
 7671:         @fields = ('lastname','firstname','middlename','generation',
 7672:                    'permanentemail','id');
 7673:     }
 7674:     if ((ref($titlesref) eq 'HASH')) {
 7675:         %fieldtitles = %{$titlesref};
 7676:     } else {
 7677:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 7678:     }
 7679:     my $output;
 7680:     my $css_class;
 7681:     if ($rowcount%2) {
 7682:         $css_class = 'LC_odd_row';
 7683:     }
 7684:     if ($customcss) {
 7685:         $css_class .= " $customcss";
 7686:     }
 7687:     $css_class =~ s/^\s+//;
 7688:     if ($css_class) {
 7689:         $css_class = ' class="'.$css_class.'"';
 7690:     }
 7691:     if ($rowstyle) {
 7692:         $css_class .= ' style="'.$rowstyle.'"';
 7693:     }
 7694:     if ($rowid) {
 7695:         $rowid = ' id="'.$rowid.'"';
 7696:     }
 7697: 
 7698:     $output = '<tr '.$css_class.$rowid.'>'.
 7699:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
 7700:               '<td class="LC_left_item" colspan="2"><table>';
 7701:     my $rem;
 7702:     my %checks;
 7703:     if (ref($settings) eq 'HASH') {
 7704:         if (ref($settings->{$context}) eq 'HASH') {
 7705:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
 7706:                 my $hashref = $settings->{$context}->{$role};
 7707:                 if ($role eq 'emailusername') {
 7708:                     if ($statustype) {
 7709:                         if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
 7710:                             $hashref = $settings->{$context}->{$role}->{$statustype};
 7711:                             if (ref($hashref) eq 'HASH') { 
 7712:                                 foreach my $field (@fields) {
 7713:                                     if ($hashref->{$field}) {
 7714:                                         $checks{$field} = $hashref->{$field};
 7715:                                     }
 7716:                                 }
 7717:                             }
 7718:                         }
 7719:                     }
 7720:                 } else {
 7721:                     if (ref($hashref) eq 'HASH') {
 7722:                         foreach my $field (@fields) {
 7723:                             if ($hashref->{$field}) {
 7724:                                 $checks{$field} = ' checked="checked" ';
 7725:                             }
 7726:                         }
 7727:                     }
 7728:                 }
 7729:             }
 7730:         }
 7731:     }
 7732: 
 7733:     my $total = scalar(@fields);
 7734:     for (my $i=0; $i<$total; $i++) {
 7735:         $rem = $i%($numinrow);
 7736:         if ($rem == 0) {
 7737:             if ($i > 0) {
 7738:                 $output .= '</tr>';
 7739:             }
 7740:             $output .= '<tr>';
 7741:         }
 7742:         my $check = ' ';
 7743:         unless ($role eq 'emailusername') {
 7744:             if (exists($checks{$fields[$i]})) {
 7745:                 $check = $checks{$fields[$i]};
 7746:             } else {
 7747:                 if ($role eq 'st') {
 7748:                     if (ref($settings) ne 'HASH') {
 7749:                         $check = ' checked="checked" '; 
 7750:                     }
 7751:                 }
 7752:             }
 7753:         }
 7754:         $output .= '<td class="LC_left_item">'.
 7755:                    '<span class="LC_nobreak">';
 7756:         if ($role eq 'emailusername') {
 7757:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
 7758:                 $checks{$fields[$i]} = 'omit';
 7759:             }
 7760:             foreach my $option ('required','optional','omit') {
 7761:                 my $checked='';
 7762:                 if ($checks{$fields[$i]} eq $option) {
 7763:                     $checked='checked="checked" ';
 7764:                 }
 7765:                 $output .= '<label>'.
 7766:                            '<input type="radio" name="canmodify_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
 7767:                            &mt($option).'</label>'.('&nbsp;' x2);
 7768:             }
 7769:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
 7770:         } else {
 7771:             $output .= '<label>'.
 7772:                        '<input type="checkbox" name="canmodify_'.$role.'" '.
 7773:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
 7774:                        '</label>';
 7775:         }
 7776:         $output .= '</span></td>';
 7777:     }
 7778:     $rem = $total%$numinrow;
 7779:     my $colsleft;
 7780:     if ($rem) {
 7781:         $colsleft = $numinrow - $rem;
 7782:     }
 7783:     if ($colsleft > 1) {
 7784:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7785:                    '&nbsp;</td>';
 7786:     } elsif ($colsleft == 1) {
 7787:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 7788:     }
 7789:     $output .= '</tr></table></td></tr>';
 7790:     return $output;
 7791: }
 7792: 
 7793: sub insttypes_row {
 7794:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
 7795:         $customcss,$rowstyle) = @_;
 7796:     my %lt = &Apache::lonlocal::texthash (
 7797:                       cansearch => 'Users allowed to search',
 7798:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
 7799:                       lockablenames => 'User preference to lock name',
 7800:                       selfassign    => 'Self-reportable affiliations',
 7801:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
 7802:              );
 7803:     my $showdom;
 7804:     if ($context eq 'cansearch') {
 7805:         $showdom = ' ('.$dom.')';
 7806:     }
 7807:     my $class = 'LC_left_item';
 7808:     if ($context eq 'statustocreate') {
 7809:         $class = 'LC_right_item';
 7810:     }
 7811:     my $css_class;
 7812:     if ($$rowtotal%2) {
 7813:         $css_class = 'LC_odd_row';
 7814:     }
 7815:     if ($customcss) {
 7816:         $css_class .= ' '.$customcss;
 7817:     }
 7818:     $css_class =~ s/^\s+//;
 7819:     if ($css_class) {
 7820:         $css_class = ' class="'.$css_class.'"';
 7821:     }
 7822:     if ($rowstyle) {
 7823:         $css_class .= ' style="'.$rowstyle.'"';
 7824:     }
 7825:     if ($onclick) {
 7826:         $onclick = 'onclick="'.$onclick.'" ';
 7827:     }
 7828:     my $output = '<tr'.$css_class.'>'.
 7829:                  '<td>'.$lt{$context}.$showdom.
 7830:                  '</td><td class="'.$class.'" colspan="2"><table>';
 7831:     my $rem;
 7832:     if (ref($types) eq 'ARRAY') {
 7833:         for (my $i=0; $i<@{$types}; $i++) {
 7834:             if (defined($usertypes->{$types->[$i]})) {
 7835:                 my $rem = $i%($numinrow);
 7836:                 if ($rem == 0) {
 7837:                     if ($i > 0) {
 7838:                         $output .= '</tr>';
 7839:                     }
 7840:                     $output .= '<tr>';
 7841:                 }
 7842:                 my $check = ' ';
 7843:                 if (ref($settings) eq 'HASH') {
 7844:                     if (ref($settings->{$context}) eq 'ARRAY') {
 7845:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
 7846:                             $check = ' checked="checked" ';
 7847:                         }
 7848:                     } elsif (ref($settings->{$context}) eq 'HASH') {
 7849:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
 7850:                             $check = ' checked="checked" ';
 7851:                         }
 7852:                     } elsif ($context eq 'statustocreate') {
 7853:                         $check = ' checked="checked" ';
 7854:                     }
 7855:                 }
 7856:                 $output .= '<td class="LC_left_item">'.
 7857:                            '<span class="LC_nobreak"><label>'.
 7858:                            '<input type="checkbox" name="'.$context.'" '.
 7859:                            'value="'.$types->[$i].'"'.$check.$onclick.'/>'.
 7860:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 7861:             }
 7862:         }
 7863:         $rem = @{$types}%($numinrow);
 7864:     }
 7865:     my $colsleft = $numinrow - $rem;
 7866:     if ($context eq 'overrides') {
 7867:         if ($colsleft > 1) {
 7868:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 7869:         } else {
 7870:             $output .= '<td class="LC_left_item">';
 7871:         }
 7872:         $output .= '&nbsp;';
 7873:     } else {
 7874:         if ($rem == 0) {
 7875:             $output .= '<tr>';
 7876:         }
 7877:         if ($colsleft > 1) {
 7878:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 7879:         } else {
 7880:             $output .= '<td class="LC_left_item">';
 7881:         }
 7882:         my $defcheck = ' ';
 7883:         if (ref($settings) eq 'HASH') {  
 7884:             if (ref($settings->{$context}) eq 'ARRAY') {
 7885:                 if (grep(/^default$/,@{$settings->{$context}})) {
 7886:                     $defcheck = ' checked="checked" ';
 7887:                 }
 7888:             } elsif ($context eq 'statustocreate') {
 7889:                 $defcheck = ' checked="checked" ';
 7890:             }
 7891:         }
 7892:         $output .= '<span class="LC_nobreak"><label>'.
 7893:                    '<input type="checkbox" name="'.$context.'" '.
 7894:                    'value="default"'.$defcheck.$onclick.' />'.
 7895:                    $othertitle.'</label></span>';
 7896:     }
 7897:     $output .= '</td></tr></table></td></tr>';
 7898:     return $output;
 7899: }
 7900: 
 7901: sub sorted_searchtitles {
 7902:     my %searchtitles = &Apache::lonlocal::texthash(
 7903:                          'uname' => 'username',
 7904:                          'lastname' => 'last name',
 7905:                          'lastfirst' => 'last name, first name',
 7906:                      );
 7907:     my @titleorder = ('uname','lastname','lastfirst');
 7908:     return (\%searchtitles,\@titleorder);
 7909: }
 7910: 
 7911: sub sorted_searchtypes {
 7912:     my %srchtypes_desc = (
 7913:                            exact    => 'is exact match',
 7914:                            contains => 'contains ..',
 7915:                            begins   => 'begins with ..',
 7916:                          );
 7917:     my @srchtypeorder = ('exact','begins','contains');
 7918:     return (\%srchtypes_desc,\@srchtypeorder);
 7919: }
 7920: 
 7921: sub usertype_update_row {
 7922:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
 7923:     my $datatable;
 7924:     my $numinrow = 4;
 7925:     foreach my $type (@{$types}) {
 7926:         if (defined($usertypes->{$type})) {
 7927:             $$rownums ++;
 7928:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
 7929:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
 7930:                           '</td><td class="LC_left_item"><table>';
 7931:             for (my $i=0; $i<@{$fields}; $i++) {
 7932:                 my $rem = $i%($numinrow);
 7933:                 if ($rem == 0) {
 7934:                     if ($i > 0) {
 7935:                         $datatable .= '</tr>';
 7936:                     }
 7937:                     $datatable .= '<tr>';
 7938:                 }
 7939:                 my $check = ' ';
 7940:                 if (ref($settings) eq 'HASH') {
 7941:                     if (ref($settings->{'fields'}) eq 'HASH') {
 7942:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
 7943:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
 7944:                                 $check = ' checked="checked" ';
 7945:                             }
 7946:                         }
 7947:                     }
 7948:                 }
 7949: 
 7950:                 if ($i == @{$fields}-1) {
 7951:                     my $colsleft = $numinrow - $rem;
 7952:                     if ($colsleft > 1) {
 7953:                         $datatable .= '<td colspan="'.$colsleft.'">';
 7954:                     } else {
 7955:                         $datatable .= '<td>';
 7956:                     }
 7957:                 } else {
 7958:                     $datatable .= '<td>';
 7959:                 }
 7960:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7961:                               '<input type="checkbox" name="updateable_'.$type.
 7962:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
 7963:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
 7964:             }
 7965:             $datatable .= '</tr></table></td></tr>';
 7966:         }
 7967:     }
 7968:     return $datatable;
 7969: }
 7970: 
 7971: sub modify_login {
 7972:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
 7973:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
 7974:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon);
 7975:     %title = ( coursecatalog => 'Display course catalog',
 7976:                adminmail => 'Display administrator E-mail address',
 7977:                helpdesk  => 'Display "Contact Helpdesk" link',
 7978:                newuser => 'Link for visitors to create a user account',
 7979:                loginheader => 'Log-in box header');
 7980:     @offon = ('off','on');
 7981:     if (ref($domconfig{login}) eq 'HASH') {
 7982:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
 7983:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
 7984:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
 7985:             }
 7986:         }
 7987:     }
 7988:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
 7989:                                            \%domconfig,\%loginhash);
 7990:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 7991:     foreach my $item (@toggles) {
 7992:         $loginhash{login}{$item} = $env{'form.'.$item};
 7993:     }
 7994:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
 7995:     if (ref($colchanges{'login'}) eq 'HASH') {  
 7996:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
 7997:                                          \%loginhash);
 7998:     }
 7999: 
 8000:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8001:     my %domservers = &Apache::lonnet::get_servers($dom);
 8002:     my @loginvia_attribs = ('serverpath','custompath','exempt');
 8003:     if (keys(%servers) > 1) {
 8004:         foreach my $lonhost (keys(%servers)) {
 8005:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
 8006:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
 8007:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
 8008:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
 8009:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
 8010:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 8011:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 8012:                         $changes{'loginvia'}{$lonhost} = 1;
 8013:                     } else {
 8014:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
 8015:                         $changes{'loginvia'}{$lonhost} = 1;
 8016:                     }
 8017:                 } else {
 8018:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 8019:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 8020:                         $changes{'loginvia'}{$lonhost} = 1;
 8021:                     }
 8022:                 }
 8023:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
 8024:                     foreach my $item (@loginvia_attribs) {
 8025:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
 8026:                     }
 8027:                 } else {
 8028:                     foreach my $item (@loginvia_attribs) {
 8029:                         my $new = $env{'form.'.$lonhost.'_'.$item};
 8030:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
 8031:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
 8032:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
 8033:                                 $new = '/';
 8034:                             }
 8035:                         }
 8036:                         if (($item eq 'custompath') && 
 8037:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
 8038:                             $new = '';
 8039:                         }
 8040:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
 8041:                             $changes{'loginvia'}{$lonhost} = 1;
 8042:                         }
 8043:                         if ($item eq 'exempt') {
 8044:                             $new = &check_exempt_addresses($new);
 8045:                         }
 8046:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
 8047:                     }
 8048:                 }
 8049:             } else {
 8050:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
 8051:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
 8052:                     $changes{'loginvia'}{$lonhost} = 1;
 8053:                     foreach my $item (@loginvia_attribs) {
 8054:                         my $new = $env{'form.'.$lonhost.'_'.$item};
 8055:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
 8056:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
 8057:                                 $new = '/';
 8058:                             }
 8059:                         }
 8060:                         if (($item eq 'custompath') && 
 8061:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
 8062:                             $new = '';
 8063:                         }
 8064:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
 8065:                     }
 8066:                 }
 8067:             }
 8068:         }
 8069:     }
 8070: 
 8071:     my $servadm = $r->dir_config('lonAdmEMail');
 8072:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 8073:     if (ref($domconfig{'login'}) eq 'HASH') {
 8074:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
 8075:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
 8076:                 if ($lang eq 'nolang') {
 8077:                     push(@currlangs,$lang);
 8078:                 } elsif (defined($langchoices{$lang})) {
 8079:                     push(@currlangs,$lang);
 8080:                 } else {
 8081:                     next;
 8082:                 }
 8083:             }
 8084:         }
 8085:     }
 8086:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
 8087:     if (@currlangs > 0) {
 8088:         foreach my $lang (@currlangs) {
 8089:             if (grep(/^\Q$lang\E$/,@delurls)) {
 8090:                 $changes{'helpurl'}{$lang} = 1;
 8091:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
 8092:                 $changes{'helpurl'}{$lang} = 1;
 8093:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
 8094:                 push(@newlangs,$lang);
 8095:             } else {
 8096:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
 8097:             }
 8098:         }
 8099:     }
 8100:     unless (grep(/^nolang$/,@currlangs)) {
 8101:         if ($env{'form.loginhelpurl_nolang.filename'}) {
 8102:             $changes{'helpurl'}{'nolang'} = 1;
 8103:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
 8104:             push(@newlangs,'nolang');
 8105:         }
 8106:     }
 8107:     if ($env{'form.loginhelpurl_add_lang'}) {
 8108:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
 8109:             ($env{'form.loginhelpurl_add_file.filename'})) {
 8110:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
 8111:             $addedfile = $env{'form.loginhelpurl_add_lang'};
 8112:         }
 8113:     }
 8114:     if ((@newlangs > 0) || ($addedfile)) {
 8115:         my $error;
 8116:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 8117:         if ($configuserok eq 'ok') {
 8118:             if ($switchserver) {
 8119:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
 8120:             } elsif ($author_ok eq 'ok') {
 8121:                 my @allnew = @newlangs;
 8122:                 if ($addedfile ne '') {
 8123:                     push(@allnew,$addedfile);
 8124:                 }
 8125:                 foreach my $lang (@allnew) {
 8126:                     my $formelem = 'loginhelpurl_'.$lang;
 8127:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
 8128:                         $formelem = 'loginhelpurl_add_file';
 8129:                     }
 8130:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 8131:                                                                "help/$lang",'','',$newfile{$lang});
 8132:                     if ($result eq 'ok') {
 8133:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
 8134:                         $changes{'helpurl'}{$lang} = 1;
 8135:                     } else {
 8136:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
 8137:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 8138:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
 8139:                             (!grep(/^\Q$lang\E$/,@delurls))) {
 8140:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
 8141:                         }
 8142:                     }
 8143:                 }
 8144:             } else {
 8145:                 $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);
 8146:             }
 8147:         } else {
 8148:             $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);
 8149:         }
 8150:         if ($error) {
 8151:             &Apache::lonnet::logthis($error);
 8152:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 8153:         }
 8154:     }
 8155: 
 8156:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
 8157:     if (ref($domconfig{'login'}) eq 'HASH') {
 8158:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
 8159:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
 8160:                 if ($domservers{$lonhost}) {
 8161:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
 8162:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
 8163:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
 8164:                     }
 8165:                 }
 8166:             }
 8167:         }
 8168:     }
 8169:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
 8170:     foreach my $lonhost (sort(keys(%domservers))) {
 8171:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
 8172:             $changes{'headtag'}{$lonhost} = 1;
 8173:         } else {
 8174:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
 8175:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
 8176:             }
 8177:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
 8178:                 push(@newhosts,$lonhost);
 8179:             } elsif ($currheadtagurls{$lonhost}) {
 8180:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
 8181:                 if ($currexempt{$lonhost}) {
 8182:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
 8183:                         $changes{'headtag'}{$lonhost} = 1;
 8184:                     }
 8185:                 } elsif ($possexempt{$lonhost}) {
 8186:                     $changes{'headtag'}{$lonhost} = 1;
 8187:                 }
 8188:                 if ($possexempt{$lonhost}) {
 8189:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
 8190:                 }
 8191:             }
 8192:         }
 8193:     }
 8194:     if (@newhosts) {
 8195:         my $error;
 8196:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 8197:         if ($configuserok eq 'ok') {
 8198:             if ($switchserver) {
 8199:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
 8200:             } elsif ($author_ok eq 'ok') {
 8201:                 foreach my $lonhost (@newhosts) {
 8202:                     my $formelem = 'loginheadtag_'.$lonhost;
 8203:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
 8204:                                                                           "login/headtag/$lonhost",'','',
 8205:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
 8206:                     if ($result eq 'ok') {
 8207:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
 8208:                         $changes{'headtag'}{$lonhost} = 1;
 8209:                         if ($possexempt{$lonhost}) {
 8210:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
 8211:                         }
 8212:                     } else {
 8213:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
 8214:                                            $newheadtagurls{$lonhost},$result);
 8215:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
 8216:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
 8217:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
 8218:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
 8219:                         }
 8220:                     }
 8221:                 }
 8222:             } else {
 8223:                 $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);
 8224:             }
 8225:         } else {
 8226:             $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);
 8227:         }
 8228:         if ($error) {
 8229:             &Apache::lonnet::logthis($error);
 8230:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 8231:         }
 8232:     }
 8233:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
 8234: 
 8235:     my $defaulthelpfile = '/adm/loginproblems.html';
 8236:     my $defaulttext = &mt('Default in use');
 8237: 
 8238:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
 8239:                                              $dom);
 8240:     if ($putresult eq 'ok') {
 8241:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 8242:         my %defaultchecked = (
 8243:                     'coursecatalog' => 'on',
 8244:                     'helpdesk'      => 'on',
 8245:                     'adminmail'     => 'off',
 8246:                     'newuser'       => 'off',
 8247:         );
 8248:         if (ref($domconfig{'login'}) eq 'HASH') {
 8249:             foreach my $item (@toggles) {
 8250:                 if ($defaultchecked{$item} eq 'on') { 
 8251:                     if (($domconfig{'login'}{$item} eq '0') &&
 8252:                         ($env{'form.'.$item} eq '1')) {
 8253:                         $changes{$item} = 1;
 8254:                     } elsif (($domconfig{'login'}{$item} eq '' ||
 8255:                               $domconfig{'login'}{$item} eq '1') &&
 8256:                              ($env{'form.'.$item} eq '0')) {
 8257:                         $changes{$item} = 1;
 8258:                     }
 8259:                 } elsif ($defaultchecked{$item} eq 'off') {
 8260:                     if (($domconfig{'login'}{$item} eq '1') &&
 8261:                         ($env{'form.'.$item} eq '0')) {
 8262:                         $changes{$item} = 1;
 8263:                     } elsif (($domconfig{'login'}{$item} eq '' ||
 8264:                               $domconfig{'login'}{$item} eq '0') &&
 8265:                              ($env{'form.'.$item} eq '1')) {
 8266:                         $changes{$item} = 1;
 8267:                     }
 8268:                 }
 8269:             }
 8270:         }
 8271:         if (keys(%changes) > 0 || $colchgtext) {
 8272:             &Apache::loncommon::devalidate_domconfig_cache($dom);
 8273:             if (ref($lastactref) eq 'HASH') {
 8274:                 $lastactref->{'domainconfig'} = 1;
 8275:             }
 8276:             $resulttext = &mt('Changes made:').'<ul>';
 8277:             foreach my $item (sort(keys(%changes))) {
 8278:                 if ($item eq 'loginvia') {
 8279:                     if (ref($changes{$item}) eq 'HASH') {
 8280:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
 8281:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
 8282:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
 8283:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
 8284:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
 8285:                                     $protocol = 'http' if ($protocol ne 'https');
 8286:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
 8287: 
 8288:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
 8289:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
 8290:                                     } else {
 8291:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
 8292:                                     }
 8293:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
 8294:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
 8295:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
 8296:                                     }
 8297:                                     $resulttext .= '</li>';
 8298:                                 } else {
 8299:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
 8300:                                 }
 8301:                             } else {
 8302:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
 8303:                             }
 8304:                         }
 8305:                         $resulttext .= '</ul></li>';
 8306:                     }
 8307:                 } elsif ($item eq 'helpurl') {
 8308:                     if (ref($changes{$item}) eq 'HASH') {
 8309:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
 8310:                             if (grep(/^\Q$lang\E$/,@delurls)) {
 8311:                                 my ($chg,$link);
 8312:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
 8313:                                 if ($lang eq 'nolang') {
 8314:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
 8315:                                 } else {
 8316:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
 8317:                                 }
 8318:                                 $resulttext .= '<li>'.$chg.'</li>';
 8319:                             } else {
 8320:                                 my $chg;
 8321:                                 if ($lang eq 'nolang') {
 8322:                                     $chg = &mt('custom log-in help file for no preferred language');
 8323:                                 } else {
 8324:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
 8325:                                 }
 8326:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
 8327:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
 8328:                                                       '?inhibitmenu=yes',$chg,600,500).
 8329:                                                '</li>';
 8330:                             }
 8331:                         }
 8332:                     }
 8333:                 } elsif ($item eq 'headtag') {
 8334:                     if (ref($changes{$item}) eq 'HASH') {
 8335:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
 8336:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
 8337:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
 8338:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
 8339:                                 $resulttext .= '<li><a href="'.
 8340:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
 8341:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 8342:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
 8343:                                 if ($possexempt{$lonhost}) {
 8344:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
 8345:                                 } else {
 8346:                                     $resulttext .= &mt('included for any client IP');
 8347:                                 }
 8348:                                 $resulttext .= '</li>';
 8349:                             }
 8350:                         }
 8351:                     }
 8352:                 } elsif ($item eq 'captcha') {
 8353:                     if (ref($loginhash{'login'}) eq 'HASH') {
 8354:                         my $chgtxt;
 8355:                         if ($loginhash{'login'}{$item} eq 'notused') {
 8356:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
 8357:                         } else {
 8358:                             my %captchas = &captcha_phrases();
 8359:                             if ($captchas{$loginhash{'login'}{$item}}) {
 8360:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
 8361:                             } else {
 8362:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
 8363:                             }
 8364:                         }
 8365:                         $resulttext .= '<li>'.$chgtxt.'</li>';
 8366:                     }
 8367:                 } elsif ($item eq 'recaptchakeys') {
 8368:                     if (ref($loginhash{'login'}) eq 'HASH') {
 8369:                         my ($privkey,$pubkey);
 8370:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
 8371:                             $pubkey = $loginhash{'login'}{$item}{'public'};
 8372:                             $privkey = $loginhash{'login'}{$item}{'private'};
 8373:                         }
 8374:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
 8375:                         if (!$pubkey) {
 8376:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
 8377:                         } else {
 8378:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
 8379:                         }
 8380:                         if (!$privkey) {
 8381:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
 8382:                         } else {
 8383:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
 8384:                         }
 8385:                         $chgtxt .= '</ul>';
 8386:                         $resulttext .= '<li>'.$chgtxt.'</li>';
 8387:                     }
 8388:                 } elsif ($item eq 'recaptchaversion') {
 8389:                     if (ref($loginhash{'login'}) eq 'HASH') {
 8390:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
 8391:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
 8392:                                            '</li>';
 8393:                         }
 8394:                     }
 8395:                 } else {
 8396:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
 8397:                 }
 8398:             }
 8399:             $resulttext .= $colchgtext.'</ul>';
 8400:         } else {
 8401:             $resulttext = &mt('No changes made to log-in page settings');
 8402:         }
 8403:     } else {
 8404:         $resulttext = '<span class="LC_error">'.
 8405: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 8406:     }
 8407:     if ($errors) {
 8408:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
 8409:                        $errors.'</ul>';
 8410:     }
 8411:     return $resulttext;
 8412: }
 8413: 
 8414: sub check_exempt_addresses {
 8415:     my ($iplist) = @_;
 8416:     $iplist =~ s/^\s+//;
 8417:     $iplist =~ s/\s+$//;
 8418:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
 8419:     my (@okips,$new);
 8420:     foreach my $ip (@poss_ips) {
 8421:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
 8422:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
 8423:                 push(@okips,$ip);
 8424:             }
 8425:         }
 8426:     }
 8427:     if (@okips > 0) {
 8428:         $new = join(',',@okips);
 8429:     } else {
 8430:         $new = '';
 8431:     }
 8432:     return $new;
 8433: }
 8434: 
 8435: sub color_font_choices {
 8436:     my %choices =
 8437:         &Apache::lonlocal::texthash (
 8438:             img => "Header",
 8439:             bgs => "Background colors",
 8440:             links => "Link colors",
 8441:             images => "Images",
 8442:             font => "Font color",
 8443:             fontmenu => "Font menu",
 8444:             pgbg => "Page",
 8445:             tabbg => "Header",
 8446:             sidebg => "Border",
 8447:             link => "Link",
 8448:             alink => "Active link",
 8449:             vlink => "Visited link",
 8450:         );
 8451:     return %choices;
 8452: }
 8453: 
 8454: sub modify_rolecolors {
 8455:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
 8456:     my ($resulttext,%rolehash);
 8457:     $rolehash{'rolecolors'} = {};
 8458:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
 8459:         if ($domconfig{'rolecolors'} eq '') {
 8460:             $domconfig{'rolecolors'} = {};
 8461:         }
 8462:     }
 8463:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
 8464:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
 8465:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
 8466:                                              $dom);
 8467:     if ($putresult eq 'ok') {
 8468:         if (keys(%changes) > 0) {
 8469:             &Apache::loncommon::devalidate_domconfig_cache($dom);
 8470:             if (ref($lastactref) eq 'HASH') {
 8471:                 $lastactref->{'domainconfig'} = 1;
 8472:             }
 8473:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
 8474:                                              $rolehash{'rolecolors'});
 8475:         } else {
 8476:             $resulttext = &mt('No changes made to default color schemes');
 8477:         }
 8478:     } else {
 8479:         $resulttext = '<span class="LC_error">'.
 8480: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 8481:     }
 8482:     if ($errors) {
 8483:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
 8484:                        $errors.'</ul>';
 8485:     }
 8486:     return $resulttext;
 8487: }
 8488: 
 8489: sub modify_colors {
 8490:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
 8491:     my (%changes,%choices);
 8492:     my @bgs;
 8493:     my @links = ('link','alink','vlink');
 8494:     my @logintext;
 8495:     my @images;
 8496:     my $servadm = $r->dir_config('lonAdmEMail');
 8497:     my $errors;
 8498:     my %defaults;
 8499:     foreach my $role (@{$roles}) {
 8500:         if ($role eq 'login') {
 8501:             %choices = &login_choices();
 8502:             @logintext = ('textcol','bgcol');
 8503:         } else {
 8504:             %choices = &color_font_choices();
 8505:         }
 8506:         if ($role eq 'login') {
 8507:             @images = ('img','logo','domlogo','login');
 8508:             @bgs = ('pgbg','mainbg','sidebg');
 8509:         } else {
 8510:             @images = ('img');
 8511:             @bgs = ('pgbg','tabbg','sidebg');
 8512:         }
 8513:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
 8514:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
 8515:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
 8516:         }
 8517:         if ($role eq 'login') {
 8518:             foreach my $item (@logintext) {
 8519:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
 8520:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
 8521:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
 8522:                 }
 8523:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
 8524:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
 8525:                 }
 8526:             }
 8527:         } else {
 8528:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
 8529:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
 8530:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
 8531:             }
 8532:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
 8533:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
 8534:             }
 8535:         }
 8536:         foreach my $item (@bgs) {
 8537:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
 8538:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
 8539:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
 8540:             }
 8541:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
 8542:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
 8543:             }
 8544:         }
 8545:         foreach my $item (@links) {
 8546:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
 8547:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
 8548:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
 8549:             }
 8550:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
 8551:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
 8552:             }
 8553:         }
 8554:         my ($configuserok,$author_ok,$switchserver) = 
 8555:             &config_check($dom,$confname,$servadm);
 8556:         my ($width,$height) = &thumb_dimensions();
 8557:         if (ref($domconfig->{$role}) ne 'HASH') {
 8558:             $domconfig->{$role} = {};
 8559:         }
 8560:         foreach my $img (@images) {
 8561:             if (($role eq 'login') && (($img eq 'img') || ($img eq 'logo'))) {  
 8562:                 if (defined($env{'form.login_showlogo_'.$img})) {
 8563:                     $confhash->{$role}{'showlogo'}{$img} = 1;
 8564:                 } else { 
 8565:                     $confhash->{$role}{'showlogo'}{$img} = 0;
 8566:                 }
 8567:             } 
 8568: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
 8569: 		 && !defined($domconfig->{$role}{$img})
 8570: 		 && !$env{'form.'.$role.'_del_'.$img}
 8571: 		 && $env{'form.'.$role.'_import_'.$img}) {
 8572: 		# import the old configured image from the .tab setting
 8573: 		# if they haven't provided a new one 
 8574: 		$domconfig->{$role}{$img} = 
 8575: 		    $env{'form.'.$role.'_import_'.$img};
 8576: 	    }
 8577:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
 8578:                 my $error;
 8579:                 if ($configuserok eq 'ok') {
 8580:                     if ($switchserver) {
 8581:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
 8582:                     } else {
 8583:                         if ($author_ok eq 'ok') {
 8584:                             my ($result,$logourl) = 
 8585:                                 &publishlogo($r,'upload',$role.'_'.$img,
 8586:                                            $dom,$confname,$img,$width,$height);
 8587:                             if ($result eq 'ok') {
 8588:                                 $confhash->{$role}{$img} = $logourl;
 8589:                                 $changes{$role}{'images'}{$img} = 1;
 8590:                             } else {
 8591:                                 $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);
 8592:                             }
 8593:                         } else {
 8594:                             $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);
 8595:                         }
 8596:                     }
 8597:                 } else {
 8598:                     $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);
 8599:                 }
 8600:                 if ($error) {
 8601:                     &Apache::lonnet::logthis($error);
 8602:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 8603:                 }
 8604:             } elsif ($domconfig->{$role}{$img} ne '') {
 8605:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 8606:                     my $error;
 8607:                     if ($configuserok eq 'ok') {
 8608: # is confname an author?
 8609:                         if ($switchserver eq '') {
 8610:                             if ($author_ok eq 'ok') {
 8611:                                 my ($result,$logourl) = 
 8612:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
 8613:                                             $dom,$confname,$img,$width,$height);
 8614:                                 if ($result eq 'ok') {
 8615:                                     $confhash->{$role}{$img} = $logourl;
 8616: 				    $changes{$role}{'images'}{$img} = 1;
 8617:                                 }
 8618:                             }
 8619:                         }
 8620:                     }
 8621:                 }
 8622:             }
 8623:         }
 8624:         if (ref($domconfig) eq 'HASH') {
 8625:             if (ref($domconfig->{$role}) eq 'HASH') {
 8626:                 foreach my $img (@images) {
 8627:                     if ($domconfig->{$role}{$img} ne '') {
 8628:                         if ($env{'form.'.$role.'_del_'.$img}) {
 8629:                             $confhash->{$role}{$img} = '';
 8630:                             $changes{$role}{'images'}{$img} = 1;
 8631:                         } else {
 8632:                             if ($confhash->{$role}{$img} eq '') {
 8633:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
 8634:                             }
 8635:                         }
 8636:                     } else {
 8637:                         if ($env{'form.'.$role.'_del_'.$img}) {
 8638:                             $confhash->{$role}{$img} = '';
 8639:                             $changes{$role}{'images'}{$img} = 1;
 8640:                         } 
 8641:                     }
 8642:                     if (($role eq 'login') && (($img eq 'logo') || ($img eq 'img'))) {
 8643:                         if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
 8644:                             if ($confhash->{$role}{'showlogo'}{$img} ne 
 8645:                                 $domconfig->{$role}{'showlogo'}{$img}) {
 8646:                                 $changes{$role}{'showlogo'}{$img} = 1; 
 8647:                             }
 8648:                         } else {
 8649:                             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
 8650:                                 $changes{$role}{'showlogo'}{$img} = 1;
 8651:                             }
 8652:                         }
 8653:                     }
 8654:                 }
 8655:                 if ($domconfig->{$role}{'font'} ne '') {
 8656:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
 8657:                         $changes{$role}{'font'} = 1;
 8658:                     }
 8659:                 } else {
 8660:                     if ($confhash->{$role}{'font'}) {
 8661:                         $changes{$role}{'font'} = 1;
 8662:                     }
 8663:                 }
 8664:                 if ($role ne 'login') {
 8665:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
 8666:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
 8667:                             $changes{$role}{'fontmenu'} = 1;
 8668:                         }
 8669:                     } else {
 8670:                         if ($confhash->{$role}{'fontmenu'}) {
 8671:                             $changes{$role}{'fontmenu'} = 1;
 8672:                         }
 8673:                     }
 8674:                 }
 8675:                 foreach my $item (@bgs) {
 8676:                     if ($domconfig->{$role}{$item} ne '') {
 8677:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
 8678:                             $changes{$role}{'bgs'}{$item} = 1;
 8679:                         } 
 8680:                     } else {
 8681:                         if ($confhash->{$role}{$item}) {
 8682:                             $changes{$role}{'bgs'}{$item} = 1;
 8683:                         }
 8684:                     }
 8685:                 }
 8686:                 foreach my $item (@links) {
 8687:                     if ($domconfig->{$role}{$item} ne '') {
 8688:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
 8689:                             $changes{$role}{'links'}{$item} = 1;
 8690:                         }
 8691:                     } else {
 8692:                         if ($confhash->{$role}{$item}) {
 8693:                             $changes{$role}{'links'}{$item} = 1;
 8694:                         }
 8695:                     }
 8696:                 }
 8697:                 foreach my $item (@logintext) {
 8698:                     if ($domconfig->{$role}{$item} ne '') {
 8699:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
 8700:                             $changes{$role}{'logintext'}{$item} = 1;
 8701:                         }
 8702:                     } else {
 8703:                         if ($confhash->{$role}{$item}) {
 8704:                             $changes{$role}{'logintext'}{$item} = 1;
 8705:                         }
 8706:                     }
 8707:                 }
 8708:             } else {
 8709:                 &default_change_checker($role,\@images,\@links,\@bgs,
 8710:                                         \@logintext,$confhash,\%changes); 
 8711:             }
 8712:         } else {
 8713:             &default_change_checker($role,\@images,\@links,\@bgs,
 8714:                                     \@logintext,$confhash,\%changes); 
 8715:         }
 8716:     }
 8717:     return ($errors,%changes);
 8718: }
 8719: 
 8720: sub config_check {
 8721:     my ($dom,$confname,$servadm) = @_;
 8722:     my ($configuserok,$author_ok,$switchserver,%currroles);
 8723:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
 8724:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
 8725:                                                    $confname,$servadm);
 8726:     if ($configuserok eq 'ok') {
 8727:         $switchserver = &check_switchserver($dom,$confname);
 8728:         if ($switchserver eq '') {
 8729:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
 8730:         }
 8731:     }
 8732:     return ($configuserok,$author_ok,$switchserver);
 8733: }
 8734: 
 8735: sub default_change_checker {
 8736:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
 8737:     foreach my $item (@{$links}) {
 8738:         if ($confhash->{$role}{$item}) {
 8739:             $changes->{$role}{'links'}{$item} = 1;
 8740:         }
 8741:     }
 8742:     foreach my $item (@{$bgs}) {
 8743:         if ($confhash->{$role}{$item}) {
 8744:             $changes->{$role}{'bgs'}{$item} = 1;
 8745:         }
 8746:     }
 8747:     foreach my $item (@{$logintext}) {
 8748:         if ($confhash->{$role}{$item}) {
 8749:             $changes->{$role}{'logintext'}{$item} = 1;
 8750:         }
 8751:     }
 8752:     foreach my $img (@{$images}) {
 8753:         if ($env{'form.'.$role.'_del_'.$img}) {
 8754:             $confhash->{$role}{$img} = '';
 8755:             $changes->{$role}{'images'}{$img} = 1;
 8756:         }
 8757:         if ($role eq 'login') {
 8758:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
 8759:                 $changes->{$role}{'showlogo'}{$img} = 1;
 8760:             }
 8761:         }
 8762:     }
 8763:     if ($confhash->{$role}{'font'}) {
 8764:         $changes->{$role}{'font'} = 1;
 8765:     }
 8766: }
 8767: 
 8768: sub display_colorchgs {
 8769:     my ($dom,$changes,$roles,$confhash) = @_;
 8770:     my (%choices,$resulttext);
 8771:     if (!grep(/^login$/,@{$roles})) {
 8772:         $resulttext = &mt('Changes made:').'<br />';
 8773:     }
 8774:     foreach my $role (@{$roles}) {
 8775:         if ($role eq 'login') {
 8776:             %choices = &login_choices();
 8777:         } else {
 8778:             %choices = &color_font_choices();
 8779:         }
 8780:         if (ref($changes->{$role}) eq 'HASH') {
 8781:             if ($role ne 'login') {
 8782:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
 8783:             }
 8784:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
 8785:                 if ($role ne 'login') {
 8786:                     $resulttext .= '<ul>';
 8787:                 }
 8788:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
 8789:                     if ($role ne 'login') {
 8790:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
 8791:                     }
 8792:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
 8793:                         if (($role eq 'login') && ($key eq 'showlogo')) {
 8794:                             if ($confhash->{$role}{$key}{$item}) {
 8795:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
 8796:                             } else {
 8797:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
 8798:                             }
 8799:                         } elsif ($confhash->{$role}{$item} eq '') {
 8800:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
 8801:                         } else {
 8802:                             my $newitem = $confhash->{$role}{$item};
 8803:                             if ($key eq 'images') {
 8804:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" valign="bottom" />';
 8805:                             }
 8806:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
 8807:                         }
 8808:                     }
 8809:                     if ($role ne 'login') {
 8810:                         $resulttext .= '</ul></li>';
 8811:                     }
 8812:                 } else {
 8813:                     if ($confhash->{$role}{$key} eq '') {
 8814:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
 8815:                     } else {
 8816:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
 8817:                     }
 8818:                 }
 8819:                 if ($role ne 'login') {
 8820:                     $resulttext .= '</ul>';
 8821:                 }
 8822:             }
 8823:         }
 8824:     }
 8825:     return $resulttext;
 8826: }
 8827: 
 8828: sub thumb_dimensions {
 8829:     return ('200','50');
 8830: }
 8831: 
 8832: sub check_dimensions {
 8833:     my ($inputfile) = @_;
 8834:     my ($fullwidth,$fullheight);
 8835:     if ($inputfile =~ m|^[/\w.\-]+$|) {
 8836:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
 8837:             my $imageinfo = <PIPE>;
 8838:             if (!close(PIPE)) {
 8839:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
 8840:             }
 8841:             chomp($imageinfo);
 8842:             my ($fullsize) = 
 8843:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
 8844:             if ($fullsize) {
 8845:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
 8846:             }
 8847:         }
 8848:     }
 8849:     return ($fullwidth,$fullheight);
 8850: }
 8851: 
 8852: sub check_configuser {
 8853:     my ($uhome,$dom,$confname,$servadm) = @_;
 8854:     my ($configuserok,%currroles);
 8855:     if ($uhome eq 'no_host') {
 8856:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
 8857:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
 8858:         $configuserok = 
 8859:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
 8860:                              $configpass,'','','','','',undef,$servadm);
 8861:     } else {
 8862:         $configuserok = 'ok';
 8863:         %currroles = 
 8864:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
 8865:     }
 8866:     return ($configuserok,%currroles);
 8867: }
 8868: 
 8869: sub check_authorstatus {
 8870:     my ($dom,$confname,%currroles) = @_;
 8871:     my $author_ok;
 8872:     if (!$currroles{':'.$dom.':au'}) {
 8873:         my $start = time;
 8874:         my $end = 0;
 8875:         $author_ok = 
 8876:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
 8877:                                         'au',$end,$start,'','','domconfig');
 8878:     } else {
 8879:         $author_ok = 'ok';
 8880:     }
 8881:     return $author_ok;
 8882: }
 8883: 
 8884: sub publishlogo {
 8885:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
 8886:     my ($output,$fname,$logourl);
 8887:     if ($action eq 'upload') {
 8888:         $fname=$env{'form.'.$formname.'.filename'};
 8889:         chop($env{'form.'.$formname});
 8890:     } else {
 8891:         ($fname) = ($formname =~ /([^\/]+)$/);
 8892:     }
 8893:     if ($savefileas ne '') {
 8894:         $fname = $savefileas;
 8895:     }
 8896:     $fname=&Apache::lonnet::clean_filename($fname);
 8897: # See if there is anything left
 8898:     unless ($fname) { return ('error: no uploaded file'); }
 8899:     $fname="$subdir/$fname";
 8900:     my $docroot=$r->dir_config('lonDocRoot');
 8901:     my $filepath="$docroot/priv";
 8902:     my $relpath = "$dom/$confname";
 8903:     my ($fnamepath,$file,$fetchthumb);
 8904:     $file=$fname;
 8905:     if ($fname=~m|/|) {
 8906:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 8907:     }
 8908:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
 8909:     my $count;
 8910:     for ($count=5;$count<=$#parts;$count++) {
 8911:         $filepath.="/$parts[$count]";
 8912:         if ((-e $filepath)!=1) {
 8913:             mkdir($filepath,02770);
 8914:         }
 8915:     }
 8916:     # Check for bad extension and disallow upload
 8917:     if ($file=~/\.(\w+)$/ &&
 8918:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
 8919:         $output = 
 8920:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
 8921:     } elsif ($file=~/\.(\w+)$/ &&
 8922:         !defined(&Apache::loncommon::fileembstyle($1))) {
 8923:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
 8924:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
 8925:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
 8926:     } elsif (-d "$filepath/$file") {
 8927:         $output = &mt('Filename is a directory name - rename the file and re-upload');
 8928:     } else {
 8929:         my $source = $filepath.'/'.$file;
 8930:         my $logfile;
 8931:         if (!open($logfile,">>",$source.'.log')) {
 8932:             return (&mt('No write permission to Authoring Space'));
 8933:         }
 8934:         print $logfile
 8935: "\n================= Publish ".localtime()." ================\n".
 8936: $env{'user.name'}.':'.$env{'user.domain'}."\n";
 8937: # Save the file
 8938:         if (!open(FH,">",$source)) {
 8939:             &Apache::lonnet::logthis('Failed to create '.$source);
 8940:             return (&mt('Failed to create file'));
 8941:         }
 8942:         if ($action eq 'upload') {
 8943:             if (!print FH ($env{'form.'.$formname})) {
 8944:                 &Apache::lonnet::logthis('Failed to write to '.$source);
 8945:                 return (&mt('Failed to write file'));
 8946:             }
 8947:         } else {
 8948:             my $original = &Apache::lonnet::filelocation('',$formname);
 8949:             if(!copy($original,$source)) {
 8950:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
 8951:                 return (&mt('Failed to write file'));
 8952:             }
 8953:         }
 8954:         close(FH);
 8955:         chmod(0660, $source); # Permissions to rw-rw---.
 8956: 
 8957:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
 8958:         my $copyfile=$targetdir.'/'.$file;
 8959: 
 8960:         my @parts=split(/\//,$targetdir);
 8961:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 8962:         for (my $count=5;$count<=$#parts;$count++) {
 8963:             $path.="/$parts[$count]";
 8964:             if (!-e $path) {
 8965:                 print $logfile "\nCreating directory ".$path;
 8966:                 mkdir($path,02770);
 8967:             }
 8968:         }
 8969:         my $versionresult;
 8970:         if (-e $copyfile) {
 8971:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
 8972:         } else {
 8973:             $versionresult = 'ok';
 8974:         }
 8975:         if ($versionresult eq 'ok') {
 8976:             if (copy($source,$copyfile)) {
 8977:                 print $logfile "\nCopied original source to ".$copyfile."\n";
 8978:                 $output = 'ok';
 8979:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
 8980:                 push(@{$modified_urls},[$copyfile,$source]);
 8981:                 my $metaoutput = 
 8982:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
 8983:                 unless ($registered_cleanup) {
 8984:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
 8985:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
 8986:                     $registered_cleanup=1;
 8987:                 }
 8988:             } else {
 8989:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
 8990:                 $output = &mt('Failed to copy file to RES space').", $!";
 8991:             }
 8992:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 8993:                 my $inputfile = $filepath.'/'.$file;
 8994:                 my $outfile = $filepath.'/'.'tn-'.$file;
 8995:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
 8996:                 if ($fullwidth ne '' && $fullheight ne '') { 
 8997:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
 8998:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 8999:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
 9000:                         system({$args[0]} @args);
 9001:                         chmod(0660, $filepath.'/tn-'.$file);
 9002:                         if (-e $outfile) {
 9003:                             my $copyfile=$targetdir.'/tn-'.$file;
 9004:                             if (copy($outfile,$copyfile)) {
 9005:                                 print $logfile "\nCopied source to ".$copyfile."\n";
 9006:                                 my $thumb_metaoutput = 
 9007:                                     &write_metadata($dom,$confname,$formname,
 9008:                                                     $targetdir,'tn-'.$file,$logfile);
 9009:                                 push(@{$modified_urls},[$copyfile,$outfile]);
 9010:                                 unless ($registered_cleanup) {
 9011:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
 9012:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
 9013:                                     $registered_cleanup=1;
 9014:                                 }
 9015:                             } else {
 9016:                                 print $logfile "\nUnable to write ".$copyfile.
 9017:                                                ':'.$!."\n";
 9018:                             }
 9019:                         }
 9020:                     }
 9021:                 }
 9022:             }
 9023:         } else {
 9024:             $output = $versionresult;
 9025:         }
 9026:     }
 9027:     return ($output,$logourl);
 9028: }
 9029: 
 9030: sub logo_versioning {
 9031:     my ($targetdir,$file,$logfile) = @_;
 9032:     my $target = $targetdir.'/'.$file;
 9033:     my ($maxversion,$fn,$extn,$output);
 9034:     $maxversion = 0;
 9035:     if ($file =~ /^(.+)\.(\w+)$/) {
 9036:         $fn=$1;
 9037:         $extn=$2;
 9038:     }
 9039:     opendir(DIR,$targetdir);
 9040:     while (my $filename=readdir(DIR)) {
 9041:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
 9042:             $maxversion=($1>$maxversion)?$1:$maxversion;
 9043:         }
 9044:     }
 9045:     $maxversion++;
 9046:     print $logfile "\nCreating old version ".$maxversion."\n";
 9047:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
 9048:     if (copy($target,$copyfile)) {
 9049:         print $logfile "Copied old target to ".$copyfile."\n";
 9050:         $copyfile=$copyfile.'.meta';
 9051:         if (copy($target.'.meta',$copyfile)) {
 9052:             print $logfile "Copied old target metadata to ".$copyfile."\n";
 9053:             $output = 'ok';
 9054:         } else {
 9055:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
 9056:             $output = &mt('Failed to copy old meta').", $!, ";
 9057:         }
 9058:     } else {
 9059:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
 9060:         $output = &mt('Failed to copy old target').", $!, ";
 9061:     }
 9062:     return $output;
 9063: }
 9064: 
 9065: sub write_metadata {
 9066:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
 9067:     my (%metadatafields,%metadatakeys,$output);
 9068:     $metadatafields{'title'}=$formname;
 9069:     $metadatafields{'creationdate'}=time;
 9070:     $metadatafields{'lastrevisiondate'}=time;
 9071:     $metadatafields{'copyright'}='public';
 9072:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
 9073:                                          $env{'user.domain'};
 9074:     $metadatafields{'authorspace'}=$confname.':'.$dom;
 9075:     $metadatafields{'domain'}=$dom;
 9076:     {
 9077:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
 9078:         my $mfh;
 9079:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
 9080:             foreach (sort(keys(%metadatafields))) {
 9081:                 unless ($_=~/\./) {
 9082:                     my $unikey=$_;
 9083:                     $unikey=~/^([A-Za-z]+)/;
 9084:                     my $tag=$1;
 9085:                     $tag=~tr/A-Z/a-z/;
 9086:                     print $mfh "\n\<$tag";
 9087:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
 9088:                         my $value=$metadatafields{$unikey.'.'.$_};
 9089:                         $value=~s/\"/\'\'/g;
 9090:                         print $mfh ' '.$_.'="'.$value.'"';
 9091:                     }
 9092:                     print $mfh '>'.
 9093:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
 9094:                             .'</'.$tag.'>';
 9095:                 }
 9096:             }
 9097:             $output = 'ok';
 9098:             print $logfile "\nWrote metadata";
 9099:             close($mfh);
 9100:         } else {
 9101:             print $logfile "\nFailed to open metadata file";
 9102:             $output = &mt('Could not write metadata');
 9103:         }
 9104:     }
 9105:     return $output;
 9106: }
 9107: 
 9108: sub notifysubscribed {
 9109:     foreach my $targetsource (@{$modified_urls}){
 9110:         next unless (ref($targetsource) eq 'ARRAY');
 9111:         my ($target,$source)=@{$targetsource};
 9112:         if ($source ne '') {
 9113:             if (open(my $logfh,">>",$source.'.log')) {
 9114:                 print $logfh "\nCleanup phase: Notifications\n";
 9115:                 my @subscribed=&subscribed_hosts($target);
 9116:                 foreach my $subhost (@subscribed) {
 9117:                     print $logfh "\nNotifying host ".$subhost.':';
 9118:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
 9119:                     print $logfh $reply;
 9120:                 }
 9121:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
 9122:                 foreach my $subhost (@subscribedmeta) {
 9123:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
 9124:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
 9125:                                                         $subhost);
 9126:                     print $logfh $reply;
 9127:                 }
 9128:                 print $logfh "\n============ Done ============\n";
 9129:                 close($logfh);
 9130:             }
 9131:         }
 9132:     }
 9133:     return OK;
 9134: }
 9135: 
 9136: sub subscribed_hosts {
 9137:     my ($target) = @_;
 9138:     my @subscribed;
 9139:     if (open(my $fh,"<","$target.subscription")) {
 9140:         while (my $subline=<$fh>) {
 9141:             if ($subline =~ /^($match_lonid):/) {
 9142:                 my $host = $1;
 9143:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
 9144:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
 9145:                         push(@subscribed,$host);
 9146:                     }
 9147:                 }
 9148:             }
 9149:         }
 9150:     }
 9151:     return @subscribed;
 9152: }
 9153: 
 9154: sub check_switchserver {
 9155:     my ($dom,$confname) = @_;
 9156:     my ($allowed,$switchserver);
 9157:     my $home = &Apache::lonnet::homeserver($confname,$dom);
 9158:     if ($home eq 'no_host') {
 9159:         $home = &Apache::lonnet::domain($dom,'primary');
 9160:     }
 9161:     my @ids=&Apache::lonnet::current_machine_ids();
 9162:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 9163:     if (!$allowed) {
 9164: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 9165:     }
 9166:     return $switchserver;
 9167: }
 9168: 
 9169: sub modify_quotas {
 9170:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
 9171:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
 9172:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
 9173:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
 9174:         $validationfieldsref);
 9175:     if ($action eq 'quotas') {
 9176:         $context = 'tools'; 
 9177:     } else {
 9178:         $context = $action;
 9179:     }
 9180:     if ($context eq 'requestcourses') {
 9181:         @usertools = ('official','unofficial','community','textbook');
 9182:         @options =('norequest','approval','validate','autolimit');
 9183:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 9184:         %titles = &courserequest_titles();
 9185:         $toolregexp = join('|',@usertools);
 9186:         %conditions = &courserequest_conditions();
 9187:         $confname = $dom.'-domainconfig';
 9188:         my $servadm = $r->dir_config('lonAdmEMail');
 9189:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
 9190:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
 9191:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
 9192:     } elsif ($context eq 'requestauthor') {
 9193:         @usertools = ('author');
 9194:         %titles = &authorrequest_titles();
 9195:     } else {
 9196:         @usertools = ('aboutme','blog','webdav','portfolio');
 9197:         %titles = &tool_titles();
 9198:     }
 9199:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 9200:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 9201:     foreach my $key (keys(%env)) {
 9202:         if ($context eq 'requestcourses') {
 9203:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
 9204:                 my $item = $1;
 9205:                 my $type = $2;
 9206:                 if ($type =~ /^limit_(.+)/) {
 9207:                     $limithash{$item}{$1} = $env{$key};
 9208:                 } else {
 9209:                     $confhash{$item}{$type} = $env{$key};
 9210:                 }
 9211:             }
 9212:         } elsif ($context eq 'requestauthor') {
 9213:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
 9214:                 $confhash{$1} = $env{$key};
 9215:             }
 9216:         } else {
 9217:             if ($key =~ /^form\.quota_(.+)$/) {
 9218:                 $confhash{'defaultquota'}{$1} = $env{$key};
 9219:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
 9220:                 $confhash{'authorquota'}{$1} = $env{$key};
 9221:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
 9222:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
 9223:             }
 9224:         }
 9225:     }
 9226:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 9227:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
 9228:         @approvalnotify = sort(@approvalnotify);
 9229:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
 9230:         my @crstypes = ('official','unofficial','community','textbook');
 9231:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
 9232:         foreach my $type (@hasuniquecode) {
 9233:             if (grep(/^\Q$type\E$/,@crstypes)) {
 9234:                 $confhash{'uniquecode'}{$type} = 1;
 9235:             }
 9236:         }
 9237:         my (%newbook,%allpos);
 9238:         if ($context eq 'requestcourses') {
 9239:             foreach my $type ('textbooks','templates') {
 9240:                 @{$allpos{$type}} = (); 
 9241:                 my $invalid;
 9242:                 if ($type eq 'textbooks') {
 9243:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
 9244:                 } else {
 9245:                     $invalid = &mt('Invalid LON-CAPA course for template');
 9246:                 }
 9247:                 if ($env{'form.'.$type.'_addbook'}) {
 9248:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
 9249:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
 9250:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
 9251:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
 9252:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
 9253:                         } else {
 9254:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
 9255:                             my $position = $env{'form.'.$type.'_addbook_pos'};
 9256:                             $position =~ s/\D+//g;
 9257:                             if ($position ne '') {
 9258:                                 $allpos{$type}[$position] = $newbook{$type};
 9259:                             }
 9260:                         }
 9261:                     } else {
 9262:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
 9263:                     }
 9264:                 }
 9265:             } 
 9266:         }
 9267:         if (ref($domconfig{$action}) eq 'HASH') {
 9268:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
 9269:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
 9270:                     $changes{'notify'}{'approval'} = 1;
 9271:                 }
 9272:             } else {
 9273:                 if ($confhash{'notify'}{'approval'}) {
 9274:                     $changes{'notify'}{'approval'} = 1;
 9275:                 }
 9276:             }
 9277:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
 9278:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
 9279:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
 9280:                         unless ($confhash{'uniquecode'}{$crstype}) {
 9281:                             $changes{'uniquecode'} = 1;
 9282:                         }
 9283:                     }
 9284:                     unless ($changes{'uniquecode'}) {
 9285:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
 9286:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
 9287:                                 $changes{'uniquecode'} = 1;
 9288:                             }
 9289:                         }
 9290:                     }
 9291:                } else {
 9292:                    $changes{'uniquecode'} = 1;
 9293:                }
 9294:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
 9295:                 $changes{'uniquecode'} = 1;
 9296:             }
 9297:             if ($context eq 'requestcourses') {
 9298:                 foreach my $type ('textbooks','templates') {
 9299:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
 9300:                         my %deletions;
 9301:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
 9302:                         if (@todelete) {
 9303:                             map { $deletions{$_} = 1; } @todelete;
 9304:                         }
 9305:                         my %imgdeletions;
 9306:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
 9307:                         if (@todeleteimages) {
 9308:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
 9309:                         }
 9310:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
 9311:                         for (my $i=0; $i<=$maxnum; $i++) {
 9312:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
 9313:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
 9314:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
 9315:                                 if ($deletions{$key}) {
 9316:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
 9317:                                         #FIXME need to obsolete item in RES space
 9318:                                     }
 9319:                                     next;
 9320:                                 } else {
 9321:                                     my $newpos = $env{'form.'.$itemid};
 9322:                                     $newpos =~ s/\D+//g;
 9323:                                     foreach my $item ('subject','title','publisher','author') {
 9324:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
 9325:                                                  ($type eq 'templates'));
 9326:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
 9327:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
 9328:                                             $changes{$type}{$key} = 1;
 9329:                                         }
 9330:                                     }
 9331:                                     $allpos{$type}[$newpos] = $key;
 9332:                                 }
 9333:                                 if ($imgdeletions{$key}) {
 9334:                                     $changes{$type}{$key} = 1;
 9335:                                     #FIXME need to obsolete item in RES space
 9336:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
 9337:                                     my ($cdom,$cnum) = split(/_/,$key);
 9338:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
 9339:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
 9340:                                     } else {
 9341:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
 9342:                                                                                       $cdom,$cnum,$type,$configuserok,
 9343:                                                                                       $switchserver,$author_ok);
 9344:                                         if ($imgurl) {
 9345:                                             $confhash{$type}{$key}{'image'} = $imgurl;
 9346:                                             $changes{$type}{$key} = 1; 
 9347:                                         }
 9348:                                         if ($error) {
 9349:                                             &Apache::lonnet::logthis($error);
 9350:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 9351:                                         }
 9352:                                     } 
 9353:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
 9354:                                     $confhash{$type}{$key}{'image'} = 
 9355:                                         $domconfig{$action}{$type}{$key}{'image'};
 9356:                                 }
 9357:                             }
 9358:                         }
 9359:                     }
 9360:                 }
 9361:             }
 9362:         } else {
 9363:             if ($confhash{'notify'}{'approval'}) {
 9364:                 $changes{'notify'}{'approval'} = 1;
 9365:             }
 9366:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
 9367:                 $changes{'uniquecode'} = 1;
 9368:             }
 9369:         }
 9370:         if ($context eq 'requestcourses') {
 9371:             foreach my $type ('textbooks','templates') {
 9372:                 if ($newbook{$type}) {
 9373:                     $changes{$type}{$newbook{$type}} = 1;
 9374:                     foreach my $item ('subject','title','publisher','author') {
 9375:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
 9376:                                  ($type eq 'template'));
 9377:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
 9378:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
 9379:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
 9380:                         }
 9381:                     }
 9382:                     if ($type eq 'textbooks') {
 9383:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
 9384:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
 9385:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
 9386:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
 9387:                             } else {
 9388:                                 my ($imageurl,$error) =
 9389:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
 9390:                                                             $configuserok,$switchserver,$author_ok);
 9391:                                 if ($imageurl) {
 9392:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
 9393:                                 }
 9394:                                 if ($error) {
 9395:                                     &Apache::lonnet::logthis($error);
 9396:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
 9397:                                 }
 9398:                             }
 9399:                         }
 9400:                     }
 9401:                 }
 9402:                 if (@{$allpos{$type}} > 0) {
 9403:                     my $idx = 0;
 9404:                     foreach my $item (@{$allpos{$type}}) {
 9405:                         if ($item ne '') {
 9406:                             $confhash{$type}{$item}{'order'} = $idx;
 9407:                             if (ref($domconfig{$action}) eq 'HASH') {
 9408:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
 9409:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
 9410:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
 9411:                                             $changes{$type}{$item} = 1;
 9412:                                         }
 9413:                                     }
 9414:                                 }
 9415:                             }
 9416:                             $idx ++;
 9417:                         }
 9418:                     }
 9419:                 }
 9420:             }
 9421:             if (ref($validationitemsref) eq 'ARRAY') {
 9422:                 foreach my $item (@{$validationitemsref}) {
 9423:                     if ($item eq 'fields') {
 9424:                         my @changed;
 9425:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
 9426:                         if (@{$confhash{'validation'}{$item}} > 0) {
 9427:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
 9428:                         }
 9429:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 9430:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 9431:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
 9432:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
 9433:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
 9434:                                 } else {
 9435:                                     @changed = @{$confhash{'validation'}{$item}};
 9436:                                 }
 9437:                             } else {
 9438:                                 @changed = @{$confhash{'validation'}{$item}};
 9439:                             }
 9440:                         } else {
 9441:                             @changed = @{$confhash{'validation'}{$item}};
 9442:                         }
 9443:                         if (@changed) {
 9444:                             if ($confhash{'validation'}{$item}) {
 9445:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
 9446:                             } else {
 9447:                                 $changes{'validation'}{$item} = &mt('None');
 9448:                             }
 9449:                         }
 9450:                     } else {
 9451:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
 9452:                         if ($item eq 'markup') {
 9453:                             if ($env{'form.requestcourses_validation_'.$item}) {
 9454:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
 9455:                             }
 9456:                         }
 9457:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 9458:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 9459:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
 9460:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
 9461:                                 }
 9462:                             } else {
 9463:                                 if ($confhash{'validation'}{$item} ne '') {
 9464:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
 9465:                                 }
 9466:                             }
 9467:                         } else {
 9468:                             if ($confhash{'validation'}{$item} ne '') {
 9469:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
 9470:                             }
 9471:                         }
 9472:                     }
 9473:                 }
 9474:             }
 9475:             if ($env{'form.validationdc'}) {
 9476:                 my $newval = $env{'form.validationdc'};
 9477:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
 9478:                 if (exists($domcoords{$newval})) {
 9479:                     $confhash{'validation'}{'dc'} = $newval;
 9480:                 }
 9481:             }
 9482:             if (ref($confhash{'validation'}) eq 'HASH') {
 9483:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 9484:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 9485:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
 9486:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
 9487:                                 if ($confhash{'validation'}{'dc'} eq '') {
 9488:                                     $changes{'validation'}{'dc'} = &mt('None');
 9489:                                 } else {
 9490:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 9491:                                 }
 9492:                             }
 9493:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
 9494:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 9495:                         }
 9496:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
 9497:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 9498:                     }
 9499:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
 9500:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
 9501:                 }
 9502:             } else {
 9503:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 9504:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 9505:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
 9506:                             $changes{'validation'}{'dc'} = &mt('None');
 9507:                         }
 9508:                     }
 9509:                 }
 9510:             }
 9511:         }
 9512:     } else {
 9513:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
 9514:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
 9515:     }
 9516:     foreach my $item (@usertools) {
 9517:         foreach my $type (@{$types},'default','_LC_adv') {
 9518:             my $unset; 
 9519:             if ($context eq 'requestcourses') {
 9520:                 $unset = '0';
 9521:                 if ($type eq '_LC_adv') {
 9522:                     $unset = '';
 9523:                 }
 9524:                 if ($confhash{$item}{$type} eq 'autolimit') {
 9525:                     $confhash{$item}{$type} .= '=';
 9526:                     unless ($limithash{$item}{$type} =~ /\D/) {
 9527:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
 9528:                     }
 9529:                 }
 9530:             } elsif ($context eq 'requestauthor') {
 9531:                 $unset = '0';
 9532:                 if ($type eq '_LC_adv') {
 9533:                     $unset = '';
 9534:                 }
 9535:             } else {
 9536:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
 9537:                     $confhash{$item}{$type} = 1;
 9538:                 } else {
 9539:                     $confhash{$item}{$type} = 0;
 9540:                 }
 9541:             }
 9542:             if (ref($domconfig{$action}) eq 'HASH') {
 9543:                 if ($action eq 'requestauthor') {
 9544:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
 9545:                         $changes{$type} = 1;
 9546:                     }
 9547:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
 9548:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
 9549:                         $changes{$item}{$type} = 1;
 9550:                     }
 9551:                 } else {
 9552:                     if ($context eq 'requestcourses') {
 9553:                         if ($confhash{$item}{$type} ne $unset) {
 9554:                             $changes{$item}{$type} = 1;
 9555:                         }
 9556:                     } else {
 9557:                         if (!$confhash{$item}{$type}) {
 9558:                             $changes{$item}{$type} = 1;
 9559:                         }
 9560:                     }
 9561:                 }
 9562:             } else {
 9563:                 if ($context eq 'requestcourses') {
 9564:                     if ($confhash{$item}{$type} ne $unset) {
 9565:                         $changes{$item}{$type} = 1;
 9566:                     }
 9567:                 } elsif ($context eq 'requestauthor') {
 9568:                     if ($confhash{$type} ne $unset) {
 9569:                         $changes{$type} = 1;
 9570:                     }
 9571:                 } else {
 9572:                     if (!$confhash{$item}{$type}) {
 9573:                         $changes{$item}{$type} = 1;
 9574:                     }
 9575:                 }
 9576:             }
 9577:         }
 9578:     }
 9579:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 9580:         if (ref($domconfig{'quotas'}) eq 'HASH') {
 9581:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 9582:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
 9583:                     if (exists($confhash{'defaultquota'}{$key})) {
 9584:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
 9585:                             $changes{'defaultquota'}{$key} = 1;
 9586:                         }
 9587:                     } else {
 9588:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
 9589:                     }
 9590:                 }
 9591:             } else {
 9592:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
 9593:                     if (exists($confhash{'defaultquota'}{$key})) {
 9594:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
 9595:                             $changes{'defaultquota'}{$key} = 1;
 9596:                         }
 9597:                     } else {
 9598:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
 9599:                     }
 9600:                 }
 9601:             }
 9602:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 9603:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
 9604:                     if (exists($confhash{'authorquota'}{$key})) {
 9605:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
 9606:                             $changes{'authorquota'}{$key} = 1;
 9607:                         }
 9608:                     } else {
 9609:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
 9610:                     }
 9611:                 }
 9612:             }
 9613:         }
 9614:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
 9615:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
 9616:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
 9617:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 9618:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
 9619:                             $changes{'defaultquota'}{$key} = 1;
 9620:                         }
 9621:                     } else {
 9622:                         if (!exists($domconfig{'quotas'}{$key})) {
 9623:                             $changes{'defaultquota'}{$key} = 1;
 9624:                         }
 9625:                     }
 9626:                 } else {
 9627:                     $changes{'defaultquota'}{$key} = 1;
 9628:                 }
 9629:             }
 9630:         }
 9631:         if (ref($confhash{'authorquota'}) eq 'HASH') {
 9632:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
 9633:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
 9634:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 9635:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
 9636:                             $changes{'authorquota'}{$key} = 1;
 9637:                         }
 9638:                     } else {
 9639:                         $changes{'authorquota'}{$key} = 1;
 9640:                     }
 9641:                 } else {
 9642:                     $changes{'authorquota'}{$key} = 1;
 9643:                 }
 9644:             }
 9645:         }
 9646:     }
 9647: 
 9648:     if ($context eq 'requestauthor') {
 9649:         $domdefaults{'requestauthor'} = \%confhash;
 9650:     } else {
 9651:         foreach my $key (keys(%confhash)) {
 9652:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
 9653:                 $domdefaults{$key} = $confhash{$key};
 9654:             }
 9655:         }
 9656:     }
 9657: 
 9658:     my %quotahash = (
 9659:                       $action => { %confhash }
 9660:                     );
 9661:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
 9662:                                              $dom);
 9663:     if ($putresult eq 'ok') {
 9664:         if (keys(%changes) > 0) {
 9665:             my $cachetime = 24*60*60;
 9666:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
 9667:             if (ref($lastactref) eq 'HASH') {
 9668:                 $lastactref->{'domdefaults'} = 1;
 9669:             }
 9670:             $resulttext = &mt('Changes made:').'<ul>';
 9671:             unless (($context eq 'requestcourses') ||
 9672:                     ($context eq 'requestauthor')) {
 9673:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
 9674:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
 9675:                     foreach my $type (@{$types},'default') {
 9676:                         if (defined($changes{'defaultquota'}{$type})) {
 9677:                             my $typetitle = $usertypes->{$type};
 9678:                             if ($type eq 'default') {
 9679:                                 $typetitle = $othertitle;
 9680:                             }
 9681:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
 9682:                         }
 9683:                     }
 9684:                     $resulttext .= '</ul></li>';
 9685:                 }
 9686:                 if (ref($changes{'authorquota'}) eq 'HASH') {
 9687:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
 9688:                     foreach my $type (@{$types},'default') {
 9689:                         if (defined($changes{'authorquota'}{$type})) {
 9690:                             my $typetitle = $usertypes->{$type};
 9691:                             if ($type eq 'default') {
 9692:                                 $typetitle = $othertitle;
 9693:                             }
 9694:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
 9695:                         }
 9696:                     }
 9697:                     $resulttext .= '</ul></li>';
 9698:                 }
 9699:             }
 9700:             my %newenv;
 9701:             foreach my $item (@usertools) {
 9702:                 my (%haschgs,%inconf);
 9703:                 if ($context eq 'requestauthor') {
 9704:                     %haschgs = %changes;
 9705:                     %inconf = %confhash;
 9706:                 } else {
 9707:                     if (ref($changes{$item}) eq 'HASH') {
 9708:                         %haschgs = %{$changes{$item}};
 9709:                     }
 9710:                     if (ref($confhash{$item}) eq 'HASH') {
 9711:                         %inconf = %{$confhash{$item}};
 9712:                     }
 9713:                 }
 9714:                 if (keys(%haschgs) > 0) {
 9715:                     my $newacc = 
 9716:                         &Apache::lonnet::usertools_access($env{'user.name'},
 9717:                                                           $env{'user.domain'},
 9718:                                                           $item,'reload',$context);
 9719:                     if (($context eq 'requestcourses') ||
 9720:                         ($context eq 'requestauthor')) {
 9721:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
 9722:                             $newenv{'environment.canrequest.'.$item} = $newacc;
 9723:                         }
 9724:                     } else {
 9725:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
 9726:                             $newenv{'environment.availabletools.'.$item} = $newacc;
 9727:                         }
 9728:                     }
 9729:                     unless ($context eq 'requestauthor') {
 9730:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
 9731:                     }
 9732:                     foreach my $type (@{$types},'default','_LC_adv') {
 9733:                         if ($haschgs{$type}) {
 9734:                             my $typetitle = $usertypes->{$type};
 9735:                             if ($type eq 'default') {
 9736:                                 $typetitle = $othertitle;
 9737:                             } elsif ($type eq '_LC_adv') {
 9738:                                 $typetitle = 'LON-CAPA Advanced Users'; 
 9739:                             }
 9740:                             if ($inconf{$type}) {
 9741:                                 if ($context eq 'requestcourses') {
 9742:                                     my $cond;
 9743:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
 9744:                                         if ($1 eq '') {
 9745:                                             $cond = &mt('(Automatic processing of any request).');
 9746:                                         } else {
 9747:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
 9748:                                         }
 9749:                                     } else { 
 9750:                                         $cond = $conditions{$inconf{$type}};
 9751:                                     }
 9752:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
 9753:                                 } elsif ($context eq 'requestauthor') {
 9754:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
 9755:                                                              $titles{$inconf{$type}},$typetitle);
 9756: 
 9757:                                 } else {
 9758:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
 9759:                                 }
 9760:                             } else {
 9761:                                 if ($type eq '_LC_adv') {
 9762:                                     if ($inconf{$type} eq '0') {
 9763:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
 9764:                                     } else { 
 9765:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
 9766:                                     }
 9767:                                 } else {
 9768:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
 9769:                                 }
 9770:                             }
 9771:                         }
 9772:                     }
 9773:                     unless ($context eq 'requestauthor') {
 9774:                         $resulttext .= '</ul></li>';
 9775:                     }
 9776:                 }
 9777:             }
 9778:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
 9779:                 if (ref($changes{'notify'}) eq 'HASH') {
 9780:                     if ($changes{'notify'}{'approval'}) {
 9781:                         if (ref($confhash{'notify'}) eq 'HASH') {
 9782:                             if ($confhash{'notify'}{'approval'}) {
 9783:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
 9784:                             } else {
 9785:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
 9786:                             }
 9787:                         }
 9788:                     }
 9789:                 }
 9790:             }
 9791:             if ($action eq 'requestcourses') {
 9792:                 my @offon = ('off','on');
 9793:                 if ($changes{'uniquecode'}) {
 9794:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
 9795:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
 9796:                         $resulttext .= '<li>'.
 9797:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
 9798:                                        '</li>';
 9799:                     } else {
 9800:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
 9801:                                        '</li>';
 9802:                     }
 9803:                 }
 9804:                 foreach my $type ('textbooks','templates') {
 9805:                     if (ref($changes{$type}) eq 'HASH') {
 9806:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
 9807:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
 9808:                             my %coursehash = &Apache::lonnet::coursedescription($key);
 9809:                             my $coursetitle = $coursehash{'description'};
 9810:                             my $position = $confhash{$type}{$key}{'order'} + 1;
 9811:                             $resulttext .= '<li>';
 9812:                             foreach my $item ('subject','title','publisher','author') {
 9813:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
 9814:                                          ($type eq 'templates'));
 9815:                                 my $name = $item.':';
 9816:                                 $name =~ s/^(\w)/\U$1/;
 9817:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
 9818:                             }
 9819:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
 9820:                             if ($type eq 'textbooks') {
 9821:                                 if ($confhash{$type}{$key}{'image'}) {
 9822:                                     $resulttext .= ' '.&mt('Image: [_1]',
 9823:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
 9824:                                                    ' alt="Textbook cover" />').'<br />';
 9825:                                 }
 9826:                             }
 9827:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
 9828:                         }
 9829:                         $resulttext .= '</ul></li>';
 9830:                     }
 9831:                 }
 9832:                 if (ref($changes{'validation'}) eq 'HASH') {
 9833:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
 9834:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
 9835:                         foreach my $item (@{$validationitemsref}) {
 9836:                             if (exists($changes{'validation'}{$item})) {
 9837:                                 if ($item eq 'markup') {
 9838:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
 9839:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
 9840:                                 } else {
 9841:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
 9842:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
 9843:                                 }
 9844:                             }
 9845:                         }
 9846:                         if (exists($changes{'validation'}{'dc'})) {
 9847:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
 9848:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
 9849:                         }
 9850:                     }
 9851:                 }
 9852:             }
 9853:             $resulttext .= '</ul>';
 9854:             if (keys(%newenv)) {
 9855:                 &Apache::lonnet::appenv(\%newenv);
 9856:             }
 9857:         } else {
 9858:             if ($context eq 'requestcourses') {
 9859:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
 9860:             } elsif ($context eq 'requestauthor') {
 9861:                 $resulttext = &mt('No changes made to rights to request author space.');
 9862:             } else {
 9863:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
 9864:             }
 9865:         }
 9866:     } else {
 9867:         $resulttext = '<span class="LC_error">'.
 9868: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
 9869:     }
 9870:     if ($errors) {
 9871:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
 9872:                        '<ul>'.$errors.'</ul></p>';
 9873:     }
 9874:     return $resulttext;
 9875: }
 9876: 
 9877: sub process_textbook_image {
 9878:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
 9879:     my $filename = $env{'form.'.$caller.'.filename'};
 9880:     my ($error,$url);
 9881:     my ($width,$height) = (50,50);
 9882:     if ($configuserok eq 'ok') {
 9883:         if ($switchserver) {
 9884:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
 9885:                          $switchserver);
 9886:         } elsif ($author_ok eq 'ok') {
 9887:             my ($result,$imageurl) =
 9888:                 &publishlogo($r,'upload',$caller,$dom,$confname,
 9889:                              "$type/$cdom/$cnum/cover",$width,$height);
 9890:             if ($result eq 'ok') {
 9891:                 $url = $imageurl;
 9892:             } else {
 9893:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
 9894:             }
 9895:         } else {
 9896:             $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);
 9897:         }
 9898:     } else {
 9899:         $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);
 9900:     }
 9901:     return ($url,$error);
 9902: }
 9903: 
 9904: sub modify_autoenroll {
 9905:     my ($dom,$lastactref,%domconfig) = @_;
 9906:     my ($resulttext,%changes);
 9907:     my %currautoenroll;
 9908:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9909:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
 9910:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
 9911:         }
 9912:     }
 9913:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 9914:     my %title = ( run => 'Auto-enrollment active',
 9915:                   sender => 'Sender for notification messages',
 9916:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
 9917:                   failsafe => 'Failsafe for no drops if institutional data missing for a section');
 9918:     my @offon = ('off','on');
 9919:     my $sender_uname = $env{'form.sender_uname'};
 9920:     my $sender_domain = $env{'form.sender_domain'};
 9921:     if ($sender_domain eq '') {
 9922:         $sender_uname = '';
 9923:     } elsif ($sender_uname eq '') {
 9924:         $sender_domain = '';
 9925:     }
 9926:     my $coowners = $env{'form.autoassign_coowners'};
 9927:     my $failsafe = $env{'form.autoenroll_failsafe'};
 9928:     $failsafe =~ s{^\s+|\s+$}{}g;
 9929:     if ($failsafe =~ /\D/) {
 9930:         undef($failsafe);
 9931:     }
 9932:     my %autoenrollhash =  (
 9933:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
 9934:                                        'sender_uname' => $sender_uname,
 9935:                                        'sender_domain' => $sender_domain,
 9936:                                        'co-owners' => $coowners,
 9937:                                        'autofailsafe' => $failsafe,
 9938:                                 }
 9939:                      );
 9940:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
 9941:                                              $dom);
 9942:     if ($putresult eq 'ok') {
 9943:         if (exists($currautoenroll{'run'})) {
 9944:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
 9945:                  $changes{'run'} = 1;
 9946:              }
 9947:         } elsif ($autorun) {
 9948:             if ($env{'form.autoenroll_run'} ne '1') {
 9949:                  $changes{'run'} = 1;
 9950:             }
 9951:         }
 9952:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
 9953:             $changes{'sender'} = 1;
 9954:         }
 9955:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
 9956:             $changes{'sender'} = 1;
 9957:         }
 9958:         if ($currautoenroll{'co-owners'} ne '') {
 9959:             if ($currautoenroll{'co-owners'} ne $coowners) {
 9960:                 $changes{'coowners'} = 1;
 9961:             }
 9962:         } elsif ($coowners) {
 9963:             $changes{'coowners'} = 1;
 9964:         }
 9965:         if ($currautoenroll{'autofailsafe'} ne $failsafe) {
 9966:             $changes{'autofailsafe'} = 1;
 9967:         }
 9968:         if (keys(%changes) > 0) {
 9969:             $resulttext = &mt('Changes made:').'<ul>';
 9970:             if ($changes{'run'}) {
 9971:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
 9972:             }
 9973:             if ($changes{'sender'}) {
 9974:                 if ($sender_uname eq '' || $sender_domain eq '') {
 9975:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
 9976:                 } else {
 9977:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
 9978:                 }
 9979:             }
 9980:             if ($changes{'coowners'}) {
 9981:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
 9982:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
 9983:                 if (ref($lastactref) eq 'HASH') {
 9984:                     $lastactref->{'domainconfig'} = 1;
 9985:                 }
 9986:             }
 9987:             if ($changes{'autofailsafe'}) {
 9988:                 if ($failsafe ne '') {
 9989:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$failsafe).'</li>';
 9990:                 } else {
 9991:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section: deleted');
 9992:                 }
 9993:                 &Apache::lonnet::get_domain_defaults($dom,1);
 9994:                 if (ref($lastactref) eq 'HASH') {
 9995:                     $lastactref->{'domdefaults'} = 1;
 9996:                 }
 9997:             }
 9998:             $resulttext .= '</ul>';
 9999:         } else {
10000:             $resulttext = &mt('No changes made to auto-enrollment settings');
10001:         }
10002:     } else {
10003:         $resulttext = '<span class="LC_error">'.
10004: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
10005:     }
10006:     return $resulttext;
10007: }
10008: 
10009: sub modify_autoupdate {
10010:     my ($dom,%domconfig) = @_;
10011:     my ($resulttext,%currautoupdate,%fields,%changes);
10012:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
10013:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
10014:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
10015:         }
10016:     }
10017:     my @offon = ('off','on');
10018:     my %title = &Apache::lonlocal::texthash (
10019:                    run => 'Auto-update:',
10020:                    classlists => 'Updates to user information in classlists?'
10021:                 );
10022:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
10023:     my %fieldtitles = &Apache::lonlocal::texthash (
10024:                         id => 'Student/Employee ID',
10025:                         permanentemail => 'E-mail address',
10026:                         lastname => 'Last Name',
10027:                         firstname => 'First Name',
10028:                         middlename => 'Middle Name',
10029:                         generation => 'Generation',
10030:                       );
10031:     $othertitle = &mt('All users');
10032:     if (keys(%{$usertypes}) >  0) {
10033:         $othertitle = &mt('Other users');
10034:     }
10035:     foreach my $key (keys(%env)) {
10036:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
10037:             my ($usertype,$item) = ($1,$2);
10038:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
10039:                 if ($usertype eq 'default') {   
10040:                     push(@{$fields{$1}},$2);
10041:                 } elsif (ref($types) eq 'ARRAY') {
10042:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
10043:                         push(@{$fields{$1}},$2);
10044:                     }
10045:                 }
10046:             }
10047:         }
10048:     }
10049:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
10050:     @lockablenames = sort(@lockablenames);
10051:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
10052:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
10053:         if (@changed) {
10054:             $changes{'lockablenames'} = 1;
10055:         }
10056:     } else {
10057:         if (@lockablenames) {
10058:             $changes{'lockablenames'} = 1;
10059:         }
10060:     }
10061:     my %updatehash = (
10062:                       autoupdate => { run => $env{'form.autoupdate_run'},
10063:                                       classlists => $env{'form.classlists'},
10064:                                       fields => {%fields},
10065:                                       lockablenames => \@lockablenames,
10066:                                     }
10067:                      );
10068:     foreach my $key (keys(%currautoupdate)) {
10069:         if (($key eq 'run') || ($key eq 'classlists')) {
10070:             if (exists($updatehash{autoupdate}{$key})) {
10071:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
10072:                     $changes{$key} = 1;
10073:                 }
10074:             }
10075:         } elsif ($key eq 'fields') {
10076:             if (ref($currautoupdate{$key}) eq 'HASH') {
10077:                 foreach my $item (@{$types},'default') {
10078:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
10079:                         my $change = 0;
10080:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
10081:                             if (!exists($fields{$item})) {
10082:                                 $change = 1;
10083:                                 last;
10084:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
10085:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
10086:                                     $change = 1;
10087:                                     last;
10088:                                 }
10089:                             }
10090:                         }
10091:                         if ($change) {
10092:                             push(@{$changes{$key}},$item);
10093:                         }
10094:                     } 
10095:                 }
10096:             }
10097:         } elsif ($key eq 'lockablenames') {
10098:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
10099:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
10100:                 if (@changed) {
10101:                     $changes{'lockablenames'} = 1;
10102:                 }
10103:             } else {
10104:                 if (@lockablenames) {
10105:                     $changes{'lockablenames'} = 1;
10106:                 }
10107:             }
10108:         }
10109:     }
10110:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
10111:         if (@lockablenames) {
10112:             $changes{'lockablenames'} = 1;
10113:         }
10114:     }
10115:     foreach my $item (@{$types},'default') {
10116:         if (defined($fields{$item})) {
10117:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
10118:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
10119:                     my $change = 0;
10120:                     if (ref($fields{$item}) eq 'ARRAY') {
10121:                         foreach my $type (@{$fields{$item}}) {
10122:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
10123:                                 $change = 1;
10124:                                 last;
10125:                             }
10126:                         }
10127:                     }
10128:                     if ($change) {
10129:                         push(@{$changes{'fields'}},$item);
10130:                     }
10131:                 } else {
10132:                     push(@{$changes{'fields'}},$item);
10133:                 }
10134:             } else {
10135:                 push(@{$changes{'fields'}},$item);
10136:             }
10137:         }
10138:     }
10139:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
10140:                                              $dom);
10141:     if ($putresult eq 'ok') {
10142:         if (keys(%changes) > 0) {
10143:             $resulttext = &mt('Changes made:').'<ul>';
10144:             foreach my $key (sort(keys(%changes))) {
10145:                 if ($key eq 'lockablenames') {
10146:                     $resulttext .= '<li>';
10147:                     if (@lockablenames) {
10148:                         $usertypes->{'default'} = $othertitle;
10149:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
10150:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
10151:                     } else {
10152:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
10153:                     }
10154:                     $resulttext .= '</li>';
10155:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
10156:                     foreach my $item (@{$changes{$key}}) {
10157:                         my @newvalues;
10158:                         foreach my $type (@{$fields{$item}}) {
10159:                             push(@newvalues,$fieldtitles{$type});
10160:                         }
10161:                         my $newvaluestr;
10162:                         if (@newvalues > 0) {
10163:                             $newvaluestr = join(', ',@newvalues);
10164:                         } else {
10165:                             $newvaluestr = &mt('none');
10166:                         }
10167:                         if ($item eq 'default') {
10168:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
10169:                         } else {
10170:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
10171:                         }
10172:                     }
10173:                 } else {
10174:                     my $newvalue;
10175:                     if ($key eq 'run') {
10176:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
10177:                     } else {
10178:                         $newvalue = $offon[$env{'form.'.$key}];
10179:                     }
10180:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
10181:                 }
10182:             }
10183:             $resulttext .= '</ul>';
10184:         } else {
10185:             $resulttext = &mt('No changes made to autoupdates');
10186:         }
10187:     } else {
10188:         $resulttext = '<span class="LC_error">'.
10189: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
10190:     }
10191:     return $resulttext;
10192: }
10193: 
10194: sub modify_autocreate {
10195:     my ($dom,%domconfig) = @_;
10196:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
10197:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
10198:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
10199:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
10200:         }
10201:     }
10202:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
10203:                  req => 'Auto-creation of validated requests for official courses',
10204:                  xmldc => 'Identity of course creator of courses from XML files',
10205:                );
10206:     my @types = ('xml','req');
10207:     foreach my $item (@types) {
10208:         $newvals{$item} = $env{'form.autocreate_'.$item};
10209:         $newvals{$item} =~ s/\D//g;
10210:         $newvals{$item} = 0 if ($newvals{$item} eq '');
10211:     }
10212:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
10213:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
10214:     unless (exists($domcoords{$newvals{'xmldc'}})) {
10215:         $newvals{'xmldc'} = '';
10216:     } 
10217:     %autocreatehash =  (
10218:                         autocreate => { xml => $newvals{'xml'},
10219:                                         req => $newvals{'req'},
10220:                                       }
10221:                        );
10222:     if ($newvals{'xmldc'} ne '') {
10223:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
10224:     }
10225:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
10226:                                              $dom);
10227:     if ($putresult eq 'ok') {
10228:         my @items = @types;
10229:         if ($newvals{'xml'}) {
10230:             push(@items,'xmldc');
10231:         }
10232:         foreach my $item (@items) {
10233:             if (exists($currautocreate{$item})) {
10234:                 if ($currautocreate{$item} ne $newvals{$item}) {
10235:                     $changes{$item} = 1;
10236:                 }
10237:             } elsif ($newvals{$item}) {
10238:                 $changes{$item} = 1;
10239:             }
10240:         }
10241:         if (keys(%changes) > 0) {
10242:             my @offon = ('off','on'); 
10243:             $resulttext = &mt('Changes made:').'<ul>';
10244:             foreach my $item (@types) {
10245:                 if ($changes{$item}) {
10246:                     my $newtxt = $offon[$newvals{$item}];
10247:                     $resulttext .= '<li>'.
10248:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
10249:                                        '<b>','</b>').
10250:                                    '</li>';
10251:                 }
10252:             }
10253:             if ($changes{'xmldc'}) {
10254:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
10255:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
10256:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
10257:             }
10258:             $resulttext .= '</ul>';
10259:         } else {
10260:             $resulttext = &mt('No changes made to auto-creation settings');
10261:         }
10262:     } else {
10263:         $resulttext = '<span class="LC_error">'.
10264:             &mt('An error occurred: [_1]',$putresult).'</span>';
10265:     }
10266:     return $resulttext;
10267: }
10268: 
10269: sub modify_directorysrch {
10270:     my ($dom,$lastactref,%domconfig) = @_;
10271:     my ($resulttext,%changes);
10272:     my %currdirsrch;
10273:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
10274:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
10275:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
10276:         }
10277:     }
10278:     my %title = ( available => 'Institutional directory search available',
10279:                   localonly => 'Other domains can search institution',
10280:                   lcavailable => 'LON-CAPA directory search available',
10281:                   lclocalonly => 'Other domains can search LON-CAPA domain',
10282:                   searchby => 'Search types',
10283:                   searchtypes => 'Search latitude');
10284:     my @offon = ('off','on');
10285:     my @otherdoms = ('Yes','No');
10286: 
10287:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
10288:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
10289:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
10290: 
10291:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
10292:     if (keys(%{$usertypes}) == 0) {
10293:         @cansearch = ('default');
10294:     } else {
10295:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
10296:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
10297:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
10298:                     push(@{$changes{'cansearch'}},$type);
10299:                 }
10300:             }
10301:             foreach my $type (@cansearch) {
10302:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
10303:                     push(@{$changes{'cansearch'}},$type);
10304:                 }
10305:             }
10306:         } else {
10307:             push(@{$changes{'cansearch'}},@cansearch);
10308:         }
10309:     }
10310: 
10311:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
10312:         foreach my $by (@{$currdirsrch{'searchby'}}) {
10313:             if (!grep(/^\Q$by\E$/,@searchby)) {
10314:                 push(@{$changes{'searchby'}},$by);
10315:             }
10316:         }
10317:         foreach my $by (@searchby) {
10318:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
10319:                 push(@{$changes{'searchby'}},$by);
10320:             }
10321:         }
10322:     } else {
10323:         push(@{$changes{'searchby'}},@searchby);
10324:     }
10325: 
10326:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
10327:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
10328:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
10329:                 push(@{$changes{'searchtypes'}},$type);
10330:             }
10331:         }
10332:         foreach my $type (@searchtypes) {
10333:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
10334:                 push(@{$changes{'searchtypes'}},$type);
10335:             }
10336:         }
10337:     } else {
10338:         if (exists($currdirsrch{'searchtypes'})) {
10339:             foreach my $type (@searchtypes) {  
10340:                 if ($type ne $currdirsrch{'searchtypes'}) { 
10341:                     push(@{$changes{'searchtypes'}},$type);
10342:                 }
10343:             }
10344:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
10345:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
10346:             }   
10347:         } else {
10348:             push(@{$changes{'searchtypes'}},@searchtypes); 
10349:         }
10350:     }
10351: 
10352:     my %dirsrch_hash =  (
10353:             directorysrch => { available => $env{'form.dirsrch_available'},
10354:                                cansearch => \@cansearch,
10355:                                localonly => $env{'form.dirsrch_instlocalonly'},
10356:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
10357:                                lcavailable => $env{'form.dirsrch_domavailable'},
10358:                                searchby => \@searchby,
10359:                                searchtypes => \@searchtypes,
10360:                              }
10361:             );
10362:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
10363:                                              $dom);
10364:     if ($putresult eq 'ok') {
10365:         if (exists($currdirsrch{'available'})) {
10366:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
10367:                  $changes{'available'} = 1;
10368:              }
10369:         } else {
10370:             if ($env{'form.dirsrch_available'} eq '1') {
10371:                 $changes{'available'} = 1;
10372:             }
10373:         }
10374:         if (exists($currdirsrch{'lcavailable'})) {
10375:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
10376:                 $changes{'lcavailable'} = 1;
10377:             }
10378:         } else {
10379:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
10380:                 $changes{'lcavailable'} = 1;
10381:             }
10382:         }
10383:         if (exists($currdirsrch{'localonly'})) {
10384:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
10385:                 $changes{'localonly'} = 1;
10386:             }
10387:         } else {
10388:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
10389:                 $changes{'localonly'} = 1;
10390:             }
10391:         }
10392:         if (exists($currdirsrch{'lclocalonly'})) {
10393:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
10394:                 $changes{'lclocalonly'} = 1;
10395:             }
10396:         } else {
10397:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
10398:                 $changes{'lclocalonly'} = 1;
10399:             }
10400:         }
10401:         if (keys(%changes) > 0) {
10402:             $resulttext = &mt('Changes made:').'<ul>';
10403:             if ($changes{'available'}) {
10404:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
10405:             }
10406:             if ($changes{'lcavailable'}) {
10407:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
10408:             }
10409:             if ($changes{'localonly'}) {
10410:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
10411:             }
10412:             if ($changes{'lclocalonly'}) {
10413:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
10414:             }
10415:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
10416:                 my $chgtext;
10417:                 if (ref($usertypes) eq 'HASH') {
10418:                     if (keys(%{$usertypes}) > 0) {
10419:                         foreach my $type (@{$types}) {
10420:                             if (grep(/^\Q$type\E$/,@cansearch)) {
10421:                                 $chgtext .= $usertypes->{$type}.'; ';
10422:                             }
10423:                         }
10424:                         if (grep(/^default$/,@cansearch)) {
10425:                             $chgtext .= $othertitle;
10426:                         } else {
10427:                             $chgtext =~ s/\; $//;
10428:                         }
10429:                         $resulttext .=
10430:                             '<li>'.
10431:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
10432:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
10433:                             '</li>';
10434:                     }
10435:                 }
10436:             }
10437:             if (ref($changes{'searchby'}) eq 'ARRAY') {
10438:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
10439:                 my $chgtext;
10440:                 foreach my $type (@{$titleorder}) {
10441:                     if (grep(/^\Q$type\E$/,@searchby)) {
10442:                         if (defined($searchtitles->{$type})) {
10443:                             $chgtext .= $searchtitles->{$type}.'; ';
10444:                         }
10445:                     }
10446:                 }
10447:                 $chgtext =~ s/\; $//;
10448:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
10449:             }
10450:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
10451:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
10452:                 my $chgtext;
10453:                 foreach my $type (@{$srchtypeorder}) {
10454:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
10455:                         if (defined($srchtypes_desc->{$type})) {
10456:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
10457:                         }
10458:                     }
10459:                 }
10460:                 $chgtext =~ s/\; $//;
10461:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
10462:             }
10463:             $resulttext .= '</ul>';
10464:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
10465:             if (ref($lastactref) eq 'HASH') {
10466:                 $lastactref->{'directorysrch'} = 1;
10467:             }
10468:         } else {
10469:             $resulttext = &mt('No changes made to directory search settings');
10470:         }
10471:     } else {
10472:         $resulttext = '<span class="LC_error">'.
10473:                       &mt('An error occurred: [_1]',$putresult).'</span>';
10474:     }
10475:     return $resulttext;
10476: }
10477: 
10478: sub modify_contacts {
10479:     my ($dom,$lastactref,%domconfig) = @_;
10480:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
10481:     if (ref($domconfig{'contacts'}) eq 'HASH') {
10482:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
10483:             $currsetting{$key} = $domconfig{'contacts'}{$key};
10484:         }
10485:     }
10486:     my (%others,%to,%bcc,%includestr,%includeloc);
10487:     my @contacts = ('supportemail','adminemail');
10488:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
10489:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
10490:     my @toggles = ('reporterrors','reportupdates');
10491:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
10492:     foreach my $type (@mailings) {
10493:         @{$newsetting{$type}} = 
10494:             &Apache::loncommon::get_env_multiple('form.'.$type);
10495:         foreach my $item (@contacts) {
10496:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
10497:                 $contacts_hash{contacts}{$type}{$item} = 1;
10498:             } else {
10499:                 $contacts_hash{contacts}{$type}{$item} = 0;
10500:             }
10501:         }
10502:         $others{$type} = $env{'form.'.$type.'_others'};
10503:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
10504:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
10505:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
10506:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
10507:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
10508:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
10509:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
10510:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
10511:             }
10512:         }
10513:     }
10514:     foreach my $item (@contacts) {
10515:         $to{$item} = $env{'form.'.$item};
10516:         $contacts_hash{'contacts'}{$item} = $to{$item};
10517:     }
10518:     foreach my $item (@toggles) {
10519:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
10520:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
10521:         }
10522:     }
10523:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
10524:         foreach my $field (@{$fields}) {
10525:             if (ref($possoptions->{$field}) eq 'ARRAY') {
10526:                 my $value = $env{'form.helpform_'.$field};
10527:                 $value =~ s/^\s+|\s+$//g;
10528:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
10529:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
10530:                     if ($field eq 'screenshot') {
10531:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
10532:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
10533:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
10534:                         }
10535:                     }
10536:                 }
10537:             }
10538:         }
10539:     }
10540:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
10541:     my (@statuses,%usertypeshash,@overrides);
10542:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
10543:         @statuses = @{$types};
10544:         if (ref($usertypes) eq 'HASH') {
10545:             %usertypeshash = %{$usertypes};
10546:         }
10547:     }
10548:     if (@statuses) {
10549:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
10550:         foreach my $type (@possoverrides) {
10551:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
10552:                 push(@overrides,$type);
10553:             }
10554:         }
10555:         if (@overrides) {
10556:             foreach my $type (@overrides) {
10557:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
10558:                 foreach my $item (@contacts) {
10559:                     if (grep(/^\Q$item\E$/,@standard)) {
10560:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
10561:                         $newsetting{'override_'.$type}{$item} = 1;
10562:                     } else {
10563:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
10564:                         $newsetting{'override_'.$type}{$item} = 0;
10565:                     }
10566:                 }
10567:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
10568:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
10569:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
10570:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
10571:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
10572:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
10573:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
10574:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
10575:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
10576:                 }
10577:             }    
10578:         }
10579:     }
10580:     if (keys(%currsetting) > 0) {
10581:         foreach my $item (@contacts) {
10582:             if ($to{$item} ne $currsetting{$item}) {
10583:                 $changes{$item} = 1;
10584:             }
10585:         }
10586:         foreach my $type (@mailings) {
10587:             foreach my $item (@contacts) {
10588:                 if (ref($currsetting{$type}) eq 'HASH') {
10589:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
10590:                         push(@{$changes{$type}},$item);
10591:                     }
10592:                 } else {
10593:                     push(@{$changes{$type}},@{$newsetting{$type}});
10594:                 }
10595:             }
10596:             if ($others{$type} ne $currsetting{$type}{'others'}) {
10597:                 push(@{$changes{$type}},'others');
10598:             }
10599:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
10600:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
10601:                     push(@{$changes{$type}},'bcc'); 
10602:                 }
10603:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
10604:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
10605:                     push(@{$changes{$type}},'include');
10606:                 }
10607:             }
10608:         }
10609:         if (ref($fields) eq 'ARRAY') {
10610:             if (ref($currsetting{'helpform'}) eq 'HASH') {
10611:                 foreach my $field (@{$fields}) {
10612:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
10613:                         push(@{$changes{'helpform'}},$field);
10614:                     }
10615:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
10616:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
10617:                             push(@{$changes{'helpform'}},'maxsize');
10618:                         }
10619:                     }
10620:                 }
10621:             } else {
10622:                 foreach my $field (@{$fields}) {
10623:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
10624:                         push(@{$changes{'helpform'}},$field);
10625:                     }
10626:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
10627:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
10628:                             push(@{$changes{'helpform'}},'maxsize');
10629:                         }
10630:                     }
10631:                 }
10632:             }
10633:         }
10634:         if (@statuses) {
10635:             if (ref($currsetting{'overrides'}) eq 'HASH') {
10636:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
10637:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
10638:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
10639:                             foreach my $item (@contacts,'bcc','others','include') {
10640:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) {
10641:                                     push(@{$changes{'overrides'}},$key);
10642:                                     last;
10643:                                 }
10644:                             }
10645:                         } else {
10646:                             push(@{$changes{'overrides'}},$key);
10647:                         }
10648:                     }
10649:                 }
10650:                 foreach my $key (@overrides) {
10651:                     unless (exists($currsetting{'overrides'}{$key})) {
10652:                         push(@{$changes{'overrides'}},$key);
10653:                     }
10654:                 }
10655:             } else {
10656:                 foreach my $key (@overrides) {
10657:                     push(@{$changes{'overrides'}},$key);
10658:                 }
10659:             }
10660:         }
10661:     } else {
10662:         my %default;
10663:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
10664:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
10665:         $default{'errormail'} = 'adminemail';
10666:         $default{'packagesmail'} = 'adminemail';
10667:         $default{'helpdeskmail'} = 'supportemail';
10668:         $default{'otherdomsmail'} = 'supportemail';
10669:         $default{'lonstatusmail'} = 'adminemail';
10670:         $default{'requestsmail'} = 'adminemail';
10671:         $default{'updatesmail'} = 'adminemail';
10672:         $default{'hostipmail'} = 'adminemail';
10673:         foreach my $item (@contacts) {
10674:            if ($to{$item} ne $default{$item}) {
10675:                $changes{$item} = 1;
10676:            }
10677:         }
10678:         foreach my $type (@mailings) {
10679:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
10680:                 push(@{$changes{$type}},@{$newsetting{$type}});
10681:             }
10682:             if ($others{$type} ne '') {
10683:                 push(@{$changes{$type}},'others');
10684:             }
10685:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
10686:                 if ($bcc{$type} ne '') {
10687:                     push(@{$changes{$type}},'bcc');
10688:                 }
10689:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
10690:                     push(@{$changes{$type}},'include');
10691:                 }
10692:             }
10693:         }
10694:         if (ref($fields) eq 'ARRAY') {
10695:             foreach my $field (@{$fields}) {
10696:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
10697:                     push(@{$changes{'helpform'}},$field);
10698:                 }
10699:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
10700:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
10701:                         push(@{$changes{'helpform'}},'maxsize');
10702:                     }
10703:                 }
10704:             }
10705:         }
10706:     }
10707:     foreach my $item (@toggles) {
10708:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
10709:             $changes{$item} = 1;
10710:         } elsif ((!$env{'form.'.$item}) &&
10711:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
10712:             $changes{$item} = 1;
10713:         }
10714:     }
10715:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
10716:                                              $dom);
10717:     if ($putresult eq 'ok') {
10718:         if (keys(%changes) > 0) {
10719:             &Apache::loncommon::devalidate_domconfig_cache($dom);
10720:             if (ref($lastactref) eq 'HASH') {
10721:                 $lastactref->{'domainconfig'} = 1;
10722:             }
10723:             my ($titles,$short_titles)  = &contact_titles();
10724:             $resulttext = &mt('Changes made:').'<ul>';
10725:             foreach my $item (@contacts) {
10726:                 if ($changes{$item}) {
10727:                     $resulttext .= '<li>'.$titles->{$item}.
10728:                                     &mt(' set to: ').
10729:                                     '<span class="LC_cusr_emph">'.
10730:                                     $to{$item}.'</span></li>';
10731:                 }
10732:             }
10733:             foreach my $type (@mailings) {
10734:                 if (ref($changes{$type}) eq 'ARRAY') {
10735:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
10736:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
10737:                     } else {
10738:                         $resulttext .= '<li>'.$titles->{$type}.': ';
10739:                     }
10740:                     my @text;
10741:                     foreach my $item (@{$newsetting{$type}}) {
10742:                         push(@text,$short_titles->{$item});
10743:                     }
10744:                     if ($others{$type} ne '') {
10745:                         push(@text,$others{$type});
10746:                     }
10747:                     if (@text) {
10748:                         $resulttext .= '<span class="LC_cusr_emph">'.
10749:                                        join(', ',@text).'</span>';
10750:                     }
10751:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
10752:                         if ($bcc{$type} ne '') {
10753:                             my $bcctext;
10754:                             if (@text) {
10755:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
10756:                             } else {
10757:                                 $bcctext = '(Bcc)';
10758:                             }
10759:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
10760:                         } elsif (!@text) {
10761:                             $resulttext .= &mt('No one');
10762:                         }
10763:                         if ($includestr{$type} ne '') {
10764:                             if ($includeloc{$type} eq 'b') {
10765:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
10766:                             } elsif ($includeloc{$type} eq 's') {
10767:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
10768:                             }
10769:                         }
10770:                     } elsif (!@text) {
10771:                         $resulttext .= &mt('No recipients');
10772:                     }
10773:                     $resulttext .= '</li>';
10774:                 }
10775:             }
10776:             if (ref($changes{'overrides'}) eq 'ARRAY') {
10777:                 my @deletions;
10778:                 foreach my $type (@{$changes{'overrides'}}) {
10779:                     if ($usertypeshash{$type}) {
10780:                         if (grep(/^\Q$type\E/,@overrides)) {
10781:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
10782:                                                       $usertypeshash{$type}).'<ul><li>';
10783:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
10784:                                 my @text;
10785:                                 foreach my $item (@contacts) {
10786:                                     if ($newsetting{'override_'.$type}{$item}) {
10787:                                         push(@text,$short_titles->{$item});
10788:                                     }
10789:                                 }
10790:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
10791:                                     push(@text,$newsetting{'override_'.$type}{'others'});
10792:                                 }
10793: 
10794:                                 if (@text) {
10795:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
10796:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
10797:                                 }
10798:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
10799:                                     my $bcctext;
10800:                                     if (@text) {
10801:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
10802:                                     } else {
10803:                                         $bcctext = '(Bcc)';
10804:                                     }
10805:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
10806:                                 } elsif (!@text) {
10807:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
10808:                                 }
10809:                                 $resulttext .= '</li>';
10810:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
10811:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
10812:                                     if ($loc eq 'b') {
10813:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
10814:                                     } elsif ($loc eq 's') {
10815:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
10816:                                     }
10817:                                 }
10818:                             }
10819:                             $resulttext .= '</li></ul></li>';
10820:                         } else {
10821:                             push(@deletions,$usertypeshash{$type});
10822:                         }
10823:                     }
10824:                 }
10825:                 if (@deletions) {
10826:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
10827:                                               join(', ',@deletions)).'</li>';
10828:                 }
10829:             }
10830:             my @offon = ('off','on');
10831:             if ($changes{'reporterrors'}) {
10832:                 $resulttext .= '<li>'.
10833:                                &mt('E-mail error reports to [_1] set to "'.
10834:                                    $offon[$env{'form.reporterrors'}].'".',
10835:                                    &Apache::loncommon::modal_link('http://loncapa.org/core.html',
10836:                                        &mt('LON-CAPA core group - MSU'),600,500)).
10837:                                '</li>';
10838:             }
10839:             if ($changes{'reportupdates'}) {
10840:                 $resulttext .= '<li>'.
10841:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
10842:                                     $offon[$env{'form.reportupdates'}].'".',
10843:                                     &Apache::loncommon::modal_link('http://loncapa.org/core.html',
10844:                                         &mt('LON-CAPA core group - MSU'),600,500)).
10845:                                 '</li>';
10846:             }
10847:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
10848:                 my (@optional,@required,@unused,$maxsizechg);
10849:                 foreach my $field (@{$changes{'helpform'}}) {
10850:                     if ($field eq 'maxsize') {
10851:                         $maxsizechg = 1;
10852:                         next;
10853:                     }
10854:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
10855:                         push(@optional,$field);
10856:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
10857:                         push(@unused,$field);
10858:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
10859:                         push(@required,$field);
10860:                     }
10861:                 }
10862:                 if (@optional) {
10863:                     $resulttext .= '<li>'.
10864:                                    &mt('Help form fields changed to "Optional": [_1].',
10865:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
10866:                                    '</li>';
10867:                 }
10868:                 if (@required) {
10869:                     $resulttext .= '<li>'.
10870:                                    &mt('Help form fields changed to "Required": [_1].',
10871:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
10872:                                    '</li>';
10873:                 }
10874:                 if (@unused) {
10875:                     $resulttext .= '<li>'.
10876:                                    &mt('Help form fields changed to "Not shown": [_1].',
10877:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
10878:                                    '</li>';
10879:                 }
10880:                 if ($maxsizechg) {
10881:                     $resulttext .= '<li>'.
10882:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
10883:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
10884:                                    '</li>';
10885:                 }
10886:             }
10887:             $resulttext .= '</ul>';
10888:         } else {
10889:             $resulttext = &mt('No changes made to contacts and form settings');
10890:         }
10891:     } else {
10892:         $resulttext = '<span class="LC_error">'.
10893:             &mt('An error occurred: [_1].',$putresult).'</span>';
10894:     }
10895:     return $resulttext;
10896: }
10897: 
10898: sub modify_passwords {
10899:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
10900:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
10901:         $updatedefaults,$updateconf);
10902:     my $customfn = 'resetpw.html';
10903:     if (ref($domconfig{'passwords'}) eq 'HASH') {
10904:         %current = %{$domconfig{'passwords'}};
10905:     }
10906:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
10907:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
10908:     if (ref($types) eq 'ARRAY') {
10909:         @oktypes = @{$types};
10910:     }
10911:     push(@oktypes,'default');
10912: 
10913:     my %titles = &Apache::lonlocal::texthash (
10914:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
10915:         intauth_check  => 'Check bcrypt cost if authenticated',
10916:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
10917:         permanent      => 'Permanent e-mail address',
10918:         critical       => 'Critical notification address',
10919:         notify         => 'Notification address',
10920:         min            => 'Minimum password length',
10921:         max            => 'Maximum password length',
10922:         chars          => 'Required characters',
10923:         numsaved       => 'Number of previous passwords to save',
10924:         reset          => 'Resetting Forgotten Password',
10925:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
10926:         rules          => 'Rules for LON-CAPA Passwords',
10927:         crsownerchg    => 'Course Owner Changing Student Passwords',
10928:         username       => 'Username',
10929:         email          => 'E-mail address',
10930:     );
10931: 
10932: #
10933: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
10934: #
10935:     my (%curr_defaults,%save_defaults);
10936:     if (ref($domconfig{'defaults'}) eq 'HASH') {
10937:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
10938:             if ($key =~ /^intauth_(cost|check|switch)$/) {
10939:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
10940:             } else {
10941:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
10942:             }
10943:         }
10944:     }
10945:     my %staticdefaults = (
10946:         'resetlink'      => 2,
10947:         'resetcase'      => \@oktypes,
10948:         'resetprelink'   => 'both',
10949:         'resetemail'     => ['critical','notify','permanent'],
10950:         'intauth_cost'   => 10,
10951:         'intauth_check'  => 0,
10952:         'intauth_switch' => 0,
10953:     );
10954:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
10955:     foreach my $type (@oktypes) {
10956:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
10957:     }
10958:     my $linklife = $env{'form.passwords_link'};
10959:     $linklife =~ s/^\s+|\s+$//g;
10960:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
10961:         $newvalues{'resetlink'} = $linklife;
10962:         if ($current{'resetlink'}) {
10963:             if ($current{'resetlink'} ne $linklife) {
10964:                 $changes{'reset'} = 1;
10965:             }
10966:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
10967:             if ($staticdefaults{'resetlink'} ne $linklife) {
10968:                 $changes{'reset'} = 1;
10969:             }
10970:         }
10971:     } elsif ($current{'resetlink'}) {
10972:         $changes{'reset'} = 1;
10973:     }
10974:     my @casesens;
10975:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
10976:     foreach my $case (sort(@posscase)) {
10977:         if (grep(/^\Q$case\E$/,@oktypes)) {
10978:             push(@casesens,$case);
10979:         }
10980:     }
10981:     $newvalues{'resetcase'} = \@casesens;
10982:     if (ref($current{'resetcase'}) eq 'ARRAY') {
10983:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
10984:         if (@diffs > 0) {
10985:             $changes{'reset'} = 1;
10986:         }
10987:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
10988:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
10989:         if (@diffs > 0) {
10990:             $changes{'reset'} = 1;
10991:         }
10992:     }
10993:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
10994:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
10995:         if (exists($current{'resetprelink'})) {
10996:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
10997:                 $changes{'reset'} = 1;
10998:             }
10999:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
11000:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
11001:                 $changes{'reset'} = 1;
11002:             }
11003:         }
11004:     } elsif ($current{'resetprelink'}) {
11005:         $changes{'reset'} = 1;
11006:     }
11007:     foreach my $type (@oktypes) {
11008:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
11009:         my @postlink;
11010:         foreach my $item (sort(@possplink)) {
11011:             if ($item =~ /^(email|username)$/) {
11012:                 push(@postlink,$item);
11013:             }
11014:         }
11015:         $newvalues{'resetpostlink'}{$type} = \@postlink;
11016:         unless ($changes{'reset'}) {
11017:             if (ref($current{'resetpostlink'}) eq 'HASH') {
11018:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
11019:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
11020:                     if (@diffs > 0) {
11021:                         $changes{'reset'} = 1;
11022:                     }
11023:                 } else {
11024:                     $changes{'reset'} = 1;
11025:                 }
11026:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
11027:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
11028:                 if (@diffs > 0) {
11029:                     $changes{'reset'} = 1;
11030:                 }
11031:             }
11032:         }
11033:     }
11034:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
11035:     my @resetemail;
11036:     foreach my $item (sort(@possemailsrc)) {
11037:         if ($item =~ /^(permanent|critical|notify)$/) {
11038:             push(@resetemail,$item);
11039:         }
11040:     }
11041:     $newvalues{'resetemail'} = \@resetemail;
11042:     unless ($changes{'reset'}) {
11043:         if (ref($current{'resetemail'}) eq 'ARRAY') {
11044:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
11045:             if (@diffs > 0) {
11046:                 $changes{'reset'} = 1;
11047:             }
11048:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
11049:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
11050:             if (@diffs > 0) {
11051:                 $changes{'reset'} = 1;
11052:             }
11053:         }
11054:     }
11055:     if ($env{'form.passwords_stdtext'} == 0) {
11056:         $newvalues{'resetremove'} = 1;
11057:         unless ($current{'resetremove'}) {
11058:             $changes{'reset'} = 1;
11059:         }
11060:     } elsif ($current{'resetremove'}) {
11061:         $changes{'reset'} = 1;
11062:     }
11063:     if ($env{'form.passwords_customfile.filename'} ne '') {
11064:         my $servadm = $r->dir_config('lonAdmEMail');
11065:         my $servadm = $r->dir_config('lonAdmEMail');
11066:         my ($configuserok,$author_ok,$switchserver) =
11067:             &config_check($dom,$confname,$servadm);
11068:         my $error;
11069:         if ($configuserok eq 'ok') {
11070:             if ($switchserver) {
11071:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
11072:             } else {
11073:                 if ($author_ok eq 'ok') {
11074:                     my ($result,$customurl) =
11075:                         &publishlogo($r,'upload','passwords_customfile',$dom,
11076:                                      $confname,'customtext/resetpw','','',$customfn);
11077:                     if ($result eq 'ok') {
11078:                         $newvalues{'resetcustom'} = $customurl;
11079:                         $changes{'reset'} = 1;
11080:                     } else {
11081:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
11082:                     }
11083:                 } else {
11084:                     $error = &mt("Upload of [_1] failed because an author role could not be assigned to a Domain Configuration user ([_2]) in domain: [_3].  Error was: [_4].",$customfn,$confname,$dom,$author_ok);
11085:                 }
11086:             }
11087:         } else {
11088:             $error = &mt("Upload of [_1] failed because a Domain Configuration user ([_2]) could not be created in domain: [_3].  Error was: [_4].",$customfn,$confname,$dom,$configuserok);
11089:         }
11090:         if ($error) {
11091:             &Apache::lonnet::logthis($error);
11092:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11093:         }
11094:     } elsif ($current{'resetcustom'}) {
11095:         if ($env{'form.passwords_custom_del'}) {
11096:             $changes{'reset'} = 1;
11097:         } else {
11098:             $newvalues{'resetcustom'} = $current{'resetcustom'};
11099:         }
11100:     }
11101:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
11102:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
11103:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
11104:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
11105:             $changes{'intauth'} = 1;
11106:         }
11107:     } else {
11108:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
11109:     }
11110:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
11111:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
11112:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
11113:             $changes{'intauth'} = 1;
11114:         }
11115:     } else {
11116:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
11117:     }
11118:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
11119:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
11120:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
11121:             $changes{'intauth'} = 1;
11122:         }
11123:     } else {
11124:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
11125:     }
11126:     foreach my $item ('cost','check','switch') {
11127:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
11128:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
11129:             $updatedefaults = 1;
11130:         }
11131:     }
11132:     foreach my $rule ('min','max','numsaved') {
11133:         $env{'form.passwords_'.$rule} =~ s/^\s+|\s+$//g;
11134:         my $ruleok;
11135:         if ($rule eq 'min') {
11136:             if ($env{'form.passwords_'.$rule} =~ /^\d+$/) {
11137:                 if ($env{'form.passwords_'.$rule} >= $Apache::lonnet::passwdmin) {
11138:                     $ruleok = 1;
11139:                 }
11140:             }
11141:         } elsif (($env{'form.passwords_'.$rule} =~ /^\d+$/) &&
11142:                  ($env{'form.passwords_'.$rule} ne '0')) {
11143:             $ruleok = 1;
11144:         }
11145:         if ($ruleok) {
11146:             $newvalues{$rule} = $env{'form.passwords_'.$rule};
11147:             if (exists($current{$rule})) {
11148:                 if ($newvalues{$rule} ne $current{$rule}) {
11149:                     $changes{'rules'} = 1;
11150:                 }
11151:             } elsif ($rule eq 'min') {
11152:                 if ($staticdefaults{$rule} ne $newvalues{$rule}) {
11153:                     $changes{'rules'} = 1;
11154:                 }
11155:             } else {
11156:                 $changes{'rules'} = 1;
11157:             }
11158:         } elsif (exists($current{$rule})) {
11159:             $changes{'rules'} = 1;
11160:         }
11161:     }
11162:     my @posschars = &Apache::loncommon::get_env_multiple('form.passwords_chars');
11163:     my @chars;
11164:     foreach my $item (sort(@posschars)) {
11165:         if ($item =~ /^(uc|lc|num|spec)$/) {
11166:             push(@chars,$item);
11167:         }
11168:     }
11169:     $newvalues{'chars'} = \@chars;
11170:     unless ($changes{'rules'}) {
11171:         if (ref($current{'chars'}) eq 'ARRAY') {
11172:             my @diffs = &Apache::loncommon::compare_arrays($current{'chars'},\@chars);
11173:             if (@diffs > 0) {
11174:                 $changes{'rules'} = 1;
11175:             }
11176:         } else {
11177:             if (@chars > 0) {
11178:                 $changes{'rules'} = 1;
11179:             }
11180:         }
11181:     }
11182:     my %crsownerchg = (
11183:                         by => [],
11184:                         for => [],
11185:                       );
11186:     foreach my $item ('by','for') {
11187:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
11188:         foreach my $type (sort(@posstypes)) {
11189:             if (grep(/^\Q$type\E$/,@oktypes)) {
11190:                 push(@{$crsownerchg{$item}},$type);
11191:             }
11192:         }
11193:     }
11194:     $newvalues{'crsownerchg'} = \%crsownerchg;
11195:     if (ref($current{'crsownerchg'}) eq 'HASH') {
11196:         foreach my $item ('by','for') {
11197:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
11198:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
11199:                 if (@diffs > 0) {
11200:                     $changes{'crsownerchg'} = 1;
11201:                     last;
11202:                 }
11203:             }
11204:         }
11205:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
11206:         foreach my $item ('by','for') {
11207:             if (@{$crsownerchg{$item}} > 0) {
11208:                 $changes{'crsownerchg'} = 1;
11209:                 last;
11210:             }
11211:         }
11212:     }
11213: 
11214:     my %confighash = (
11215:                         defaults  => \%save_defaults,
11216:                         passwords => \%newvalues,
11217:                      );
11218:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
11219: 
11220:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
11221:     if ($putresult eq 'ok') {
11222:         if (keys(%changes) > 0) {
11223:             $resulttext = &mt('Changes made: ').'<ul>';
11224:             foreach my $key ('reset','intauth','rules','crsownerchg') {
11225:                 if ($changes{$key}) {
11226:                     unless ($key eq 'intauth') {
11227:                         $updateconf = 1;
11228:                     }
11229:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
11230:                     if ($key eq 'reset') {
11231:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
11232:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
11233:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
11234:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
11235:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
11236:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
11237:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
11238:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
11239:                             }
11240:                         } else {
11241:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
11242:                         }
11243:                         if ($confighash{'passwords'}{'resetlink'}) {
11244:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
11245:                         } else {
11246:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
11247:                                                   &mt('Will default to 2 hours').'</li>';
11248:                         }
11249:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
11250:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
11251:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
11252:                             } else {
11253:                                 my $casesens;
11254:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
11255:                                     if ($type eq 'default') {
11256:                                         $casesens .= $othertitle.', ';
11257:                                     } elsif ($usertypes->{$type} ne '') {
11258:                                         $casesens .= $usertypes->{$type}.', ';
11259:                                     }
11260:                                 }
11261:                                 $casesens =~ s/\Q, \E$//;
11262:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
11263:                             }
11264:                         } else {
11265:                             $resulttext .= '<li>'.&mt('Case-sensitivity not set for "Forgot Password" web form').' '.&mt('Will default to case-sensitive for username and/or e-mail address for all').'</li>';
11266:                         }
11267:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
11268:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
11269:                         } else {
11270:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
11271:                         }
11272:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
11273:                             my $output;
11274:                             if (ref($types) eq 'ARRAY') {
11275:                                 foreach my $type (@{$types}) {
11276:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
11277:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
11278:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
11279:                                         } else {
11280:                                             $output .= $usertypes->{$type}.' -- '.
11281:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
11282:                                         }
11283:                                     }
11284:                                 }
11285:                             }
11286:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
11287:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
11288:                                     $output .= $othertitle.' -- '.&mt('none');
11289:                                 } else {
11290:                                     $output .= $othertitle.' -- '.
11291:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
11292:                                 }
11293:                             }
11294:                             if ($output) {
11295:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
11296:                             } else {
11297:                                 $resulttext .= '<li>'.&mt('Information required for new password form not set.').' '.&mt('Will default to requiring both the username and an e-mail address').'</li>';
11298:                             }
11299:                         } else {
11300:                             $resulttext .= '<li>'.&mt('Information required for new password form not set.').' '.&mt('Will default to requiring both the username and an e-mail address').'</li>';
11301:                         }
11302:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
11303:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
11304:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
11305:                             } else {
11306:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
11307:                             }
11308:                         } else {
11309:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA usedfor verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
11310:                         }
11311:                         if ($confighash{'passwords'}{'resetremove'}) {
11312:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
11313:                         } else {
11314:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
11315:                         }
11316:                         if ($confighash{'passwords'}{'resetcustom'}) {
11317:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
11318:                                                                             &mt('custom text'),600,500,undef,undef,
11319:                                                                             undef,undef,'background-color:#ffffff');
11320:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
11321:                         } else {
11322:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
11323:                         }
11324:                     } elsif ($key eq 'intauth') {
11325:                         foreach my $item ('cost','switch','check') {
11326:                             my $value = $save_defaults{$key.'_'.$item};
11327:                             if ($item eq 'switch') {
11328:                                 my %optiondesc = &Apache::lonlocal::texthash (
11329:                                                      0 => 'No',
11330:                                                      1 => 'Yes',
11331:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
11332:                                                  );
11333:                                 if ($value =~ /^(0|1|2)$/) {
11334:                                     $value = $optiondesc{$value};
11335:                                 } else {
11336:                                     $value = &mt('none -- defaults to No');
11337:                                 }
11338:                             } elsif ($item eq 'check') {
11339:                                 my %optiondesc = &Apache::lonlocal::texthash (
11340:                                                      0 => 'No',
11341:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
11342:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
11343:                                                  );
11344:                                 if ($value =~ /^(0|1|2)$/) {
11345:                                     $value = $optiondesc{$value};
11346:                                 } else {
11347:                                     $value = &mt('none -- defaults to No');
11348:                                 }
11349:                             }
11350:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
11351:                         }
11352:                     } elsif ($key eq 'rules') {
11353:                         foreach my $rule ('min','max','numsaved') {
11354:                             if ($confighash{'passwords'}{$rule} eq '') {
11355:                                 if ($rule eq 'min') {
11356:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
11357:                                                    ' '.&mt('Default of [_1] will be used',
11358:                                                            $Apache::lonnet::passwdmin).'</li>';
11359:                                 } else {
11360:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
11361:                                 }
11362:                             } else {
11363:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
11364:                             }
11365:                         }
11366:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
11367:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
11368:                                 my %rulenames = &Apache::lonlocal::texthash(
11369:                                                      uc => 'At least one upper case letter',
11370:                                                      lc => 'At least one lower case letter',
11371:                                                      num => 'At least one number',
11372:                                                      spec => 'At least one non-alphanumeric',
11373:                                                    );
11374:                                 my $needed = '<ul><li>'.
11375:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
11376:                                              '</li></ul>';
11377:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
11378:                             } else {
11379:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
11380:                             }
11381:                         } else {
11382:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
11383:                         }
11384:                     } elsif ($key eq 'crsownerchg') {
11385:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
11386:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
11387:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
11388:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
11389:                             } else {
11390:                                 my %crsownerstr;
11391:                                 foreach my $item ('by','for') {
11392:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
11393:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
11394:                                             if ($type eq 'default') {
11395:                                                 $crsownerstr{$item} .= $othertitle.', ';
11396:                                             } elsif ($usertypes->{$type} ne '') {
11397:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
11398:                                             }
11399:                                         }
11400:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
11401:                                     }
11402:                                 }
11403:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
11404:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
11405:                             }
11406:                         } else {
11407:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
11408:                         }
11409:                     }
11410:                     $resulttext .= '</ul></li>';
11411:                 }
11412:             }
11413:             $resulttext .= '</ul>';
11414:         } else {
11415:             $resulttext = &mt('No changes made to password settings');
11416:         }
11417:         my $cachetime = 24*60*60;
11418:         if ($updatedefaults) {
11419:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
11420:             if (ref($lastactref) eq 'HASH') {
11421:                 $lastactref->{'domdefaults'} = 1;
11422:             }
11423:         }
11424:         if ($updateconf) {
11425:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
11426:             if (ref($lastactref) eq 'HASH') {
11427:                 $lastactref->{'passwdconf'} = 1;
11428:             }
11429:         }
11430:     } else {
11431:         $resulttext = '<span class="LC_error">'.
11432:             &mt('An error occurred: [_1]',$putresult).'</span>';
11433:     }
11434:     if ($errors) {
11435:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
11436:                        $errors.'</ul></p>';
11437:     }
11438:     return $resulttext;
11439: }
11440: 
11441: sub modify_usercreation {
11442:     my ($dom,%domconfig) = @_;
11443:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
11444:     my $warningmsg;
11445:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
11446:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
11447:             if ($key eq 'cancreate') {
11448:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
11449:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
11450:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
11451:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
11452:                         } else {
11453:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
11454:                         }
11455:                     }
11456:                 }
11457:             } elsif ($key eq 'email_rule') {
11458:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
11459:             } else {
11460:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
11461:             }
11462:         }
11463:     }
11464:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
11465:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
11466:     my @contexts = ('author','course','requestcrs');
11467:     foreach my $item(@contexts) {
11468:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
11469:     }
11470:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
11471:         foreach my $item (@contexts) {
11472:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
11473:                 push(@{$changes{'cancreate'}},$item);
11474:             }
11475:         }
11476:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
11477:         foreach my $item (@contexts) {
11478:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
11479:                 if ($cancreate{$item} ne 'any') {
11480:                     push(@{$changes{'cancreate'}},$item);
11481:                 }
11482:             } else {
11483:                 if ($cancreate{$item} ne 'none') {
11484:                     push(@{$changes{'cancreate'}},$item);
11485:                 }
11486:             }
11487:         }
11488:     } else {
11489:         foreach my $item (@contexts)  {
11490:             push(@{$changes{'cancreate'}},$item);
11491:         }
11492:     }
11493: 
11494:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
11495:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
11496:             if (!grep(/^\Q$type\E$/,@username_rule)) {
11497:                 push(@{$changes{'username_rule'}},$type);
11498:             }
11499:         }
11500:         foreach my $type (@username_rule) {
11501:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
11502:                 push(@{$changes{'username_rule'}},$type);
11503:             }
11504:         }
11505:     } else {
11506:         push(@{$changes{'username_rule'}},@username_rule);
11507:     }
11508: 
11509:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
11510:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
11511:             if (!grep(/^\Q$type\E$/,@id_rule)) {
11512:                 push(@{$changes{'id_rule'}},$type);
11513:             }
11514:         }
11515:         foreach my $type (@id_rule) {
11516:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
11517:                 push(@{$changes{'id_rule'}},$type);
11518:             }
11519:         }
11520:     } else {
11521:         push(@{$changes{'id_rule'}},@id_rule);
11522:     }
11523: 
11524:     my @authen_contexts = ('author','course','domain');
11525:     my @authtypes = ('int','krb4','krb5','loc');
11526:     my %authhash;
11527:     foreach my $item (@authen_contexts) {
11528:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
11529:         foreach my $auth (@authtypes) {
11530:             if (grep(/^\Q$auth\E$/,@authallowed)) {
11531:                 $authhash{$item}{$auth} = 1;
11532:             } else {
11533:                 $authhash{$item}{$auth} = 0;
11534:             }
11535:         }
11536:     }
11537:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
11538:         foreach my $item (@authen_contexts) {
11539:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
11540:                 foreach my $auth (@authtypes) {
11541:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
11542:                         push(@{$changes{'authtypes'}},$item);
11543:                         last;
11544:                     }
11545:                 }
11546:             }
11547:         }
11548:     } else {
11549:         foreach my $item (@authen_contexts) {
11550:             push(@{$changes{'authtypes'}},$item);
11551:         }
11552:     }
11553: 
11554:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
11555:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
11556:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
11557:     $save_usercreate{'id_rule'} = \@id_rule;
11558:     $save_usercreate{'username_rule'} = \@username_rule,
11559:     $save_usercreate{'authtypes'} = \%authhash;
11560: 
11561:     my %usercreation_hash =  (
11562:         usercreation     => \%save_usercreate,
11563:     );
11564: 
11565:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
11566:                                              $dom);
11567: 
11568:     if ($putresult eq 'ok') {
11569:         if (keys(%changes) > 0) {
11570:             $resulttext = &mt('Changes made:').'<ul>';
11571:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
11572:                 my %lt = &usercreation_types();
11573:                 foreach my $type (@{$changes{'cancreate'}}) {
11574:                     my $chgtext = $lt{$type}.', ';
11575:                     if ($cancreate{$type} eq 'none') {
11576:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
11577:                     } elsif ($cancreate{$type} eq 'any') {
11578:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
11579:                     } elsif ($cancreate{$type} eq 'official') {
11580:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
11581:                     } elsif ($cancreate{$type} eq 'unofficial') {
11582:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
11583:                     }
11584:                     $resulttext .= '<li>'.$chgtext.'</li>';
11585:                 }
11586:             }
11587:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
11588:                 my ($rules,$ruleorder) = 
11589:                     &Apache::lonnet::inst_userrules($dom,'username');
11590:                 my $chgtext = '<ul>';
11591:                 foreach my $type (@username_rule) {
11592:                     if (ref($rules->{$type}) eq 'HASH') {
11593:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
11594:                     }
11595:                 }
11596:                 $chgtext .= '</ul>';
11597:                 if (@username_rule > 0) {
11598:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
11599:                 } else {
11600:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
11601:                 }
11602:             }
11603:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
11604:                 my ($idrules,$idruleorder) = 
11605:                     &Apache::lonnet::inst_userrules($dom,'id');
11606:                 my $chgtext = '<ul>';
11607:                 foreach my $type (@id_rule) {
11608:                     if (ref($idrules->{$type}) eq 'HASH') {
11609:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
11610:                     }
11611:                 }
11612:                 $chgtext .= '</ul>';
11613:                 if (@id_rule > 0) {
11614:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
11615:                 } else {
11616:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
11617:                 }
11618:             }
11619:             my %authname = &authtype_names();
11620:             my %context_title = &context_names();
11621:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
11622:                 my $chgtext = '<ul>';
11623:                 foreach my $type (@{$changes{'authtypes'}}) {
11624:                     my @allowed;
11625:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
11626:                     foreach my $auth (@authtypes) {
11627:                         if ($authhash{$type}{$auth}) {
11628:                             push(@allowed,$authname{$auth});
11629:                         }
11630:                     }
11631:                     if (@allowed > 0) {
11632:                         $chgtext .= join(', ',@allowed).'</li>';
11633:                     } else {
11634:                         $chgtext .= &mt('none').'</li>';
11635:                     }
11636:                 }
11637:                 $chgtext .= '</ul>';
11638:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
11639:                 $resulttext .= '</li>';
11640:             }
11641:             $resulttext .= '</ul>';
11642:         } else {
11643:             $resulttext = &mt('No changes made to user creation settings');
11644:         }
11645:     } else {
11646:         $resulttext = '<span class="LC_error">'.
11647:             &mt('An error occurred: [_1]',$putresult).'</span>';
11648:     }
11649:     if ($warningmsg ne '') {
11650:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
11651:     }
11652:     return $resulttext;
11653: }
11654: 
11655: sub modify_selfcreation {
11656:     my ($dom,$lastactref,%domconfig) = @_;
11657:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
11658:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
11659:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
11660:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
11661:     if (ref($typesref) eq 'ARRAY') {
11662:         @types = @{$typesref};
11663:     }
11664:     if (ref($usertypesref) eq 'HASH') {
11665:         %usertypes = %{$usertypesref};
11666:     }
11667:     $usertypes{'default'} = $othertitle;
11668: #
11669: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
11670: #
11671:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
11672:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
11673:             if ($key eq 'cancreate') {
11674:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
11675:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
11676:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
11677:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
11678:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
11679:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
11680:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
11681:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
11682:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
11683:                         } else {
11684:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
11685:                         }
11686:                     }
11687:                 }
11688:             } elsif ($key eq 'email_rule') {
11689:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
11690:             } else {
11691:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
11692:             }
11693:         }
11694:     }
11695: #
11696: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
11697: #
11698:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
11699:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
11700:             if ($key eq 'selfcreate') {
11701:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
11702:             } else {
11703:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
11704:             }
11705:         }
11706:     }
11707: #
11708: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
11709: #
11710:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
11711:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
11712:             if ($key eq 'inststatusguest') {
11713:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
11714:             } else {
11715:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
11716:             }
11717:         }
11718:     }
11719: 
11720:     my @contexts = ('selfcreate');
11721:     @{$cancreate{'selfcreate'}} = ();
11722:     %{$cancreate{'emailusername'}} = ();
11723:     if (@types) {
11724:         @{$cancreate{'statustocreate'}} = ();
11725:     }
11726:     %{$cancreate{'selfcreateprocessing'}} = ();
11727:     %{$cancreate{'shibenv'}} = ();
11728:     %{$cancreate{'emailverified'}} = ();
11729:     %{$cancreate{'emailoptions'}} = ();
11730:     %{$cancreate{'emaildomain'}} = ();
11731:     my %selfcreatetypes = (
11732:                              sso   => 'users authenticated by institutional single sign on',
11733:                              login => 'users authenticated by institutional log-in',
11734:                              email => 'users verified by e-mail',
11735:                           );
11736: #
11737: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
11738: # is permitted.
11739: #
11740: 
11741:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
11742: 
11743:     my (@statuses,%email_rule);
11744:     foreach my $item ('login','sso','email') {
11745:         if ($item eq 'email') {
11746:             if ($env{'form.cancreate_email'}) {
11747:                 if (@types) {
11748:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
11749:                     foreach my $status (@poss_statuses) {
11750:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
11751:                             push(@statuses,$status);
11752:                         }
11753:                     }
11754:                     $save_inststatus{'inststatusguest'} = \@statuses;
11755:                 } else {
11756:                     push(@statuses,'default');
11757:                 }
11758:                 if (@statuses) {
11759:                     my %curr_rule;
11760:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
11761:                         foreach my $type (@statuses) {
11762:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
11763:                         }
11764:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
11765:                         foreach my $type (@statuses) {
11766:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
11767:                         }
11768:                     }
11769:                     push(@{$cancreate{'selfcreate'}},'email');
11770:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
11771:                     my %curremaildom;
11772:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
11773:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
11774:                     }
11775:                     foreach my $type (@statuses) {
11776:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
11777:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
11778:                         }
11779:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
11780:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
11781:                         }
11782:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
11783: #
11784: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
11785: #
11786:                             my $chosen = $1;
11787:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
11788:                                 my $emaildom;
11789:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
11790:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type};
11791:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
11792:                                     if (ref($curremaildom{$type}) eq 'HASH') {
11793:                                         if (exists($curremaildom{$type}{$chosen})) {
11794:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
11795:                                                 push(@{$changes{'cancreate'}},'emaildomain');
11796:                                             }
11797:                                         } elsif ($emaildom ne '') {
11798:                                             push(@{$changes{'cancreate'}},'emaildomain');
11799:                                         }
11800:                                     } elsif ($emaildom ne '') {
11801:                                         push(@{$changes{'cancreate'}},'emaildomain');
11802:                                     }
11803:                                 }
11804:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
11805:                             } elsif ($chosen eq 'custom') {
11806:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
11807:                                 $email_rule{$type} = [];
11808:                                 if (ref($emailrules) eq 'HASH') {
11809:                                     foreach my $rule (@possemail_rules) {
11810:                                         if (exists($emailrules->{$rule})) {
11811:                                             push(@{$email_rule{$type}},$rule);
11812:                                         }
11813:                                     }
11814:                                 }
11815:                                 if (@{$email_rule{$type}}) {
11816:                                     $cancreate{'emailoptions'}{$type} = 'custom';
11817:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
11818:                                         if (@{$curr_rule{$type}} > 0) {
11819:                                             foreach my $rule (@{$curr_rule{$type}}) {
11820:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
11821:                                                     push(@{$changes{'email_rule'}},$type);
11822:                                                 }
11823:                                             }
11824:                                         }
11825:                                         foreach my $type (@{$email_rule{$type}}) {
11826:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
11827:                                                 push(@{$changes{'email_rule'}},$type);
11828:                                             }
11829:                                         }
11830:                                     } else {
11831:                                         push(@{$changes{'email_rule'}},$type);
11832:                                     }
11833:                                 }
11834:                             } else {
11835:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
11836:                             }
11837:                         }
11838:                     }
11839:                     if (@types) {
11840:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
11841:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
11842:                             if (@changed) {
11843:                                 push(@{$changes{'inststatus'}},'inststatusguest');
11844:                             }
11845:                         } else {
11846:                             push(@{$changes{'inststatus'}},'inststatusguest');
11847:                         }
11848:                     }
11849:                 } else {
11850:                     delete($env{'form.cancreate_email'});
11851:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
11852:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
11853:                             push(@{$changes{'inststatus'}},'inststatusguest');
11854:                         }
11855:                     }
11856:                 }
11857:             } else {
11858:                 $save_inststatus{'inststatusguest'} = [];
11859:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
11860:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
11861:                         push(@{$changes{'inststatus'}},'inststatusguest');
11862:                     }
11863:                 }
11864:             }
11865:         } else {
11866:             if ($env{'form.cancreate_'.$item}) {
11867:                 push(@{$cancreate{'selfcreate'}},$item);
11868:             }
11869:         }
11870:     }
11871:     my (%userinfo,%savecaptcha);
11872:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
11873: #
11874: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
11875: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
11876: #
11877: 
11878:     if ($env{'form.cancreate_email'}) {
11879:         push(@contexts,'emailusername');
11880:         if (@statuses) {
11881:             foreach my $type (@statuses) {
11882:                 if (ref($infofields) eq 'ARRAY') {
11883:                     foreach my $field (@{$infofields}) {
11884:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
11885:                             $cancreate{'emailusername'}{$type}{$field} = $1;
11886:                         }
11887:                     }
11888:                 }
11889:             }
11890:         }
11891: #
11892: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
11893: # queued requests for self-creation of account verified by e-mail.
11894: #
11895: 
11896:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
11897:         @approvalnotify = sort(@approvalnotify);
11898:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
11899:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
11900:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
11901:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
11902:                     push(@{$changes{'cancreate'}},'notify');
11903:                 }
11904:             } else {
11905:                 if ($cancreate{'notify'}{'approval'}) {
11906:                     push(@{$changes{'cancreate'}},'notify');
11907:                 }
11908:             }
11909:         } elsif ($cancreate{'notify'}{'approval'}) {
11910:             push(@{$changes{'cancreate'}},'notify');
11911:         }
11912: 
11913:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
11914:     }
11915: #  
11916: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
11917: # institutional log-in.
11918: #
11919:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
11920:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
11921:                ($domdefaults{'auth_def'} eq 'localauth'))) {
11922:             $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.').' '.
11923:                           &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.');
11924:         }
11925:     }
11926:     my @fields = ('lastname','firstname','middlename','generation',
11927:                   'permanentemail','id');
11928:     my @shibfields = (@fields,'inststatus');
11929:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
11930: #
11931: # Where usernames may created for institutional log-in and/or institutional single sign on:
11932: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
11933: # may self-create accounts 
11934: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
11935: # which the user may supply, if institutional data is unavailable.
11936: #
11937:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
11938:         if (@types) {
11939:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
11940:             push(@contexts,'statustocreate');
11941:             foreach my $type (@types) {
11942:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
11943:                 foreach my $field (@fields) {
11944:                     if (grep(/^\Q$field\E$/,@modifiable)) {
11945:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
11946:                     } else {
11947:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
11948:                     }
11949:                 }
11950:             }
11951:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
11952:                 foreach my $type (@types) {
11953:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
11954:                         foreach my $field (@fields) {
11955:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
11956:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
11957:                                 push(@{$changes{'selfcreate'}},$type);
11958:                                 last;
11959:                             }
11960:                         }
11961:                     }
11962:                 }
11963:             } else {
11964:                 foreach my $type (@types) {
11965:                     push(@{$changes{'selfcreate'}},$type);
11966:                 }
11967:             }
11968:         }
11969:         foreach my $field (@shibfields) {
11970:             if ($env{'form.shibenv_'.$field} ne '') {
11971:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
11972:             }
11973:         }
11974:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
11975:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
11976:                 foreach my $field (@shibfields) {
11977:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
11978:                         push(@{$changes{'cancreate'}},'shibenv');
11979:                     }
11980:                 }
11981:             } else {
11982:                 foreach my $field (@shibfields) {
11983:                     if ($env{'form.shibenv_'.$field}) {
11984:                         push(@{$changes{'cancreate'}},'shibenv');
11985:                         last;
11986:                     }
11987:                 }
11988:             }
11989:         }
11990:     }
11991:     foreach my $item (@contexts) {
11992:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
11993:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
11994:                 if (ref($cancreate{$item}) eq 'ARRAY') {
11995:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
11996:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
11997:                             push(@{$changes{'cancreate'}},$item);
11998:                         }
11999:                     }
12000:                 }
12001:             }
12002:             if (ref($cancreate{$item}) eq 'ARRAY') {
12003:                 foreach my $type (@{$cancreate{$item}}) {
12004:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
12005:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
12006:                             push(@{$changes{'cancreate'}},$item);
12007:                         }
12008:                     }
12009:                 }
12010:             }
12011:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
12012:             if (ref($cancreate{$item}) eq 'HASH') {
12013:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
12014:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
12015:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
12016:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
12017:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
12018:                                     push(@{$changes{'cancreate'}},$item);
12019:                                 }
12020:                             }
12021:                         }
12022:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
12023:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
12024:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
12025:                                 push(@{$changes{'cancreate'}},$item);
12026:                             }
12027:                         }
12028:                     }
12029:                 }
12030:                 foreach my $type (keys(%{$cancreate{$item}})) {
12031:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
12032:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
12033:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
12034:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
12035:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
12036:                                         push(@{$changes{'cancreate'}},$item);
12037:                                     }
12038:                                 }
12039:                             } else {
12040:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
12041:                                     push(@{$changes{'cancreate'}},$item);
12042:                                 }
12043:                             }
12044:                         }
12045:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
12046:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
12047:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
12048:                                 push(@{$changes{'cancreate'}},$item);
12049:                             }
12050:                         }
12051:                     }
12052:                 }
12053:             }
12054:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
12055:             if (ref($cancreate{$item}) eq 'ARRAY') {
12056:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
12057:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
12058:                         push(@{$changes{'cancreate'}},$item);
12059:                     }
12060:                 }
12061:             }
12062:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
12063:             if (ref($cancreate{$item}) eq 'HASH') {
12064:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
12065:                     push(@{$changes{'cancreate'}},$item);
12066:                 }
12067:             }
12068:         } elsif ($item eq 'emailusername') {
12069:             if (ref($cancreate{$item}) eq 'HASH') {
12070:                 foreach my $type (keys(%{$cancreate{$item}})) {
12071:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
12072:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
12073:                             if ($cancreate{$item}{$type}{$field}) {
12074:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
12075:                                     push(@{$changes{'cancreate'}},$item);
12076:                                 }
12077:                                 last;
12078:                             }
12079:                         }
12080:                     }
12081:                 }
12082:             }
12083:         }
12084:     }
12085: #
12086: # Populate %save_usercreate hash with updates to self-creation configuration.
12087: #
12088:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
12089:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
12090:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
12091:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
12092:     if (ref($cancreate{'notify'}) eq 'HASH') {
12093:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
12094:     }
12095:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
12096:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
12097:     }
12098:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
12099:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
12100:     }
12101:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
12102:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
12103:     }
12104:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
12105:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
12106:     }
12107:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
12108:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
12109:     }
12110:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
12111:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
12112:     }
12113:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
12114:     $save_usercreate{'email_rule'} = \%email_rule;
12115: 
12116:     my %userconfig_hash = (
12117:             usercreation     => \%save_usercreate,
12118:             usermodification => \%save_usermodify,
12119:             inststatus       => \%save_inststatus,
12120:     );
12121: 
12122:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
12123:                                              $dom);
12124: #
12125: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
12126: #
12127:     if ($putresult eq 'ok') {
12128:         if (keys(%changes) > 0) {
12129:             $resulttext = &mt('Changes made:').'<ul>';
12130:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
12131:                 my %lt = &selfcreation_types();
12132:                 foreach my $type (@{$changes{'cancreate'}}) {
12133:                     my $chgtext = '';
12134:                     if ($type eq 'selfcreate') {
12135:                         if (@{$cancreate{$type}} == 0) {
12136:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
12137:                         } else {
12138:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
12139:                                         '<ul>';
12140:                             foreach my $case (@{$cancreate{$type}}) {
12141:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
12142:                             }
12143:                             $chgtext .= '</ul>';
12144:                             if (ref($cancreate{$type}) eq 'ARRAY') {
12145:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
12146:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
12147:                                         if (@{$cancreate{'statustocreate'}} == 0) {
12148:                                             $chgtext .= '<span class="LC_warning">'.
12149:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
12150:                                                         '</span><br />';
12151:                                         }
12152:                                     }
12153:                                 }
12154:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
12155:                                     if (!@statuses) {
12156:                                         $chgtext .= '<span class="LC_warning">'.
12157:                                                     &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.").
12158:                                                     '</span><br />';
12159: 
12160:                                     }
12161:                                 }
12162:                             }
12163:                         }
12164:                     } elsif ($type eq 'shibenv') {
12165:                         if (keys(%{$cancreate{$type}}) == 0) {
12166:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
12167:                         } else {
12168:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
12169:                                         '<ul>';
12170:                             foreach my $field (@shibfields) {
12171:                                 next if ($cancreate{$type}{$field} eq '');
12172:                                 if ($field eq 'inststatus') {
12173:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
12174:                                 } else {
12175:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
12176:                                 }
12177:                             }
12178:                             $chgtext .= '</ul>';
12179:                         }
12180:                     } elsif ($type eq 'statustocreate') {
12181:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
12182:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
12183:                             if (@{$cancreate{'selfcreate'}} > 0) {
12184:                                 if (@{$cancreate{'statustocreate'}} == 0) {
12185:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
12186:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
12187:                                         $chgtext .= '<br />'.
12188:                                                     '<span class="LC_warning">'.
12189:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
12190:                                                     '</span>';
12191:                                     }
12192:                                 } elsif (keys(%usertypes) > 0) {
12193:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
12194:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
12195:                                     } else {
12196:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
12197:                                     }
12198:                                     $chgtext .= '<ul>';
12199:                                     foreach my $case (@{$cancreate{$type}}) {
12200:                                         if ($case eq 'default') {
12201:                                             $chgtext .= '<li>'.$othertitle.'</li>';
12202:                                         } else {
12203:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
12204:                                         }
12205:                                     }
12206:                                     $chgtext .= '</ul>';
12207:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
12208:                                         $chgtext .= '<span class="LC_warning">'.
12209:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
12210:                                                     '</span>';
12211:                                     }
12212:                                 }
12213:                             } else {
12214:                                 if (@{$cancreate{$type}} == 0) {
12215:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
12216:                                 } else {
12217:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
12218:                                 }
12219:                             }
12220:                             $chgtext .= '<br />';
12221:                         }
12222:                     } elsif ($type eq 'selfcreateprocessing') {
12223:                         my %choices = &Apache::lonlocal::texthash (
12224:                                                                     automatic => 'Automatic approval',
12225:                                                                     approval  => 'Queued for approval',
12226:                                                                   );
12227:                         if (@types) {
12228:                             if (@statuses) {
12229:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:').
12230:                                             '<ul>';
12231:                                 foreach my $status (@statuses) {
12232:                                     if ($status eq 'default') {
12233:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
12234:                                     } else {
12235:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
12236:                                     }
12237:                                 }
12238:                                 $chgtext .= '</ul>';
12239:                             }
12240:                         } else {
12241:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
12242:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
12243:                         }
12244:                     } elsif ($type eq 'emailverified') {
12245:                         my %options = &Apache::lonlocal::texthash (
12246:                                                                     all   => 'Same as e-mail',
12247:                                                                     first => 'Omit @domain',
12248:                                                                     free  => 'Free to choose',
12249:                                                                   );
12250:                         if (@types) {
12251:                             if (@statuses) {
12252:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
12253:                                             '<ul>';
12254:                                 foreach my $status (@statuses) {
12255:                                     if ($status eq 'default') {
12256:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
12257:                                     } else {
12258:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
12259:                                     }
12260:                                 }
12261:                                 $chgtext .= '</ul>';
12262:                             }
12263:                         } else {
12264:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
12265:                                             $options{$cancreate{'emailverified'}{'default'}});
12266:                         }
12267:                     } elsif ($type eq 'emailoptions') {
12268:                         my %options = &Apache::lonlocal::texthash (
12269:                                                                     any     => 'Any e-mail',
12270:                                                                     inst    => 'Institutional only',
12271:                                                                     noninst => 'Non-institutional only',
12272:                                                                     custom  => 'Custom restrictions',
12273:                                                                   );
12274:                         if (@types) {
12275:                             if (@statuses) {
12276:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
12277:                                             '<ul>';
12278:                                 foreach my $status (@statuses) {
12279:                                     if ($type eq 'default') {
12280:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
12281:                                     } else {
12282:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
12283:                                     }
12284:                                 }
12285:                                 $chgtext .= '</ul>';
12286:                             }
12287:                         } else {
12288:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
12289:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
12290:                             } else {
12291:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
12292:                                                 $options{$cancreate{'emailoptions'}{'default'}});
12293:                             }
12294:                         }
12295:                     } elsif ($type eq 'emaildomain') {
12296:                         my $output;
12297:                         if (@statuses) {
12298:                             foreach my $type (@statuses) {
12299:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
12300:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
12301:                                         if ($type eq 'default') {
12302:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
12303:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
12304:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
12305:                                             } else {
12306:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
12307:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
12308:                                             }
12309:                                         } else {
12310:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
12311:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
12312:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
12313:                                             } else {
12314:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
12315:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
12316:                                             }
12317:                                         }
12318:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
12319:                                         if ($type eq 'default') {
12320:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
12321:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
12322:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
12323:                                             } else {
12324:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
12325:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
12326:                                             }
12327:                                         } else {
12328:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
12329:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
12330:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
12331:                                             } else {
12332:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
12333:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
12334:                                             }
12335:                                         }
12336:                                     }
12337:                                 }
12338:                             }
12339:                         }
12340:                         if ($output ne '') {
12341:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
12342:                                         '<ul>'.$output.'</ul>';
12343:                         }
12344:                     } elsif ($type eq 'captcha') {
12345:                         if ($savecaptcha{$type} eq 'notused') {
12346:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
12347:                         } else {
12348:                             my %captchas = &captcha_phrases();
12349:                             if ($captchas{$savecaptcha{$type}}) {
12350:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
12351:                             } else {
12352:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
12353:                             }
12354:                         }
12355:                     } elsif ($type eq 'recaptchakeys') {
12356:                         my ($privkey,$pubkey);
12357:                         if (ref($savecaptcha{$type}) eq 'HASH') {
12358:                             $pubkey = $savecaptcha{$type}{'public'};
12359:                             $privkey = $savecaptcha{$type}{'private'};
12360:                         }
12361:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
12362:                         if (!$pubkey) {
12363:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
12364:                         } else {
12365:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
12366:                         }
12367:                         if (!$privkey) {
12368:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
12369:                         } else {
12370:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
12371:                         }
12372:                         $chgtext .= '</ul>';
12373:                     } elsif ($type eq 'recaptchaversion') {
12374:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
12375:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
12376:                         }
12377:                     } elsif ($type eq 'emailusername') {
12378:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
12379:                             if (@statuses) {
12380:                                 foreach my $type (@statuses) {
12381:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
12382:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
12383:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
12384:                                                     '<ul>';
12385:                                             foreach my $field (@{$infofields}) {
12386:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
12387:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
12388:                                                 }
12389:                                             }
12390:                                             $chgtext .= '</ul>';
12391:                                         } else {
12392:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
12393:                                         }
12394:                                     } else {
12395:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
12396:                                     }
12397:                                 }
12398:                             }
12399:                         }
12400:                     } elsif ($type eq 'notify') {
12401:                         my $numapprove = 0;
12402:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
12403:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
12404:                                 if ($cancreate{'notify'}{'approval'}) {
12405:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
12406:                                     $numapprove ++;
12407:                                 }
12408:                             }
12409:                         }
12410:                         unless ($numapprove) {
12411:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
12412:                         }
12413:                     }
12414:                     if ($chgtext) {
12415:                         $resulttext .= '<li>'.$chgtext.'</li>';
12416:                     }
12417:                 }
12418:             }
12419:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
12420:                 my ($emailrules,$emailruleorder) =
12421:                     &Apache::lonnet::inst_userrules($dom,'email');
12422:                 foreach my $type (@{$changes{'email_rule'}}) {
12423:                     if (ref($email_rule{$type}) eq 'ARRAY') {
12424:                         my $chgtext = '<ul>';
12425:                         foreach my $rule (@{$email_rule{$type}}) {
12426:                             if (ref($emailrules->{$rule}) eq 'HASH') {
12427:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
12428:                             }
12429:                         }
12430:                         $chgtext .= '</ul>';
12431:                         my $typename;
12432:                         if (@types) {
12433:                             if ($type eq 'default') {
12434:                                 $typename = $othertitle;
12435:                             } else {
12436:                                 $typename = $usertypes{$type};
12437:                             }
12438:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
12439:                         }
12440:                         if (@{$email_rule{$type}} > 0) {
12441:                             $resulttext .= '<li>'.
12442:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
12443:                                                $usertypes{$type}).
12444:                                            $chgtext.
12445:                                            '</li>';
12446:                         } else {
12447:                             $resulttext .= '<li>'.
12448:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
12449:                                            '</li>'.
12450:                                            &mt('(Affiliation: [_1])',$typename);
12451:                         }
12452:                     }
12453:                 }
12454:             }
12455:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
12456:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
12457:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
12458:                         my $chgtext = '<ul>';
12459:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
12460:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
12461:                         }
12462:                         $chgtext .= '</ul>';
12463:                         $resulttext .= '<li>'.
12464:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
12465:                                           $chgtext.
12466:                                        '</li>';
12467:                     } else {
12468:                         $resulttext .= '<li>'.
12469:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
12470:                                        '</li>';
12471:                     }
12472:                 }
12473:             }
12474:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
12475:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
12476:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
12477:                 foreach my $type (@{$changes{'selfcreate'}}) {
12478:                     my $typename = $type;
12479:                     if (keys(%usertypes) > 0) {
12480:                         if ($usertypes{$type} ne '') {
12481:                             $typename = $usertypes{$type};
12482:                         }
12483:                     }
12484:                     my @modifiable;
12485:                     $resulttext .= '<li>'.
12486:                                     &mt('Self-creation of account by users with status: [_1]',
12487:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
12488:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
12489:                     foreach my $field (@fields) {
12490:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
12491:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
12492:                         }
12493:                     }
12494:                     if (@modifiable > 0) {
12495:                         $resulttext .= join(', ',@modifiable);
12496:                     } else {
12497:                         $resulttext .= &mt('none');
12498:                     }
12499:                     $resulttext .= '</li>';
12500:                 }
12501:                 $resulttext .= '</ul></li>';
12502:             }
12503:             $resulttext .= '</ul>';
12504:             my $cachetime = 24*60*60;
12505:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
12506:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
12507:             if (ref($lastactref) eq 'HASH') {
12508:                 $lastactref->{'domdefaults'} = 1;
12509:             }
12510:         } else {
12511:             $resulttext = &mt('No changes made to self-creation settings');
12512:         }
12513:     } else {
12514:         $resulttext = '<span class="LC_error">'.
12515:             &mt('An error occurred: [_1]',$putresult).'</span>';
12516:     }
12517:     if ($warningmsg ne '') {
12518:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
12519:     }
12520:     return $resulttext;
12521: }
12522: 
12523: sub process_captcha {
12524:     my ($container,$changes,$newsettings,$currsettings) = @_;
12525:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
12526:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
12527:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
12528:         $newsettings->{'captcha'} = 'original';
12529:     }
12530:     my %current;
12531:     if (ref($currsettings) eq 'HASH') {
12532:         %current = %{$currsettings};
12533:     }
12534:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
12535:         if ($container eq 'cancreate') {
12536:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
12537:                 push(@{$changes->{'cancreate'}},'captcha');
12538:             } elsif (!defined($changes->{'cancreate'})) {
12539:                 $changes->{'cancreate'} = ['captcha'];
12540:             }
12541:         } elsif ($container eq 'passwords') {
12542:             $changes->{'reset'} = 1;
12543:         } else {
12544:             $changes->{'captcha'} = 1;
12545:         }
12546:     }
12547:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
12548:     if ($newsettings->{'captcha'} eq 'recaptcha') {
12549:         $newpub = $env{'form.'.$container.'_recaptchapub'};
12550:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
12551:         $newpub =~ s/[^\w\-]//g;
12552:         $newpriv =~ s/[^\w\-]//g;
12553:         $newsettings->{'recaptchakeys'} = {
12554:                                              public  => $newpub,
12555:                                              private => $newpriv,
12556:                                           };
12557:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
12558:         $newversion =~ s/\D//g;
12559:         if ($newversion ne '2') {
12560:             $newversion = 1;
12561:         }
12562:         $newsettings->{'recaptchaversion'} = $newversion;
12563:     }
12564:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
12565:         $currpub = $current{'recaptchakeys'}{'public'};
12566:         $currpriv = $current{'recaptchakeys'}{'private'};
12567:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
12568:             $newsettings->{'recaptchakeys'} = {
12569:                                                  public  => '',
12570:                                                  private => '',
12571:                                               }
12572:         }
12573:     }
12574:     if ($current{'captcha'} eq 'recaptcha') {
12575:         $currversion = $current{'recaptchaversion'};
12576:         if ($currversion ne '2') {
12577:             $currversion = 1;
12578:         }
12579:     }
12580:     if ($currversion ne $newversion) {
12581:         if ($container eq 'cancreate') {
12582:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
12583:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
12584:             } elsif (!defined($changes->{'cancreate'})) {
12585:                 $changes->{'cancreate'} = ['recaptchaversion'];
12586:             }
12587:         } elsif ($container eq 'passwords') {
12588:             $changes->{'reset'} = 1;
12589:         } else {
12590:             $changes->{'recaptchaversion'} = 1;
12591:         }
12592:     }
12593:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
12594:         if ($container eq 'cancreate') {
12595:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
12596:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
12597:             } elsif (!defined($changes->{'cancreate'})) {
12598:                 $changes->{'cancreate'} = ['recaptchakeys'];
12599:             }
12600:         } elsif ($container eq 'passwords') {
12601:             $changes->{'reset'} = 1;
12602:         } else {
12603:             $changes->{'recaptchakeys'} = 1;
12604:         }
12605:     }
12606:     return;
12607: }
12608: 
12609: sub modify_usermodification {
12610:     my ($dom,%domconfig) = @_;
12611:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
12612:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
12613:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
12614:             if ($key eq 'selfcreate') {
12615:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
12616:             } else {  
12617:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
12618:             }
12619:         }
12620:     }
12621:     my @contexts = ('author','course');
12622:     my %context_title = (
12623:                            author => 'In author context',
12624:                            course => 'In course context',
12625:                         );
12626:     my @fields = ('lastname','firstname','middlename','generation',
12627:                   'permanentemail','id');
12628:     my %roles = (
12629:                   author => ['ca','aa'],
12630:                   course => ['st','ep','ta','in','cr'],
12631:                 );
12632:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
12633:     foreach my $context (@contexts) {
12634:         foreach my $role (@{$roles{$context}}) {
12635:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
12636:             foreach my $item (@fields) {
12637:                 if (grep(/^\Q$item\E$/,@modifiable)) {
12638:                     $modifyhash{$context}{$role}{$item} = 1;
12639:                 } else {
12640:                     $modifyhash{$context}{$role}{$item} = 0;
12641:                 }
12642:             }
12643:         }
12644:         if (ref($curr_usermodification{$context}) eq 'HASH') {
12645:             foreach my $role (@{$roles{$context}}) {
12646:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
12647:                     foreach my $field (@fields) {
12648:                         if ($modifyhash{$context}{$role}{$field} ne 
12649:                                 $curr_usermodification{$context}{$role}{$field}) {
12650:                             push(@{$changes{$context}},$role);
12651:                             last;
12652:                         }
12653:                     }
12654:                 }
12655:             }
12656:         } else {
12657:             foreach my $context (@contexts) {
12658:                 foreach my $role (@{$roles{$context}}) {
12659:                     push(@{$changes{$context}},$role);
12660:                 }
12661:             }
12662:         }
12663:     }
12664:     my %usermodification_hash =  (
12665:                                    usermodification => \%modifyhash,
12666:                                  );
12667:     my $putresult = &Apache::lonnet::put_dom('configuration',
12668:                                              \%usermodification_hash,$dom);
12669:     if ($putresult eq 'ok') {
12670:         if (keys(%changes) > 0) {
12671:             $resulttext = &mt('Changes made: ').'<ul>';
12672:             foreach my $context (@contexts) {
12673:                 if (ref($changes{$context}) eq 'ARRAY') {
12674:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
12675:                     if (ref($changes{$context}) eq 'ARRAY') {
12676:                         foreach my $role (@{$changes{$context}}) {
12677:                             my $rolename;
12678:                             if ($role eq 'cr') {
12679:                                 $rolename = &mt('Custom');
12680:                             } else {
12681:                                 $rolename = &Apache::lonnet::plaintext($role);
12682:                             }
12683:                             my @modifiable;
12684:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
12685:                             foreach my $field (@fields) {
12686:                                 if ($modifyhash{$context}{$role}{$field}) {
12687:                                     push(@modifiable,$fieldtitles{$field});
12688:                                 }
12689:                             }
12690:                             if (@modifiable > 0) {
12691:                                 $resulttext .= join(', ',@modifiable);
12692:                             } else {
12693:                                 $resulttext .= &mt('none'); 
12694:                             }
12695:                             $resulttext .= '</li>';
12696:                         }
12697:                         $resulttext .= '</ul></li>';
12698:                     }
12699:                 }
12700:             }
12701:             $resulttext .= '</ul>';
12702:         } else {
12703:             $resulttext = &mt('No changes made to user modification settings');
12704:         }
12705:     } else {
12706:         $resulttext = '<span class="LC_error">'.
12707:             &mt('An error occurred: [_1]',$putresult).'</span>';
12708:     }
12709:     return $resulttext;
12710: }
12711: 
12712: sub modify_defaults {
12713:     my ($dom,$lastactref,%domconfig) = @_;
12714:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
12715:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12716:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
12717:                  'portal_def');
12718:     my @authtypes = ('internal','krb4','krb5','localauth');
12719:     foreach my $item (@items) {
12720:         $newvalues{$item} = $env{'form.'.$item};
12721:         if ($item eq 'auth_def') {
12722:             if ($newvalues{$item} ne '') {
12723:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
12724:                     push(@errors,$item);
12725:                 }
12726:             }
12727:         } elsif ($item eq 'lang_def') {
12728:             if ($newvalues{$item} ne '') {
12729:                 if ($newvalues{$item} =~ /^(\w+)/) {
12730:                     my $langcode = $1;
12731:                     if ($langcode ne 'x_chef') {
12732:                         if (code2language($langcode) eq '') {
12733:                             push(@errors,$item);
12734:                         }
12735:                     }
12736:                 } else {
12737:                     push(@errors,$item);
12738:                 }
12739:             }
12740:         } elsif ($item eq 'timezone_def') {
12741:             if ($newvalues{$item} ne '') {
12742:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
12743:                     push(@errors,$item);   
12744:                 }
12745:             }
12746:         } elsif ($item eq 'datelocale_def') {
12747:             if ($newvalues{$item} ne '') {
12748:                 my @datelocale_ids = DateTime::Locale->ids();
12749:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
12750:                     push(@errors,$item);
12751:                 }
12752:             }
12753:         } elsif ($item eq 'portal_def') {
12754:             if ($newvalues{$item} ne '') {
12755:                 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])\/?$/) {
12756:                     push(@errors,$item);
12757:                 }
12758:             }
12759:         }
12760:         if (grep(/^\Q$item\E$/,@errors)) {
12761:             $newvalues{$item} = $domdefaults{$item};
12762:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
12763:             $changes{$item} = 1;
12764:         }
12765:         $domdefaults{$item} = $newvalues{$item};
12766:     }
12767:     my %staticdefaults = (
12768:                            'intauth_cost'   => 10,
12769:                            'intauth_check'  => 0,
12770:                            'intauth_switch' => 0,
12771:                          );
12772:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
12773:         if (exists($domdefaults{$item})) {
12774:             $newvalues{$item} = $domdefaults{$item};
12775:         } else {
12776:             $newvalues{$item} = $staticdefaults{$item};
12777:         }
12778:     }
12779:     my %defaults_hash = (
12780:                          defaults => \%newvalues,
12781:                         );
12782:     my $title = &defaults_titles();
12783: 
12784:     my $currinststatus;
12785:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
12786:         $currinststatus = $domconfig{'inststatus'};
12787:     } else {
12788:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
12789:         $currinststatus = {
12790:                              inststatustypes => $usertypes,
12791:                              inststatusorder => $types,
12792:                              inststatusguest => [],
12793:                           };
12794:     }
12795:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
12796:     my @allpos;
12797:     my %alltypes;
12798:     my @inststatusguest;
12799:     if (ref($currinststatus) eq 'HASH') {
12800:         if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
12801:             foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
12802:                 unless (grep(/^\Q$type\E$/,@todelete)) {
12803:                     push(@inststatusguest,$type);
12804:                 }
12805:             }
12806:         }
12807:     }
12808:     my ($currtitles,$currorder);
12809:     if (ref($currinststatus) eq 'HASH') {
12810:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
12811:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
12812:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
12813:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
12814:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
12815:                     }
12816:                 }
12817:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
12818:                     my $position = $env{'form.inststatus_pos_'.$type};
12819:                     $position =~ s/\D+//g;
12820:                     $allpos[$position] = $type;
12821:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
12822:                     $alltypes{$type} =~ s/`//g;
12823:                 }
12824:             }
12825:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
12826:             $currtitles =~ s/,$//;
12827:         }
12828:     }
12829:     if ($env{'form.addinststatus'}) {
12830:         my $newtype = $env{'form.addinststatus'};
12831:         $newtype =~ s/\W//g;
12832:         unless (exists($alltypes{$newtype})) {
12833:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
12834:             $alltypes{$newtype} =~ s/`//g; 
12835:             my $position = $env{'form.addinststatus_pos'};
12836:             $position =~ s/\D+//g;
12837:             if ($position ne '') {
12838:                 $allpos[$position] = $newtype;
12839:             }
12840:         }
12841:     }
12842:     my @orderedstatus;
12843:     foreach my $type (@allpos) {
12844:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
12845:             push(@orderedstatus,$type);
12846:         }
12847:     }
12848:     foreach my $type (keys(%alltypes)) {
12849:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
12850:             delete($alltypes{$type});
12851:         }
12852:     }
12853:     $defaults_hash{'inststatus'} = {
12854:                                      inststatustypes => \%alltypes,
12855:                                      inststatusorder => \@orderedstatus,
12856:                                      inststatusguest => \@inststatusguest,
12857:                                    };
12858:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
12859:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
12860:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
12861:         }
12862:     }
12863:     if ($currorder ne join(',',@orderedstatus)) {
12864:         $changes{'inststatus'}{'inststatusorder'} = 1;
12865:     }
12866:     my $newtitles;
12867:     foreach my $item (@orderedstatus) {
12868:         $newtitles .= $alltypes{$item}.',';
12869:     }
12870:     $newtitles =~ s/,$//;
12871:     if ($currtitles ne $newtitles) {
12872:         $changes{'inststatus'}{'inststatustypes'} = 1;
12873:     }
12874:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
12875:                                              $dom);
12876:     if ($putresult eq 'ok') {
12877:         if (keys(%changes) > 0) {
12878:             $resulttext = &mt('Changes made:').'<ul>';
12879:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
12880:             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";
12881:             foreach my $item (sort(keys(%changes))) {
12882:                 if ($item eq 'inststatus') {
12883:                     if (ref($changes{'inststatus'}) eq 'HASH') {
12884:                         if (@orderedstatus) {
12885:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
12886:                             foreach my $type (@orderedstatus) { 
12887:                                 $resulttext .= $alltypes{$type}.', ';
12888:                             }
12889:                             $resulttext =~ s/, $//;
12890:                             $resulttext .= '</li>';
12891:                         } else {
12892:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>';
12893:                         }
12894:                     }
12895:                 } else {
12896:                     my $value = $env{'form.'.$item};
12897:                     if ($value eq '') {
12898:                         $value = &mt('none');
12899:                     } elsif ($item eq 'auth_def') {
12900:                         my %authnames = &authtype_names();
12901:                         my %shortauth = (
12902:                                           internal   => 'int',
12903:                                           krb4       => 'krb4',
12904:                                           krb5       => 'krb5',
12905:                                           localauth  => 'loc',
12906:                         );
12907:                         $value = $authnames{$shortauth{$value}};
12908:                     }
12909:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
12910:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
12911:                 }
12912:             }
12913:             $resulttext .= '</ul>';
12914:             $mailmsgtext .= "\n";
12915:             my $cachetime = 24*60*60;
12916:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
12917:             if (ref($lastactref) eq 'HASH') {
12918:                 $lastactref->{'domdefaults'} = 1;
12919:             }
12920:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
12921:                 my $notify = 1;
12922:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
12923:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
12924:                         $notify = 0;
12925:                     }
12926:                 }
12927:                 if ($notify) {
12928:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
12929:                                                "LON-CAPA Domain Settings Change - $dom",
12930:                                                $mailmsgtext);
12931:                 }
12932:             }
12933:         } else {
12934:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
12935:         }
12936:     } else {
12937:         $resulttext = '<span class="LC_error">'.
12938:             &mt('An error occurred: [_1]',$putresult).'</span>';
12939:     }
12940:     if (@errors > 0) {
12941:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
12942:         foreach my $item (@errors) {
12943:             $resulttext .= ' "'.$title->{$item}.'",';
12944:         }
12945:         $resulttext =~ s/,$//;
12946:     }
12947:     return $resulttext;
12948: }
12949: 
12950: sub modify_scantron {
12951:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
12952:     my ($resulttext,%confhash,%changes,$errors);
12953:     my $custom = 'custom.tab';
12954:     my $default = 'default.tab';
12955:     my $servadm = $r->dir_config('lonAdmEMail');
12956:     my ($configuserok,$author_ok,$switchserver) =
12957:         &config_check($dom,$confname,$servadm);
12958:     if ($env{'form.scantronformat.filename'} ne '') {
12959:         my $error;
12960:         if ($configuserok eq 'ok') {
12961:             if ($switchserver) {
12962:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
12963:             } else {
12964:                 if ($author_ok eq 'ok') {
12965:                     my ($result,$scantronurl) =
12966:                         &publishlogo($r,'upload','scantronformat',$dom,
12967:                                      $confname,'scantron','','',$custom);
12968:                     if ($result eq 'ok') {
12969:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
12970:                         $changes{'scantronformat'} = 1;
12971:                     } else {
12972:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
12973:                     }
12974:                 } else {
12975:                     $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);
12976:                 }
12977:             }
12978:         } else {
12979:             $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);
12980:         }
12981:         if ($error) {
12982:             &Apache::lonnet::logthis($error);
12983:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12984:         }
12985:     }
12986:     if (ref($domconfig{'scantron'}) eq 'HASH') {
12987:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
12988:             if ($env{'form.scantronformat_del'}) {
12989:                 $confhash{'scantron'}{'scantronformat'} = '';
12990:                 $changes{'scantronformat'} = 1;
12991:             } else {
12992:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
12993:             }
12994:         }
12995:     }
12996:     my @options = ('hdr','pad','rem');
12997:     my @fields = &scantroncsv_fields();
12998:     my %titles = &scantronconfig_titles();
12999:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
13000:     my ($newdat,$currdat,%newcol,%currcol);
13001:     if (grep(/^dat$/,@formats)) {
13002:         $confhash{'scantron'}{config}{dat} = 1;
13003:         $newdat = 1;
13004:     } else {
13005:         $newdat = 0;
13006:     }
13007:     if (grep(/^csv$/,@formats)) {
13008:         my %bynum;
13009:         foreach my $field (@fields) {
13010:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
13011:                 my $posscol = $1;
13012:                 if (($posscol < 20) && (!$bynum{$posscol})) {
13013:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
13014:                     $bynum{$posscol} = $field;
13015:                     $newcol{$field} = $posscol;
13016:                 }
13017:             }
13018:         }
13019:         if (keys(%newcol)) {
13020:             foreach my $option (@options) {
13021:                 if ($env{'form.scantroncsv_'.$option}) {
13022:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
13023:                 }
13024:             }
13025:         }
13026:     }
13027:     $currdat = 1;
13028:     if (ref($domconfig{'scantron'}) eq 'HASH') {
13029:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
13030:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
13031:                 $currdat = 0;
13032:             }
13033:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
13034:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
13035:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
13036:                 }
13037:             }
13038:         }
13039:     }
13040:     if ($currdat != $newdat) {
13041:         $changes{'config'} = 1;
13042:     } else {
13043:         foreach my $field (@fields) {
13044:             if ($currcol{$field} ne '') {
13045:                 if ($currcol{$field} ne $newcol{$field}) {
13046:                     $changes{'config'} = 1;
13047:                     last;
13048:                 }
13049:             } elsif ($newcol{$field} ne '') {
13050:                 $changes{'config'} = 1;
13051:                 last;
13052:             }
13053:         }
13054:     }
13055:     if (keys(%confhash) > 0) {
13056:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
13057:                                                  $dom);
13058:         if ($putresult eq 'ok') {
13059:             if (keys(%changes) > 0) {
13060:                 if (ref($confhash{'scantron'}) eq 'HASH') {
13061:                     $resulttext = &mt('Changes made:').'<ul>';
13062:                     if ($changes{'scantronformat'}) {
13063:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
13064:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
13065:                         } else {
13066:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
13067:                         }
13068:                     }
13069:                     if ($changes{'config'}) {
13070:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
13071:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
13072:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
13073:                             }
13074:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
13075:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
13076:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
13077:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
13078:                                         foreach my $field (@fields) {
13079:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
13080:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
13081:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
13082:                                             }
13083:                                         }
13084:                                         $resulttext .= '</ul></li>';
13085:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
13086:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
13087:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
13088:                                                 foreach my $option (@options) {
13089:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
13090:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
13091:                                                     }
13092:                                                 }
13093:                                                 $resulttext .= '</ul></li>';
13094:                                             }
13095:                                         }
13096:                                     }
13097:                                 }
13098:                             }
13099:                         } else {
13100:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
13101:                         }
13102:                     }
13103:                     $resulttext .= '</ul>';
13104:                 } else {
13105:                     $resulttext = &mt('Changes made to bubblesheet format file.');
13106:                 }
13107:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
13108:                 if (ref($lastactref) eq 'HASH') {
13109:                     $lastactref->{'domainconfig'} = 1;
13110:                 }
13111:             } else {
13112:                 $resulttext = &mt('No changes made to bubblesheet format settings');
13113:             }
13114:         } else {
13115:             $resulttext = '<span class="LC_error">'.
13116:                 &mt('An error occurred: [_1]',$putresult).'</span>';
13117:         }
13118:     } else {
13119:         $resulttext = &mt('No changes made to bubblesheet format settings');
13120:     }
13121:     if ($errors) {
13122:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
13123:                        $errors.'</ul>';
13124:     }
13125:     return $resulttext;
13126: }
13127: 
13128: sub modify_coursecategories {
13129:     my ($dom,$lastactref,%domconfig) = @_;
13130:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
13131:         $cathash);
13132:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
13133:     my @catitems = ('unauth','auth');
13134:     my @cattypes = ('std','domonly','codesrch','none');
13135:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
13136:         $cathash = $domconfig{'coursecategories'}{'cats'};
13137:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
13138:             $changes{'togglecats'} = 1;
13139:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
13140:         }
13141:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
13142:             $changes{'categorize'} = 1;
13143:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
13144:         }
13145:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
13146:             $changes{'togglecatscomm'} = 1;
13147:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
13148:         }
13149:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
13150:             $changes{'categorizecomm'} = 1;
13151:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
13152:         }
13153:         foreach my $item (@catitems) {
13154:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
13155:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
13156:                     $changes{$item} = 1;
13157:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
13158:                 }
13159:             }
13160:         }
13161:     } else {
13162:         $changes{'togglecats'} = 1;
13163:         $changes{'categorize'} = 1;
13164:         $changes{'togglecatscomm'} = 1;
13165:         $changes{'categorizecomm'} = 1;
13166:         $domconfig{'coursecategories'} = {
13167:                                              togglecats => $env{'form.togglecats'},
13168:                                              categorize => $env{'form.categorize'},
13169:                                              togglecatscomm => $env{'form.togglecatscomm'},
13170:                                              categorizecomm => $env{'form.categorizecomm'},
13171:                                          };
13172:         foreach my $item (@catitems) {
13173:             if ($env{'form.coursecat_'.$item} ne 'std') {
13174:                 $changes{$item} = 1;
13175:             }
13176:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
13177:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
13178:             }
13179:         }
13180:     }
13181:     if (ref($cathash) eq 'HASH') {
13182:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
13183:             push (@deletecategory,'instcode::0');
13184:         }
13185:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
13186:             push(@deletecategory,'communities::0');
13187:         }
13188:     }
13189:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
13190:     if (ref($cathash) eq 'HASH') {
13191:         if (@deletecategory > 0) {
13192:             #FIXME Need to remove category from all courses using a deleted category 
13193:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
13194:             foreach my $item (@deletecategory) {
13195:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
13196:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
13197:                     $deletions{$item} = 1;
13198:                     &recurse_cat_deletes($item,$cathash,\%deletions);
13199:                 }
13200:             }
13201:         }
13202:         foreach my $item (keys(%{$cathash})) {
13203:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
13204:             if ($cathash->{$item} ne $env{'form.'.$item}) {
13205:                 $reorderings{$item} = 1;
13206:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
13207:             }
13208:             if ($env{'form.addcategory_name_'.$item} ne '') {
13209:                 my $newcat = $env{'form.addcategory_name_'.$item};
13210:                 my $newdepth = $depth+1;
13211:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
13212:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
13213:                 $adds{$newitem} = 1; 
13214:             }
13215:             if ($env{'form.subcat_'.$item} ne '') {
13216:                 my $newcat = $env{'form.subcat_'.$item};
13217:                 my $newdepth = $depth+1;
13218:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
13219:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
13220:                 $adds{$newitem} = 1;
13221:             }
13222:         }
13223:     }
13224:     if ($env{'form.instcode'} eq '1') {
13225:         if (ref($cathash) eq 'HASH') {
13226:             my $newitem = 'instcode::0';
13227:             if ($cathash->{$newitem} eq '') {  
13228:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
13229:                 $adds{$newitem} = 1;
13230:             }
13231:         } else {
13232:             my $newitem = 'instcode::0';
13233:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
13234:             $adds{$newitem} = 1;
13235:         }
13236:     }
13237:     if ($env{'form.communities'} eq '1') {
13238:         if (ref($cathash) eq 'HASH') {
13239:             my $newitem = 'communities::0';
13240:             if ($cathash->{$newitem} eq '') {
13241:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
13242:                 $adds{$newitem} = 1;
13243:             }
13244:         } else {
13245:             my $newitem = 'communities::0';
13246:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
13247:             $adds{$newitem} = 1;
13248:         }
13249:     }
13250:     if ($env{'form.addcategory_name'} ne '') {
13251:         if (($env{'form.addcategory_name'} ne 'instcode') &&
13252:             ($env{'form.addcategory_name'} ne 'communities')) {
13253:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
13254:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
13255:             $adds{$newitem} = 1;
13256:         }
13257:     }
13258:     my $putresult;
13259:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
13260:         if (keys(%deletions) > 0) {
13261:             foreach my $key (keys(%deletions)) {
13262:                 if ($predelallitems{$key} ne '') {
13263:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
13264:                 }
13265:             }
13266:         }
13267:         my (@chkcats,@chktrails,%chkallitems);
13268:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
13269:         if (ref($chkcats[0]) eq 'ARRAY') {
13270:             my $depth = 0;
13271:             my $chg = 0;
13272:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
13273:                 my $name = $chkcats[0][$i];
13274:                 my $item;
13275:                 if ($name eq '') {
13276:                     $chg ++;
13277:                 } else {
13278:                     $item = &escape($name).'::0';
13279:                     if ($chg) {
13280:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
13281:                     }
13282:                     $depth ++; 
13283:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
13284:                     $depth --;
13285:                 }
13286:             }
13287:         }
13288:     }
13289:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
13290:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
13291:         if ($putresult eq 'ok') {
13292:             my %title = (
13293:                          togglecats     => 'Show/Hide a course in catalog',
13294:                          categorize     => 'Assign a category to a course',
13295:                          togglecatscomm => 'Show/Hide a community in catalog',
13296:                          categorizecomm => 'Assign a category to a community',
13297:                         );
13298:             my %level = (
13299:                          dom  => 'set in Domain ("Modify Course/Community")',
13300:                          crs  => 'set in Course ("Course Configuration")',
13301:                          comm => 'set in Community ("Community Configuration")',
13302:                          none     => 'No catalog',
13303:                          std      => 'Standard catalog',
13304:                          domonly  => 'Domain-only catalog',
13305:                          codesrch => 'Code search form',
13306:                         );
13307:             $resulttext = &mt('Changes made:').'<ul>';
13308:             if ($changes{'togglecats'}) {
13309:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
13310:             }
13311:             if ($changes{'categorize'}) {
13312:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
13313:             }
13314:             if ($changes{'togglecatscomm'}) {
13315:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
13316:             }
13317:             if ($changes{'categorizecomm'}) {
13318:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
13319:             }
13320:             if ($changes{'unauth'}) {
13321:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
13322:             }
13323:             if ($changes{'auth'}) {
13324:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
13325:             }
13326:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
13327:                 my $cathash;
13328:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
13329:                     $cathash = $domconfig{'coursecategories'}{'cats'};
13330:                 } else {
13331:                     $cathash = {};
13332:                 } 
13333:                 my (@cats,@trails,%allitems);
13334:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
13335:                 if (keys(%deletions) > 0) {
13336:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
13337:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
13338:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
13339:                     }
13340:                     $resulttext .= '</ul></li>';
13341:                 }
13342:                 if (keys(%reorderings) > 0) {
13343:                     my %sort_by_trail;
13344:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
13345:                     foreach my $key (keys(%reorderings)) {
13346:                         if ($allitems{$key} ne '') {
13347:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
13348:                         }
13349:                     }
13350:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
13351:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
13352:                     }
13353:                     $resulttext .= '</ul></li>';
13354:                 }
13355:                 if (keys(%adds) > 0) {
13356:                     my %sort_by_trail;
13357:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
13358:                     foreach my $key (keys(%adds)) {
13359:                         if ($allitems{$key} ne '') {
13360:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
13361:                         }
13362:                     }
13363:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
13364:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
13365:                     }
13366:                     $resulttext .= '</ul></li>';
13367:                 }
13368:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
13369:                 if (ref($lastactref) eq 'HASH') {
13370:                     $lastactref->{'cats'} = 1;
13371:                 }
13372:             }
13373:             $resulttext .= '</ul>';
13374:             if ($changes{'unauth'} || $changes{'auth'}) {
13375:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
13376:                 if ($changes{'auth'}) {
13377:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
13378:                 }
13379:                 if ($changes{'unauth'}) {
13380:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
13381:                 }
13382:                 my $cachetime = 24*60*60;
13383:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
13384:                 if (ref($lastactref) eq 'HASH') {
13385:                     $lastactref->{'domdefaults'} = 1;
13386:                 }
13387:             }
13388:         } else {
13389:             $resulttext = '<span class="LC_error">'.
13390:                           &mt('An error occurred: [_1]',$putresult).'</span>';
13391:         }
13392:     } else {
13393:         $resulttext = &mt('No changes made to course and community categories');
13394:     }
13395:     return $resulttext;
13396: }
13397: 
13398: sub modify_serverstatuses {
13399:     my ($dom,%domconfig) = @_;
13400:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
13401:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
13402:         %currserverstatus = %{$domconfig{'serverstatuses'}};
13403:     }
13404:     my @pages = &serverstatus_pages();
13405:     foreach my $type (@pages) {
13406:         $newserverstatus{$type}{'namedusers'} = '';
13407:         $newserverstatus{$type}{'machines'} = '';
13408:         if (defined($env{'form.'.$type.'_namedusers'})) {
13409:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
13410:             my @okusers;
13411:             foreach my $user (@users) {
13412:                 my ($uname,$udom) = split(/:/,$user);
13413:                 if (($udom =~ /^$match_domain$/) &&   
13414:                     (&Apache::lonnet::domain($udom)) &&
13415:                     ($uname =~ /^$match_username$/)) {
13416:                     if (!grep(/^\Q$user\E/,@okusers)) {
13417:                         push(@okusers,$user);
13418:                     }
13419:                 }
13420:             }
13421:             if (@okusers > 0) {
13422:                  @okusers = sort(@okusers);
13423:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
13424:             }
13425:         }
13426:         if (defined($env{'form.'.$type.'_machines'})) {
13427:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
13428:             my @okmachines;
13429:             foreach my $ip (@machines) {
13430:                 my @parts = split(/\./,$ip);
13431:                 next if (@parts < 4);
13432:                 my $badip = 0;
13433:                 for (my $i=0; $i<4; $i++) {
13434:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
13435:                         $badip = 1;
13436:                         last;
13437:                     }
13438:                 }
13439:                 if (!$badip) {
13440:                     push(@okmachines,$ip);     
13441:                 }
13442:             }
13443:             @okmachines = sort(@okmachines);
13444:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
13445:         }
13446:     }
13447:     my %serverstatushash =  (
13448:                                 serverstatuses => \%newserverstatus,
13449:                             );
13450:     foreach my $type (@pages) {
13451:         foreach my $setting ('namedusers','machines') {
13452:             my (@current,@new);
13453:             if (ref($currserverstatus{$type}) eq 'HASH') {
13454:                 if ($currserverstatus{$type}{$setting} ne '') { 
13455:                     @current = split(/,/,$currserverstatus{$type}{$setting});
13456:                 }
13457:             }
13458:             if ($newserverstatus{$type}{$setting} ne '') {
13459:                 @new = split(/,/,$newserverstatus{$type}{$setting});
13460:             }
13461:             if (@current > 0) {
13462:                 if (@new > 0) {
13463:                     foreach my $item (@current) {
13464:                         if (!grep(/^\Q$item\E$/,@new)) {
13465:                             $changes{$type}{$setting} = 1;
13466:                             last;
13467:                         }
13468:                     }
13469:                     foreach my $item (@new) {
13470:                         if (!grep(/^\Q$item\E$/,@current)) {
13471:                             $changes{$type}{$setting} = 1;
13472:                             last;
13473:                         }
13474:                     }
13475:                 } else {
13476:                     $changes{$type}{$setting} = 1;
13477:                 }
13478:             } elsif (@new > 0) {
13479:                 $changes{$type}{$setting} = 1;
13480:             }
13481:         }
13482:     }
13483:     if (keys(%changes) > 0) {
13484:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
13485:         my $putresult = &Apache::lonnet::put_dom('configuration',
13486:                                                  \%serverstatushash,$dom);
13487:         if ($putresult eq 'ok') {
13488:             $resulttext .= &mt('Changes made:').'<ul>';
13489:             foreach my $type (@pages) {
13490:                 if (ref($changes{$type}) eq 'HASH') {
13491:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
13492:                     if ($changes{$type}{'namedusers'}) {
13493:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
13494:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
13495:                         } else {
13496:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
13497:                         }
13498:                     }
13499:                     if ($changes{$type}{'machines'}) {
13500:                         if ($newserverstatus{$type}{'machines'} eq '') {
13501:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
13502:                         } else {
13503:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
13504:                         }
13505: 
13506:                     }
13507:                     $resulttext .= '</ul></li>';
13508:                 }
13509:             }
13510:             $resulttext .= '</ul>';
13511:         } else {
13512:             $resulttext = '<span class="LC_error">'.
13513:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
13514: 
13515:         }
13516:     } else {
13517:         $resulttext = &mt('No changes made to access to server status pages');
13518:     }
13519:     return $resulttext;
13520: }
13521: 
13522: sub modify_helpsettings {
13523:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
13524:     my ($resulttext,$errors,%changes,%helphash);
13525:     my %defaultchecked = ('submitbugs' => 'on');
13526:     my @offon = ('off','on');
13527:     my @toggles = ('submitbugs');
13528:     my %current = ('submitbugs' => '',
13529:                    'adhoc'      => {},
13530:                   );
13531:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
13532:         %current = %{$domconfig{'helpsettings'}};
13533:     }
13534:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13535:     foreach my $item (@toggles) {
13536:         if ($defaultchecked{$item} eq 'on') { 
13537:             if ($current{$item} eq '') {
13538:                 if ($env{'form.'.$item} eq '0') {
13539:                     $changes{$item} = 1;
13540:                 }
13541:             } elsif ($current{$item} ne $env{'form.'.$item}) {
13542:                 $changes{$item} = 1;
13543:             }
13544:         } elsif ($defaultchecked{$item} eq 'off') {
13545:             if ($current{$item} eq '') {
13546:                 if ($env{'form.'.$item} eq '1') {
13547:                     $changes{$item} = 1;
13548:                 }
13549:             } elsif ($current{$item} ne $env{'form.'.$item}) {
13550:                 $changes{$item} = 1;
13551:             }
13552:         }
13553:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
13554:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
13555:         }
13556:     }
13557:     my $maxnum = $env{'form.helproles_maxnum'};
13558:     my $confname = $dom.'-domainconfig';
13559:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
13560:     my (@allpos,%newsettings,%changedprivs,$newrole);
13561:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13562:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
13563:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
13564:     my %lt = &Apache::lonlocal::texthash(
13565:                     s      => 'system',
13566:                     d      => 'domain',
13567:                     order  => 'Display order',
13568:                     access => 'Role usage',
13569:                     all    => 'All with domain helpdesk or helpdesk assistant role',
13570:                     dh     => 'All with domain helpdesk role',
13571:                     da     => 'All with domain helpdesk assistant role',
13572:                     none   => 'None',
13573:                     status => 'Determined based on institutional status',
13574:                     inc    => 'Include all, but exclude specific personnel',
13575:                     exc    => 'Exclude all, but include specific personnel',
13576:     );
13577:     for (my $num=0; $num<=$maxnum; $num++) {
13578:         my ($prefix,$identifier,$rolename,%curr);
13579:         if ($num == $maxnum) {
13580:             next unless ($env{'form.newcusthelp'} == $maxnum);
13581:             $identifier = 'custhelp'.$num;
13582:             $prefix = 'helproles_'.$num;
13583:             $rolename = $env{'form.custhelpname'.$num};
13584:             $rolename=~s/[^A-Za-z0-9]//gs;
13585:             next if ($rolename eq '');
13586:             next if (exists($existing{'rolesdef_'.$rolename}));
13587:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
13588:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
13589:                                                      $newprivs{'c'},$confname,$dom);
13590:             if ($result ne 'ok') {
13591:                 $errors .= '<li><span class="LC_error">'.
13592:                            &mt('An error occurred storing the new custom role: [_1]',
13593:                            $result).'</span></li>';
13594:                 next;
13595:             } else {
13596:                 $changedprivs{$rolename} = \%newprivs;
13597:                 $newrole = $rolename;
13598:             }
13599:         } else {
13600:             $prefix = 'helproles_'.$num;
13601:             $rolename = $env{'form.'.$prefix};
13602:             next if ($rolename eq '');
13603:             next unless (exists($existing{'rolesdef_'.$rolename}));
13604:             $identifier = 'custhelp'.$num;
13605:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
13606:             my %currprivs;
13607:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
13608:                 split(/\_/,$existing{'rolesdef_'.$rolename});
13609:             foreach my $level ('c','d','s') {
13610:                 if ($newprivs{$level} ne $currprivs{$level}) {
13611:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
13612:                                                              $newprivs{'c'},$confname,$dom);
13613:                     if ($result ne 'ok') {
13614:                         $errors .= '<li><span class="LC_error">'.
13615:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
13616:                                        $rolename,$result).'</span></li>';
13617:                     } else {
13618:                         $changedprivs{$rolename} = \%newprivs;
13619:                     }
13620:                     last;
13621:                 }
13622:             }
13623:             if (ref($current{'adhoc'}) eq 'HASH') {
13624:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
13625:                     %curr = %{$current{'adhoc'}{$rolename}};
13626:                 }
13627:             }
13628:         }
13629:         my $newpos = $env{'form.'.$prefix.'_pos'};
13630:         $newpos =~ s/\D+//g;
13631:         $allpos[$newpos] = $rolename;
13632:         my $newdesc = $env{'form.'.$prefix.'_desc'};
13633:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
13634:         if ($curr{'desc'}) {
13635:             if ($curr{'desc'} ne $newdesc) {
13636:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
13637:                 $newsettings{$rolename}{'desc'} = $newdesc;
13638:             }
13639:         } elsif ($newdesc ne '') {
13640:             $changes{'customrole'}{$rolename}{'desc'} = 1;
13641:             $newsettings{$rolename}{'desc'} = $newdesc;
13642:         }
13643:         my $access = $env{'form.'.$prefix.'_access'};
13644:         if (grep(/^\Q$access\E$/,@accesstypes)) {
13645:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
13646:             if ($access eq 'status') {
13647:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
13648:                 if (scalar(@statuses) == 0) {
13649:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
13650:                 } else {
13651:                     my (@shownstatus,$numtypes);
13652:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
13653:                     if (ref($types) eq 'ARRAY') {
13654:                         $numtypes = scalar(@{$types});
13655:                         foreach my $type (sort(@statuses)) {
13656:                             if ($type eq 'default') {
13657:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
13658:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
13659:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
13660:                                 push(@shownstatus,$usertypes->{$type});
13661:                             }
13662:                         }
13663:                     }
13664:                     if (grep(/^default$/,@statuses)) {
13665:                         push(@shownstatus,$othertitle);
13666:                     }
13667:                     if (scalar(@shownstatus) == 1+$numtypes) {
13668:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
13669:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
13670:                     } else {
13671:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
13672:                         if (ref($curr{'status'}) eq 'ARRAY') {
13673:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
13674:                             if (@diffs) {
13675:                                 $changes{'customrole'}{$rolename}{$access} = 1;
13676:                             }
13677:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
13678:                             $changes{'customrole'}{$rolename}{$access} = 1;
13679:                         }
13680:                     }
13681:                 }
13682:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
13683:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
13684:                 my @newspecstaff;
13685:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
13686:                 foreach my $person (sort(@personnel)) {
13687:                     if ($domhelpdesk{$person}) {
13688:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
13689:                     }
13690:                 }
13691:                 if (ref($curr{$access}) eq 'ARRAY') {
13692:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
13693:                     if (@diffs) {
13694:                         $changes{'customrole'}{$rolename}{$access} = 1;
13695:                     }
13696:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
13697:                     $changes{'customrole'}{$rolename}{$access} = 1;
13698:                 }
13699:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
13700:                     my ($uname,$udom) = split(/:/,$person);
13701:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
13702:                 }
13703:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
13704:             }
13705:         } else {
13706:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
13707:         }
13708:         unless ($curr{'access'} eq $access) {
13709:             $changes{'customrole'}{$rolename}{'access'} = 1;
13710:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
13711:         }
13712:     }
13713:     if (@allpos > 0) {
13714:         my $idx = 0;
13715:         foreach my $rolename (@allpos) {
13716:             if ($rolename ne '') {
13717:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
13718:                 if (ref($current{'adhoc'}) eq 'HASH') {
13719:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
13720:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
13721:                             $changes{'customrole'}{$rolename}{'order'} = 1;
13722:                             $newsettings{$rolename}{'order'} = $idx+1;
13723:                         }
13724:                     }
13725:                 }
13726:                 $idx ++;
13727:             }
13728:         }
13729:     }
13730:     my $putresult;
13731:     if (keys(%changes) > 0) {
13732:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
13733:         if ($putresult eq 'ok') {
13734:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
13735:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
13736:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
13737:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
13738:                 }
13739:             }
13740:             my $cachetime = 24*60*60;
13741:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
13742:             if (ref($lastactref) eq 'HASH') {
13743:                 $lastactref->{'domdefaults'} = 1;
13744:             }
13745:         } else {
13746:             $errors .= '<li><span class="LC_error">'.
13747:                        &mt('An error occurred storing the settings: [_1]',
13748:                            $putresult).'</span></li>';
13749:         }
13750:     }
13751:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
13752:         $resulttext = &mt('Changes made:').'<ul>';
13753:         my (%shownprivs,@levelorder);
13754:         @levelorder = ('c','d','s');
13755:         if ((keys(%changes)) && ($putresult eq 'ok')) {
13756:             foreach my $item (sort(keys(%changes))) {
13757:                 if ($item eq 'submitbugs') {
13758:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
13759:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
13760:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
13761:                 } elsif ($item eq 'customrole') {
13762:                     if (ref($changes{'customrole'}) eq 'HASH') {
13763:                         my @keyorder = ('order','desc','access','status','exc','inc');
13764:                         my %keytext = &Apache::lonlocal::texthash(
13765:                                                                    order  => 'Order',
13766:                                                                    desc   => 'Role description',
13767:                                                                    access => 'Role usage',
13768:                                                                    status => 'Allowed institutional types',
13769:                                                                    exc    => 'Allowed personnel',
13770:                                                                    inc    => 'Disallowed personnel',
13771:                         );
13772:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
13773:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
13774:                                 if ($role eq $newrole) {
13775:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
13776:                                                               $role).'<ul>';
13777:                                 } else {
13778:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
13779:                                                               $role).'<ul>';
13780:                                 }
13781:                                 foreach my $key (@keyorder) {
13782:                                     if ($changes{'customrole'}{$role}{$key}) {
13783:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
13784:                                                                   $keytext{$key},$newsettings{$role}{$key}).
13785:                                                        '</li>';
13786:                                     }
13787:                                 }
13788:                                 if (ref($changedprivs{$role}) eq 'HASH') {
13789:                                     $shownprivs{$role} = 1;
13790:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
13791:                                     foreach my $level (@levelorder) {
13792:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
13793:                                             next if ($item eq '');
13794:                                             my ($priv) = split(/\&/,$item,2);
13795:                                             if (&Apache::lonnet::plaintext($priv)) {
13796:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
13797:                                                 unless ($level eq 'c') {
13798:                                                     $resulttext .= ' ('.$lt{$level}.')';
13799:                                                 }
13800:                                                 $resulttext .= '</li>';
13801:                                             }
13802:                                         }
13803:                                     }
13804:                                     $resulttext .= '</ul>';
13805:                                 }
13806:                                 $resulttext .= '</ul></li>';
13807:                             }
13808:                         }
13809:                     }
13810:                 }
13811:             }
13812:         }
13813:         if (keys(%changedprivs)) {
13814:             foreach my $role (sort(keys(%changedprivs))) {
13815:                 unless ($shownprivs{$role}) {
13816:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
13817:                                               $role).'<ul>'.
13818:                                    '<li>'.&mt('Privileges set to :').'<ul>';
13819:                     foreach my $level (@levelorder) {
13820:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
13821:                             next if ($item eq '');
13822:                             my ($priv) = split(/\&/,$item,2);
13823:                             if (&Apache::lonnet::plaintext($priv)) {
13824:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
13825:                                 unless ($level eq 'c') {
13826:                                     $resulttext .= ' ('.$lt{$level}.')';
13827:                                 }
13828:                                 $resulttext .= '</li>';
13829:                             }
13830:                         }
13831:                     }
13832:                     $resulttext .= '</ul></li></ul></li>';
13833:                 }
13834:             }
13835:         }
13836:         $resulttext .= '</ul>';
13837:     } else {
13838:         $resulttext = &mt('No changes made to help settings');
13839:     }
13840:     if ($errors) {
13841:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
13842:                                     $errors.'</ul>';
13843:     }
13844:     return $resulttext;
13845: }
13846: 
13847: sub modify_coursedefaults {
13848:     my ($dom,$lastactref,%domconfig) = @_;
13849:     my ($resulttext,$errors,%changes,%defaultshash);
13850:     my %defaultchecked = (
13851:                            'uselcmath'       => 'on',
13852:                            'usejsme'         => 'on'
13853:                          );
13854:     my @toggles = ('uselcmath','usejsme');
13855:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
13856:                    'uploadquota_community','uploadquota_textbook','mysqltables_official',
13857:                    'mysqltables_unofficial','mysqltables_community','mysqltables_textbook');
13858:     my @types = ('official','unofficial','community','textbook');
13859:     my %staticdefaults = (
13860:                            anonsurvey_threshold => 10,
13861:                            uploadquota          => 500,
13862:                            postsubmit           => 60,
13863:                            mysqltables          => 172800,
13864:                          );
13865:     my %texoptions = (
13866:                         MathJax  => 'MathJax',
13867:                         mimetex  => &mt('Convert to Images'),
13868:                         tth      => &mt('TeX to HTML'),
13869:                      );
13870:     $defaultshash{'coursedefaults'} = {};
13871: 
13872:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
13873:         if ($domconfig{'coursedefaults'} eq '') {
13874:             $domconfig{'coursedefaults'} = {};
13875:         }
13876:     }
13877: 
13878:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
13879:         foreach my $item (@toggles) {
13880:             if ($defaultchecked{$item} eq 'on') {
13881:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
13882:                     ($env{'form.'.$item} eq '0')) {
13883:                     $changes{$item} = 1;
13884:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
13885:                     $changes{$item} = 1;
13886:                 }
13887:             } elsif ($defaultchecked{$item} eq 'off') {
13888:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
13889:                     ($env{'form.'.$item} eq '1')) {
13890:                     $changes{$item} = 1;
13891:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
13892:                     $changes{$item} = 1;
13893:                 }
13894:             }
13895:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
13896:         }
13897:         foreach my $item (@numbers) {
13898:             my ($currdef,$newdef);
13899:             $newdef = $env{'form.'.$item};
13900:             if ($item eq 'anonsurvey_threshold') {
13901:                 $currdef = $domconfig{'coursedefaults'}{$item};
13902:                 $newdef =~ s/\D//g;
13903:                 if ($newdef eq '' || $newdef < 1) {
13904:                     $newdef = 1;
13905:                 }
13906:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
13907:             } else {
13908:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
13909:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
13910:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
13911:                 }
13912:                 $newdef =~ s/[^\w.\-]//g;
13913:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
13914:             }
13915:             if ($currdef ne $newdef) {
13916:                 if ($item eq 'anonsurvey_threshold') {
13917:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
13918:                         $changes{$item} = 1;
13919:                     }
13920:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
13921:                     my $setting = $1;
13922:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
13923:                         $changes{$setting} = 1;
13924:                     }
13925:                 }
13926:             }
13927:         }
13928:         my $texengine;
13929:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
13930:             $texengine = $env{'form.texengine'};
13931:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
13932:             if ($currdef eq '') {
13933:                 unless ($texengine eq $Apache::lonnet::deftex) {
13934:                     $changes{'texengine'} = 1;
13935:                 }
13936:             } elsif ($currdef ne $texengine) {
13937:                 $changes{'texengine'} = 1;
13938:             }
13939:         }
13940:         if ($texengine ne '') {
13941:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
13942:         }
13943:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
13944:         my @currclonecode;
13945:         if (ref($currclone) eq 'HASH') {
13946:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
13947:                 @currclonecode = @{$currclone->{'instcode'}};
13948:             }
13949:         }
13950:         my $newclone;
13951:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
13952:             $newclone = $env{'form.canclone'};
13953:         }
13954:         if ($newclone eq 'instcode') {
13955:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
13956:             my (%codedefaults,@code_order,@clonecode);
13957:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
13958:                                                     \@code_order);
13959:             foreach my $item (@code_order) {
13960:                 if (grep(/^\Q$item\E$/,@newcodes)) {
13961:                     push(@clonecode,$item);
13962:                 }
13963:             }
13964:             if (@clonecode) {
13965:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
13966:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
13967:                 if (@diffs) {
13968:                     $changes{'canclone'} = 1;
13969:                 }
13970:             } else {
13971:                 $newclone eq '';
13972:             }
13973:         } elsif ($newclone ne '') {
13974:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
13975:         }
13976:         if ($newclone ne $currclone) {
13977:             $changes{'canclone'} = 1;
13978:         }
13979:         my %credits;
13980:         foreach my $type (@types) {
13981:             unless ($type eq 'community') {
13982:                 $credits{$type} = $env{'form.'.$type.'_credits'};
13983:                 $credits{$type} =~ s/[^\d.]+//g;
13984:             }
13985:         }
13986:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
13987:             ($env{'form.coursecredits'} eq '1')) {
13988:             $changes{'coursecredits'} = 1;
13989:             foreach my $type (keys(%credits)) {
13990:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
13991:             }
13992:         } else {
13993:             if ($env{'form.coursecredits'} eq '1') {
13994:                 foreach my $type (@types) {
13995:                     unless ($type eq 'community') {
13996:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
13997:                             $changes{'coursecredits'} = 1;
13998:                         }
13999:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
14000:                     }
14001:                 }
14002:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
14003:                 foreach my $type (@types) {
14004:                     unless ($type eq 'community') {
14005:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
14006:                             $changes{'coursecredits'} = 1;
14007:                             last;
14008:                         }
14009:                     }
14010:                 }
14011:             }
14012:         }
14013:         if ($env{'form.postsubmit'} eq '1') {
14014:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
14015:             my %currtimeout;
14016:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
14017:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
14018:                     $changes{'postsubmit'} = 1;
14019:                 }
14020:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
14021:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
14022:                 }
14023:             } else {
14024:                 $changes{'postsubmit'} = 1;
14025:             }
14026:             foreach my $type (@types) {
14027:                 my $timeout = $env{'form.'.$type.'_timeout'};
14028:                 $timeout =~ s/\D//g;
14029:                 if ($timeout == $staticdefaults{'postsubmit'}) {
14030:                     $timeout = '';
14031:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
14032:                     $timeout = '0';
14033:                 }
14034:                 unless ($timeout eq '') {
14035:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
14036:                 }
14037:                 if (exists($currtimeout{$type})) {
14038:                     if ($timeout ne $currtimeout{$type}) {
14039:                         $changes{'postsubmit'} = 1;
14040:                     }
14041:                 } elsif ($timeout ne '') {
14042:                     $changes{'postsubmit'} = 1;
14043:                 }
14044:             }
14045:         } else {
14046:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
14047:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
14048:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
14049:                     $changes{'postsubmit'} = 1;
14050:                 }
14051:             } else {
14052:                 $changes{'postsubmit'} = 1;
14053:             }
14054:         }
14055:     }
14056:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
14057:                                              $dom);
14058:     if ($putresult eq 'ok') {
14059:         if (keys(%changes) > 0) {
14060:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14061:             if (($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
14062:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
14063:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'})) {
14064:                 foreach my $item ('uselcmath','usejsme','texengine') {
14065:                     if ($changes{$item}) {
14066:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
14067:                     }
14068:                 }
14069:                 if ($changes{'coursecredits'}) {
14070:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
14071:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
14072:                             $domdefaults{$type.'credits'} =
14073:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
14074:                         }
14075:                     }
14076:                 }
14077:                 if ($changes{'postsubmit'}) {
14078:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
14079:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
14080:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
14081:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
14082:                                 $domdefaults{$type.'postsubtimeout'} =
14083:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
14084:                             }
14085:                         }
14086:                     }
14087:                 }
14088:                 if ($changes{'uploadquota'}) {
14089:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
14090:                         foreach my $type (@types) {
14091:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
14092:                         }
14093:                     }
14094:                 }
14095:                 if ($changes{'canclone'}) {
14096:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
14097:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
14098:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
14099:                             if (@clonecodes) {
14100:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
14101:                             }
14102:                         }
14103:                     } else {
14104:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
14105:                     }
14106:                 }
14107:                 my $cachetime = 24*60*60;
14108:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14109:                 if (ref($lastactref) eq 'HASH') {
14110:                     $lastactref->{'domdefaults'} = 1;
14111:                 }
14112:             }
14113:             $resulttext = &mt('Changes made:').'<ul>';
14114:             foreach my $item (sort(keys(%changes))) {
14115:                 if ($item eq 'uselcmath') {
14116:                     if ($env{'form.'.$item} eq '1') {
14117:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
14118:                     } else {
14119:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
14120:                     }
14121:                 } elsif ($item eq 'usejsme') {
14122:                     if ($env{'form.'.$item} eq '1') {
14123:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
14124:                     } else {
14125:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
14126:                     }
14127:                 } elsif ($item eq 'texengine') {
14128:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
14129:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
14130:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
14131:                     }
14132:                 } elsif ($item eq 'anonsurvey_threshold') {
14133:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
14134:                 } elsif ($item eq 'uploadquota') {
14135:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
14136:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
14137:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
14138:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
14139:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
14140: 
14141:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
14142:                                        '</ul>'.
14143:                                        '</li>';
14144:                     } else {
14145:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
14146:                     }
14147:                 } elsif ($item eq 'mysqltables') {
14148:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
14149:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
14150:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
14151:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
14152:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
14153:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
14154:                                        '</ul>'.
14155:                                        '</li>';
14156:                     } else {
14157:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
14158:                     }
14159:                 } elsif ($item eq 'postsubmit') {
14160:                     if ($domdefaults{'postsubmit'} eq 'off') {
14161:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
14162:                     } else {
14163:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
14164:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
14165:                             $resulttext .= &mt('durations:').'<ul>';
14166:                             foreach my $type (@types) {
14167:                                 $resulttext .= '<li>';
14168:                                 my $timeout;
14169:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
14170:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
14171:                                 }
14172:                                 my $display;
14173:                                 if ($timeout eq '0') {
14174:                                     $display = &mt('unlimited');
14175:                                 } elsif ($timeout eq '') {
14176:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
14177:                                 } else {
14178:                                     $display = &mt('[quant,_1,second]',$timeout);
14179:                                 }
14180:                                 if ($type eq 'community') {
14181:                                     $resulttext .= &mt('Communities');
14182:                                 } elsif ($type eq 'official') {
14183:                                     $resulttext .= &mt('Official courses');
14184:                                 } elsif ($type eq 'unofficial') {
14185:                                     $resulttext .= &mt('Unofficial courses');
14186:                                 } elsif ($type eq 'textbook') {
14187:                                     $resulttext .= &mt('Textbook courses');
14188:                                 }
14189:                                 $resulttext .= ' -- '.$display.'</li>';
14190:                             }
14191:                             $resulttext .= '</ul>';
14192:                         }
14193:                         $resulttext .= '</li>';
14194:                     }
14195:                 } elsif ($item eq 'coursecredits') {
14196:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
14197:                         if (($domdefaults{'officialcredits'} eq '') &&
14198:                             ($domdefaults{'unofficialcredits'} eq '') &&
14199:                             ($domdefaults{'textbookcredits'} eq '')) {
14200:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
14201:                         } else {
14202:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
14203:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
14204:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
14205:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
14206:                                            '</ul>'.
14207:                                            '</li>';
14208:                         }
14209:                     } else {
14210:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
14211:                     }
14212:                 } elsif ($item eq 'canclone') {
14213:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
14214:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
14215:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
14216:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
14217:                         }
14218:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
14219:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
14220:                     } else {
14221:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
14222:                     }
14223:                 }
14224:             }
14225:             $resulttext .= '</ul>';
14226:         } else {
14227:             $resulttext = &mt('No changes made to course defaults');
14228:         }
14229:     } else {
14230:         $resulttext = '<span class="LC_error">'.
14231:             &mt('An error occurred: [_1]',$putresult).'</span>';
14232:     }
14233:     return $resulttext;
14234: }
14235: 
14236: sub modify_selfenrollment {
14237:     my ($dom,$lastactref,%domconfig) = @_;
14238:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
14239:     my @types = ('official','unofficial','community','textbook');
14240:     my %titles = &tool_titles();
14241:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
14242:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
14243:     $ordered{'default'} = ['types','registered','approval','limit'];
14244: 
14245:     my (%roles,%shown,%toplevel);
14246:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
14247: 
14248:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
14249:         if ($domconfig{'selfenrollment'} eq '') {
14250:             $domconfig{'selfenrollment'} = {};
14251:         }
14252:     }
14253:     %toplevel = (
14254:                   admin      => 'Configuration Rights',
14255:                   default    => 'Default settings',
14256:                   validation => 'Validation of self-enrollment requests',
14257:                 );
14258:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
14259: 
14260:     if (ref($ordered{'admin'}) eq 'ARRAY') {
14261:         foreach my $item (@{$ordered{'admin'}}) {
14262:             foreach my $type (@types) {
14263:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
14264:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
14265:                 } else {
14266:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
14267:                 }
14268:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
14269:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
14270:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
14271:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
14272:                             push(@{$changes{'admin'}{$type}},$item);
14273:                         }
14274:                     } else {
14275:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
14276:                             push(@{$changes{'admin'}{$type}},$item);
14277:                         }
14278:                     }
14279:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
14280:                     push(@{$changes{'admin'}{$type}},$item);
14281:                 }
14282:             }
14283:         }
14284:     }
14285: 
14286:     foreach my $item (@{$ordered{'default'}}) {
14287:         foreach my $type (@types) {
14288:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
14289:             if ($item eq 'types') {
14290:                 unless (($value eq 'all') || ($value eq 'dom')) {
14291:                     $value = '';
14292:                 }
14293:             } elsif ($item eq 'registered') {
14294:                 unless ($value eq '1') {
14295:                     $value = 0;
14296:                 }
14297:             } elsif ($item eq 'approval') {
14298:                 unless ($value =~ /^[012]$/) {
14299:                     $value = 0;
14300:                 }
14301:             } else {
14302:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
14303:                     $value = 'none';
14304:                 }
14305:             }
14306:             $selfenrollhash{'default'}{$type}{$item} = $value;
14307:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
14308:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
14309:                     if ($selfenrollhash{'default'}{$type}{$item} ne
14310:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
14311:                          push(@{$changes{'default'}{$type}},$item);
14312:                     }
14313:                 } else {
14314:                     push(@{$changes{'default'}{$type}},$item);
14315:                 }
14316:             } else {
14317:                 push(@{$changes{'default'}{$type}},$item);
14318:             }
14319:             if ($item eq 'limit') {
14320:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
14321:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
14322:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
14323:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
14324:                     }
14325:                 } else {
14326:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
14327:                 }
14328:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
14329:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
14330:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
14331:                          push(@{$changes{'default'}{$type}},'cap');
14332:                     }
14333:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
14334:                     push(@{$changes{'default'}{$type}},'cap');
14335:                 }
14336:             }
14337:         }
14338:     }
14339: 
14340:     foreach my $item (@{$itemsref}) {
14341:         if ($item eq 'fields') {
14342:             my @changed;
14343:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
14344:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
14345:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
14346:             }
14347:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
14348:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
14349:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
14350:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
14351:                 } else {
14352:                     @changed = @{$selfenrollhash{'validation'}{$item}};
14353:                 }
14354:             } else {
14355:                 @changed = @{$selfenrollhash{'validation'}{$item}};
14356:             }
14357:             if (@changed) {
14358:                 if ($selfenrollhash{'validation'}{$item}) { 
14359:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
14360:                 } else {
14361:                     $changes{'validation'}{$item} = &mt('None');
14362:                 }
14363:             }
14364:         } else {
14365:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
14366:             if ($item eq 'markup') {
14367:                if ($env{'form.selfenroll_validation_'.$item}) {
14368:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
14369:                }
14370:             }
14371:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
14372:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
14373:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
14374:                 }
14375:             }
14376:         }
14377:     }
14378: 
14379:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
14380:                                              $dom);
14381:     if ($putresult eq 'ok') {
14382:         if (keys(%changes) > 0) {
14383:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14384:             $resulttext = &mt('Changes made:').'<ul>';
14385:             foreach my $key ('admin','default','validation') {
14386:                 if (ref($changes{$key}) eq 'HASH') {
14387:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
14388:                     if ($key eq 'validation') {
14389:                         foreach my $item (@{$itemsref}) {
14390:                             if (exists($changes{$key}{$item})) {
14391:                                 if ($item eq 'markup') {
14392:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
14393:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
14394:                                 } else {  
14395:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
14396:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
14397:                                 }
14398:                             }
14399:                         }
14400:                     } else {
14401:                         foreach my $type (@types) {
14402:                             if ($type eq 'community') {
14403:                                 $roles{'1'} = &mt('Community personnel');
14404:                             } else {
14405:                                 $roles{'1'} = &mt('Course personnel');
14406:                             }
14407:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
14408:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
14409:                                     if ($key eq 'admin') {
14410:                                         my @mgrdc = ();
14411:                                         if (ref($ordered{$key}) eq 'ARRAY') {
14412:                                             foreach my $item (@{$ordered{'admin'}}) {
14413:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
14414:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
14415:                                                         push(@mgrdc,$item);
14416:                                                     }
14417:                                                 }
14418:                                             }
14419:                                             if (@mgrdc) {
14420:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
14421:                                             } else {
14422:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
14423:                                             }
14424:                                         }
14425:                                     } else {
14426:                                         if (ref($ordered{$key}) eq 'ARRAY') {
14427:                                             foreach my $item (@{$ordered{$key}}) {
14428:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
14429:                                                     $domdefaults{$type.'selfenroll'.$item} =
14430:                                                         $selfenrollhash{$key}{$type}{$item};
14431:                                                 }
14432:                                             }
14433:                                         }
14434:                                     }
14435:                                 }
14436:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
14437:                                 foreach my $item (@{$ordered{$key}}) {
14438:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
14439:                                         $resulttext .= '<li>';
14440:                                         if ($key eq 'admin') {
14441:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
14442:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
14443:                                         } else {
14444:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
14445:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
14446:                                         }
14447:                                         $resulttext .= '</li>';
14448:                                     }
14449:                                 }
14450:                                 $resulttext .= '</ul></li>';
14451:                             }
14452:                         }
14453:                         $resulttext .= '</ul></li>'; 
14454:                     }
14455:                 }
14456:             }
14457:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
14458:                 my $cachetime = 24*60*60;
14459:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14460:                 if (ref($lastactref) eq 'HASH') {
14461:                     $lastactref->{'domdefaults'} = 1;
14462:                 }
14463:             }
14464:             $resulttext .= '</ul>';
14465:         } else {
14466:             $resulttext = &mt('No changes made to self-enrollment settings');
14467:         }
14468:     } else {
14469:         $resulttext = '<span class="LC_error">'.
14470:             &mt('An error occurred: [_1]',$putresult).'</span>';
14471:     }
14472:     return $resulttext;
14473: }
14474: 
14475: sub modify_usersessions {
14476:     my ($dom,$lastactref,%domconfig) = @_;
14477:     my @hostingtypes = ('version','excludedomain','includedomain');
14478:     my @offloadtypes = ('primary','default');
14479:     my %types = (
14480:                   remote => \@hostingtypes,
14481:                   hosted => \@hostingtypes,
14482:                   spares => \@offloadtypes,
14483:                 );
14484:     my @prefixes = ('remote','hosted','spares');
14485:     my @lcversions = &Apache::lonnet::all_loncaparevs();
14486:     my (%by_ip,%by_location,@intdoms);
14487:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location);
14488:     my @locations = sort(keys(%by_location));
14489:     my (%defaultshash,%changes);
14490:     foreach my $prefix (@prefixes) {
14491:         $defaultshash{'usersessions'}{$prefix} = {};
14492:     }
14493:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14494:     my $resulttext;
14495:     my %iphost = &Apache::lonnet::get_iphost();
14496:     foreach my $prefix (@prefixes) {
14497:         next if ($prefix eq 'spares');
14498:         foreach my $type (@{$types{$prefix}}) {
14499:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
14500:             if ($type eq 'version') {
14501:                 my $value = $env{'form.'.$prefix.'_'.$type};
14502:                 my $okvalue;
14503:                 if ($value ne '') {
14504:                     if (grep(/^\Q$value\E$/,@lcversions)) {
14505:                         $okvalue = $value;
14506:                     }
14507:                 }
14508:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
14509:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
14510:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
14511:                             if ($inuse == 0) {
14512:                                 $changes{$prefix}{$type} = 1;
14513:                             } else {
14514:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
14515:                                     $changes{$prefix}{$type} = 1;
14516:                                 }
14517:                                 if ($okvalue ne '') {
14518:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
14519:                                 } 
14520:                             }
14521:                         } else {
14522:                             if (($inuse == 1) && ($okvalue ne '')) {
14523:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
14524:                                 $changes{$prefix}{$type} = 1;
14525:                             }
14526:                         }
14527:                     } else {
14528:                         if (($inuse == 1) && ($okvalue ne '')) {
14529:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
14530:                             $changes{$prefix}{$type} = 1;
14531:                         }
14532:                     }
14533:                 } else {
14534:                     if (($inuse == 1) && ($okvalue ne '')) {
14535:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
14536:                         $changes{$prefix}{$type} = 1;
14537:                     }
14538:                 }
14539:             } else {
14540:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
14541:                 my @okvals;
14542:                 foreach my $val (@vals) {
14543:                     if ($val =~ /:/) {
14544:                         my @items = split(/:/,$val);
14545:                         foreach my $item (@items) {
14546:                             if (ref($by_location{$item}) eq 'ARRAY') {
14547:                                 push(@okvals,$item);
14548:                             }
14549:                         }
14550:                     } else {
14551:                         if (ref($by_location{$val}) eq 'ARRAY') {
14552:                             push(@okvals,$val);
14553:                         }
14554:                     }
14555:                 }
14556:                 @okvals = sort(@okvals);
14557:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
14558:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
14559:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
14560:                             if ($inuse == 0) {
14561:                                 $changes{$prefix}{$type} = 1; 
14562:                             } else {
14563:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
14564:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
14565:                                 if (@changed > 0) {
14566:                                     $changes{$prefix}{$type} = 1;
14567:                                 }
14568:                             }
14569:                         } else {
14570:                             if ($inuse == 1) {
14571:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
14572:                                 $changes{$prefix}{$type} = 1;
14573:                             }
14574:                         } 
14575:                     } else {
14576:                         if ($inuse == 1) {
14577:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
14578:                             $changes{$prefix}{$type} = 1;
14579:                         }
14580:                     }
14581:                 } else {
14582:                     if ($inuse == 1) {
14583:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
14584:                         $changes{$prefix}{$type} = 1;
14585:                     }
14586:                 }
14587:             }
14588:         }
14589:     }
14590: 
14591:     my @alldoms = &Apache::lonnet::all_domains();
14592:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
14593:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
14594:     my $savespares;
14595: 
14596:     foreach my $lonhost (sort(keys(%servers))) {
14597:         my $serverhomeID =
14598:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
14599:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
14600:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
14601:         my %spareschg;
14602:         foreach my $type (@{$types{'spares'}}) {
14603:             my @okspares;
14604:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
14605:             foreach my $server (@checked) {
14606:                 if (&Apache::lonnet::hostname($server) ne '') {
14607:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
14608:                         unless (grep(/^\Q$server\E$/,@okspares)) {
14609:                             push(@okspares,$server);
14610:                         }
14611:                     }
14612:                 }
14613:             }
14614:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
14615:             my $newspare;
14616:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
14617:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
14618:                     $newspare = $new;
14619:                 }
14620:             }
14621:             my @spares;
14622:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
14623:                 @spares = sort(@okspares,$newspare);
14624:             } else {
14625:                 @spares = sort(@okspares);
14626:             }
14627:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
14628:             if (ref($spareid{$lonhost}) eq 'HASH') {
14629:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
14630:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
14631:                     if (@diffs > 0) {
14632:                         $spareschg{$type} = 1;
14633:                     }
14634:                 }
14635:             }
14636:         }
14637:         if (keys(%spareschg) > 0) {
14638:             $changes{'spares'}{$lonhost} = \%spareschg;
14639:         }
14640:     }
14641:     $defaultshash{'usersessions'}{'offloadnow'} = {};
14642:     $defaultshash{'usersessions'}{'offloadoth'} = {};
14643:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
14644:     my @okoffload;
14645:     if (@offloadnow) {
14646:         foreach my $server (@offloadnow) {
14647:             if (&Apache::lonnet::hostname($server) ne '') {
14648:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
14649:                     push(@okoffload,$server);
14650:                 }
14651:             }
14652:         }
14653:         if (@okoffload) {
14654:             foreach my $lonhost (@okoffload) {
14655:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
14656:             }
14657:         }
14658:     }
14659:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
14660:     my @okoffloadoth;
14661:     if (@offloadoth) {
14662:         foreach my $server (@offloadoth) {
14663:             if (&Apache::lonnet::hostname($server) ne '') {
14664:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
14665:                     push(@okoffloadoth,$server);
14666:                 }
14667:             }
14668:         }
14669:         if (@okoffloadoth) {
14670:             foreach my $lonhost (@okoffloadoth) {
14671:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
14672:             }
14673:         }
14674:     }
14675:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
14676:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
14677:             if (ref($changes{'spares'}) eq 'HASH') {
14678:                 if (keys(%{$changes{'spares'}}) > 0) {
14679:                     $savespares = 1;
14680:                 }
14681:             }
14682:         } else {
14683:             $savespares = 1;
14684:         }
14685:         foreach my $offload ('offloadnow','offloadoth') {
14686:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
14687:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
14688:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
14689:                         $changes{$offload} = 1;
14690:                         last;
14691:                     }
14692:                 }
14693:                 unless ($changes{$offload}) {
14694:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
14695:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
14696:                             $changes{$offload} = 1;
14697:                             last;
14698:                         }
14699:                     }
14700:                 }
14701:             } else {
14702:                 if (($offload eq 'offloadnow') && (@okoffload)) {
14703:                      $changes{'offloadnow'} = 1;
14704:                 }
14705:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
14706:                     $changes{'offloadoth'} = 1;
14707:                 }
14708:             }
14709:         }
14710:     } else {
14711:         if (@okoffload) {
14712:             $changes{'offloadnow'} = 1;
14713:         }
14714:         if (@okoffloadoth) {
14715:             $changes{'offloadoth'} = 1;
14716:         }
14717:     }
14718:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
14719:     if ((keys(%changes) > 0) || ($savespares)) {
14720:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
14721:                                                  $dom);
14722:         if ($putresult eq 'ok') {
14723:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
14724:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
14725:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
14726:                 }
14727:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
14728:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
14729:                 }
14730:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
14731:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
14732:                 }
14733:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
14734:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
14735:                 }
14736:             }
14737:             my $cachetime = 24*60*60;
14738:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14739:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
14740:             if (ref($lastactref) eq 'HASH') {
14741:                 $lastactref->{'domdefaults'} = 1;
14742:                 $lastactref->{'usersessions'} = 1;
14743:             }
14744:             if (keys(%changes) > 0) {
14745:                 my %lt = &usersession_titles();
14746:                 $resulttext = &mt('Changes made:').'<ul>';
14747:                 foreach my $prefix (@prefixes) {
14748:                     if (ref($changes{$prefix}) eq 'HASH') {
14749:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
14750:                         if ($prefix eq 'spares') {
14751:                             if (ref($changes{$prefix}) eq 'HASH') {
14752:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
14753:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
14754:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
14755:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
14756:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
14757:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
14758:                                         foreach my $type (@{$types{$prefix}}) {
14759:                                             if ($changes{$prefix}{$lonhost}{$type}) {
14760:                                                 my $offloadto = &mt('None');
14761:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
14762:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
14763:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
14764:                                                     }
14765:                                                 }
14766:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
14767:                                             }
14768:                                         }
14769:                                     }
14770:                                     $resulttext .= '</li>';
14771:                                 }
14772:                             }
14773:                         } else {
14774:                             foreach my $type (@{$types{$prefix}}) {
14775:                                 if (defined($changes{$prefix}{$type})) {
14776:                                     my $newvalue;
14777:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
14778:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
14779:                                             if ($type eq 'version') {
14780:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
14781:                                             } elsif (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
14782:                                                 if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
14783:                                                     $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
14784:                                                 }
14785:                                             }
14786:                                         }
14787:                                     }
14788:                                     if ($newvalue eq '') {
14789:                                         if ($type eq 'version') {
14790:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
14791:                                         } else {
14792:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
14793:                                         }
14794:                                     } else {
14795:                                         if ($type eq 'version') {
14796:                                             $newvalue .= ' '.&mt('(or later)'); 
14797:                                         }
14798:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
14799:                                     }
14800:                                 }
14801:                             }
14802:                         }
14803:                         $resulttext .= '</ul>';
14804:                     }
14805:                 }
14806:                 if ($changes{'offloadnow'}) {
14807:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
14808:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
14809:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
14810:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
14811:                                 $resulttext .= '<li>'.$lonhost.'</li>';
14812:                             }
14813:                             $resulttext .= '</ul>';
14814:                         } else {
14815:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
14816:                         }
14817:                     } else {
14818:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
14819:                     }
14820:                 }
14821:                 if ($changes{'offloadoth'}) {
14822:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
14823:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
14824:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
14825:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
14826:                                 $resulttext .= '<li>'.$lonhost.'</li>';
14827:                             }
14828:                             $resulttext .= '</ul>';
14829:                         } else {
14830:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
14831:                         }
14832:                     } else {
14833:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
14834:                     }
14835:                 }
14836:                 $resulttext .= '</ul>';
14837:             } else {
14838:                 $resulttext = $nochgmsg;
14839:             }
14840:         } else {
14841:             $resulttext = '<span class="LC_error">'.
14842:                           &mt('An error occurred: [_1]',$putresult).'</span>';
14843:         }
14844:     } else {
14845:         $resulttext = $nochgmsg;
14846:     }
14847:     return $resulttext;
14848: }
14849: 
14850: sub modify_loadbalancing {
14851:     my ($dom,%domconfig) = @_;
14852:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
14853:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
14854:     my ($othertitle,$usertypes,$types) =
14855:         &Apache::loncommon::sorted_inst_types($dom);
14856:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
14857:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
14858:     my @sparestypes = ('primary','default');
14859:     my %typetitles = &sparestype_titles();
14860:     my $resulttext;
14861:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
14862:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
14863:         %existing = %{$domconfig{'loadbalancing'}};
14864:     }
14865:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
14866:                               \%currtargets,\%currrules,\%currcookies);
14867:     my ($saveloadbalancing,%defaultshash,%changes);
14868:     my ($alltypes,$othertypes,$titles) =
14869:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
14870:     my %ruletitles = &offloadtype_text();
14871:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
14872:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
14873:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
14874:         if ($balancer eq '') {
14875:             next;
14876:         }
14877:         if (!exists($servers{$balancer})) {
14878:             if (exists($currbalancer{$balancer})) {
14879:                 push(@{$changes{'delete'}},$balancer);
14880:             }
14881:             next;
14882:         }
14883:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
14884:             push(@{$changes{'delete'}},$balancer);
14885:             next;
14886:         }
14887:         if (!exists($currbalancer{$balancer})) {
14888:             push(@{$changes{'add'}},$balancer);
14889:         }
14890:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
14891:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
14892:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
14893:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
14894:             $saveloadbalancing = 1;
14895:         }
14896:         foreach my $sparetype (@sparestypes) {
14897:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
14898:             my @offloadto;
14899:             foreach my $target (@targets) {
14900:                 if (($servers{$target}) && ($target ne $balancer)) {
14901:                     if ($sparetype eq 'default') {
14902:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
14903:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
14904:                         }
14905:                     }
14906:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
14907:                         push(@offloadto,$target);
14908:                     }
14909:                 }
14910:             }
14911:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
14912:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
14913:                     push(@offloadto,$balancer);
14914:                 }
14915:             }
14916:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
14917:         }
14918:         if ($env{'form.loadbalancing_cookie_'.$i}) {
14919:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
14920:             if (exists($currbalancer{$balancer})) {
14921:                 unless ($currcookies{$balancer}) {
14922:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
14923:                 }
14924:             }
14925:         } elsif (exists($currbalancer{$balancer})) {
14926:             if ($currcookies{$balancer}) {
14927:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
14928:             }
14929:         }
14930:         if (ref($currtargets{$balancer}) eq 'HASH') {
14931:             foreach my $sparetype (@sparestypes) {
14932:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
14933:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
14934:                     if (@targetdiffs > 0) {
14935:                         $changes{'curr'}{$balancer}{'targets'} = 1;
14936:                     }
14937:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
14938:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
14939:                         $changes{'curr'}{$balancer}{'targets'} = 1;
14940:                     }
14941:                 }
14942:             }
14943:         } else {
14944:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
14945:                 foreach my $sparetype (@sparestypes) {
14946:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
14947:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
14948:                             $changes{'curr'}{$balancer}{'targets'} = 1;
14949:                         }
14950:                     }
14951:                 }
14952:             }
14953:         }
14954:         my $ishomedom;
14955:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
14956:             $ishomedom = 1;
14957:         }
14958:         if (ref($alltypes) eq 'ARRAY') {
14959:             foreach my $type (@{$alltypes}) {
14960:                 my $rule;
14961:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
14962:                          (!$ishomedom)) {
14963:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
14964:                 }
14965:                 if ($rule eq 'specific') {
14966:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
14967:                     if (exists($servers{$specifiedhost})) {
14968:                         $rule = $specifiedhost;
14969:                     }
14970:                 }
14971:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
14972:                 if (ref($currrules{$balancer}) eq 'HASH') {
14973:                     if ($rule ne $currrules{$balancer}{$type}) {
14974:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
14975:                     }
14976:                 } elsif ($rule ne '') {
14977:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
14978:                 }
14979:             }
14980:         }
14981:     }
14982:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
14983:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
14984:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
14985:             $defaultshash{'loadbalancing'} = {};
14986:         }
14987:         my $putresult = &Apache::lonnet::put_dom('configuration',
14988:                                                  \%defaultshash,$dom);
14989:         if ($putresult eq 'ok') {
14990:             if (keys(%changes) > 0) {
14991:                 my %toupdate;
14992:                 if (ref($changes{'delete'}) eq 'ARRAY') {
14993:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
14994:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
14995:                         $toupdate{$balancer} = 1;
14996:                     }
14997:                 }
14998:                 if (ref($changes{'add'}) eq 'ARRAY') {
14999:                     foreach my $balancer (sort(@{$changes{'add'}})) {
15000:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
15001:                         $toupdate{$balancer} = 1;
15002:                     }
15003:                 }
15004:                 if (ref($changes{'curr'}) eq 'HASH') {
15005:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
15006:                         $toupdate{$balancer} = 1;
15007:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
15008:                             if ($changes{'curr'}{$balancer}{'targets'}) {
15009:                                 my %offloadstr;
15010:                                 foreach my $sparetype (@sparestypes) {
15011:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
15012:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
15013:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
15014:                                         }
15015:                                     }
15016:                                 }
15017:                                 if (keys(%offloadstr) == 0) {
15018:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
15019:                                 } else {
15020:                                     my $showoffload;
15021:                                     foreach my $sparetype (@sparestypes) {
15022:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
15023:                                         if (defined($offloadstr{$sparetype})) {
15024:                                             $showoffload .= $offloadstr{$sparetype};
15025:                                         } else {
15026:                                             $showoffload .= &mt('None');
15027:                                         }
15028:                                         $showoffload .= ('&nbsp;'x3);
15029:                                     }
15030:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
15031:                                 }
15032:                             }
15033:                         }
15034:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
15035:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
15036:                                 foreach my $type (@{$alltypes}) {
15037:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
15038:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
15039:                                         my $balancetext;
15040:                                         if ($rule eq '') {
15041:                                             $balancetext =  $ruletitles{'default'};
15042:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
15043:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
15044:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
15045:                                                 foreach my $sparetype (@sparestypes) {
15046:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
15047:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
15048:                                                     }
15049:                                                 }
15050:                                                 foreach my $item (@{$alltypes}) {
15051:                                                     next if ($item =~  /^_LC_ipchange/);
15052:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
15053:                                                     if ($hasrule eq 'homeserver') {
15054:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
15055:                                                     } else {
15056:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
15057:                                                             if ($servers{$hasrule}) {
15058:                                                                 $toupdate{$hasrule} = 1;
15059:                                                             }
15060:                                                         }
15061:                                                     }
15062:                                                 }
15063:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
15064:                                                     $balancetext =  $ruletitles{$rule};
15065:                                                 } else {
15066:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
15067:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
15068:                                                     if ($receiver) {
15069:                                                         $toupdate{$receiver};
15070:                                                     }
15071:                                                 }
15072:                                             } else {
15073:                                                 $balancetext =  $ruletitles{$rule};
15074:                                             }
15075:                                         } else {
15076:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
15077:                                         }
15078:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
15079:                                     }
15080:                                 }
15081:                             }
15082:                         }
15083:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
15084:                             $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
15085:                                                       $balancer).'</li>';
15086:                         }
15087:                         if (keys(%toupdate)) {
15088:                             my %thismachine;
15089:                             my $updatedhere;
15090:                             my $cachetime = 60*60*24;
15091:                             map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
15092:                             foreach my $lonhost (keys(%toupdate)) {
15093:                                 if ($thismachine{$lonhost}) {
15094:                                     unless ($updatedhere) {
15095:                                         &Apache::lonnet::do_cache_new('loadbalancing',$dom,
15096:                                                                       $defaultshash{'loadbalancing'},
15097:                                                                       $cachetime);
15098:                                         $updatedhere = 1;
15099:                                     }
15100:                                 } else {
15101:                                     my $cachekey = &escape('loadbalancing').':'.&escape($dom);
15102:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
15103:                                 }
15104:                             }
15105:                         }
15106:                     }
15107:                 }
15108:                 if ($resulttext ne '') {
15109:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
15110:                 } else {
15111:                     $resulttext = $nochgmsg;
15112:                 }
15113:             } else {
15114:                 $resulttext = $nochgmsg;
15115:             }
15116:         } else {
15117:             $resulttext = '<span class="LC_error">'.
15118:                           &mt('An error occurred: [_1]',$putresult).'</span>';
15119:         }
15120:     } else {
15121:         $resulttext = $nochgmsg;
15122:     }
15123:     return $resulttext;
15124: }
15125: 
15126: sub recurse_check {
15127:     my ($chkcats,$categories,$depth,$name) = @_;
15128:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
15129:         my $chg = 0;
15130:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
15131:             my $category = $chkcats->[$depth]{$name}[$j];
15132:             my $item;
15133:             if ($category eq '') {
15134:                 $chg ++;
15135:             } else {
15136:                 my $deeper = $depth + 1;
15137:                 $item = &escape($category).':'.&escape($name).':'.$depth;
15138:                 if ($chg) {
15139:                     $categories->{$item} -= $chg;
15140:                 }
15141:                 &recurse_check($chkcats,$categories,$deeper,$category);
15142:                 $deeper --;
15143:             }
15144:         }
15145:     }
15146:     return;
15147: }
15148: 
15149: sub recurse_cat_deletes {
15150:     my ($item,$coursecategories,$deletions) = @_;
15151:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15152:     my $subdepth = $depth + 1;
15153:     if (ref($coursecategories) eq 'HASH') {
15154:         foreach my $subitem (keys(%{$coursecategories})) {
15155:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
15156:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
15157:                 delete($coursecategories->{$subitem});
15158:                 $deletions->{$subitem} = 1;
15159:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
15160:             }
15161:         }
15162:     }
15163:     return;
15164: }
15165: 
15166: sub active_dc_picker {
15167:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
15168:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
15169:     my @domcoord = keys(%domcoords);
15170:     if (keys(%currhash)) {
15171:         foreach my $dc (keys(%currhash)) {
15172:             unless (exists($domcoords{$dc})) {
15173:                 push(@domcoord,$dc);
15174:             }
15175:         }
15176:     }
15177:     @domcoord = sort(@domcoord);
15178:     my $numdcs = scalar(@domcoord);
15179:     my $rows = 0;
15180:     my $table;
15181:     if ($numdcs > 1) {
15182:         $table = '<table>';
15183:         for (my $i=0; $i<@domcoord; $i++) {
15184:             my $rem = $i%($numinrow);
15185:             if ($rem == 0) {
15186:                 if ($i > 0) {
15187:                     $table .= '</tr>';
15188:                 }
15189:                 $table .= '<tr>';
15190:                 $rows ++;
15191:             }
15192:             my $check = '';
15193:             if ($inputtype eq 'radio') {
15194:                 if (keys(%currhash) == 0) {
15195:                     if (!$i) {
15196:                         $check = ' checked="checked"';
15197:                     }
15198:                 } elsif (exists($currhash{$domcoord[$i]})) {
15199:                     $check = ' checked="checked"';
15200:                 }
15201:             } else {
15202:                 if (exists($currhash{$domcoord[$i]})) {
15203:                     $check = ' checked="checked"';
15204:                 }
15205:             }
15206:             if ($i == @domcoord - 1) {
15207:                 my $colsleft = $numinrow - $rem;
15208:                 if ($colsleft > 1) {
15209:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
15210:                 } else {
15211:                     $table .= '<td class="LC_left_item">';
15212:                 }
15213:             } else {
15214:                 $table .= '<td class="LC_left_item">';
15215:             }
15216:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
15217:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
15218:             $table .= '<span class="LC_nobreak"><label>'.
15219:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
15220:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
15221:             if ($user ne $dcname.':'.$dcdom) {
15222:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
15223:             }
15224:             $table .= '</label></span></td>';
15225:         }
15226:         $table .= '</tr></table>';
15227:     } elsif ($numdcs == 1) {
15228:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
15229:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
15230:         if ($inputtype eq 'radio') {
15231:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
15232:             if ($user ne $dcname.':'.$dcdom) {
15233:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
15234:             }
15235:         } else {
15236:             my $check;
15237:             if (exists($currhash{$domcoord[0]})) {
15238:                 $check = ' checked="checked"';
15239:             }
15240:             $table = '<span class="LC_nobreak"><label>'.
15241:                      '<input type="checkbox" name="'.$name.'" '.
15242:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
15243:             if ($user ne $dcname.':'.$dcdom) {
15244:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
15245:             }
15246:             $table .= '</label></span>';
15247:             $rows ++;
15248:         }
15249:     }
15250:     return ($numdcs,$table,$rows);
15251: }
15252: 
15253: sub usersession_titles {
15254:     return &Apache::lonlocal::texthash(
15255:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
15256:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
15257:                spares => 'Servers offloaded to, when busy',
15258:                version => 'LON-CAPA version requirement',
15259:                excludedomain => 'Allow all, but exclude specific domains',
15260:                includedomain => 'Deny all, but include specific domains',
15261:                primary => 'Primary (checked first)',
15262:                default => 'Default',
15263:            );
15264: }
15265: 
15266: sub id_for_thisdom {
15267:     my (%servers) = @_;
15268:     my %altids;
15269:     foreach my $server (keys(%servers)) {
15270:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
15271:         if ($serverhome ne $server) {
15272:             $altids{$serverhome} = $server;
15273:         }
15274:     }
15275:     return %altids;
15276: }
15277: 
15278: sub count_servers {
15279:     my ($currbalancer,%servers) = @_;
15280:     my (@spares,$numspares);
15281:     foreach my $lonhost (sort(keys(%servers))) {
15282:         next if ($currbalancer eq $lonhost);
15283:         push(@spares,$lonhost);
15284:     }
15285:     if ($currbalancer) {
15286:         $numspares = scalar(@spares);
15287:     } else {
15288:         $numspares = scalar(@spares) - 1;
15289:     }
15290:     return ($numspares,@spares);
15291: }
15292: 
15293: sub lonbalance_targets_js {
15294:     my ($dom,$types,$servers,$settings) = @_;
15295:     my $select = &mt('Select');
15296:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
15297:     if (ref($servers) eq 'HASH') {
15298:         $alltargets = join("','",sort(keys(%{$servers})));
15299:         my @homedoms;
15300:         foreach my $server (sort(keys(%{$servers}))) {
15301:             if (&Apache::lonnet::host_domain($server) eq $dom) {
15302:                 push(@homedoms,'1');
15303:             } else {
15304:                 push(@homedoms,'0');
15305:             }
15306:         }
15307:         $allishome = join("','",@homedoms);
15308:     }
15309:     if (ref($types) eq 'ARRAY') {
15310:         if (@{$types} > 0) {
15311:             @alltypes = @{$types};
15312:         }
15313:     }
15314:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
15315:     $allinsttypes = join("','",@alltypes);
15316:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
15317:     if (ref($settings) eq 'HASH') {
15318:         %existing = %{$settings};
15319:     }
15320:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
15321:                               \%currtargets,\%currrules,\%currcookies);
15322:     my $balancers = join("','",sort(keys(%currbalancer)));
15323:     return <<"END";
15324: 
15325: <script type="text/javascript">
15326: // <![CDATA[
15327: 
15328: currBalancers = new Array('$balancers');
15329: 
15330: function toggleTargets(balnum) {
15331:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
15332:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
15333:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
15334:     var prevbalancer = prevhostitem.value;
15335:     var baltotal = document.getElementById('loadbalancing_total').value;
15336:     prevhostitem.value = balancer;
15337:     if (prevbalancer != '') {
15338:         var prevIdx = currBalancers.indexOf(prevbalancer);
15339:         if (prevIdx != -1) {
15340:             currBalancers.splice(prevIdx,1);
15341:         }
15342:     }
15343:     if (balancer == '') {
15344:         hideSpares(balnum);
15345:     } else {
15346:         var currIdx = currBalancers.indexOf(balancer);
15347:         if (currIdx == -1) {
15348:             currBalancers.push(balancer);
15349:         }
15350:         var homedoms = new Array('$allishome');
15351:         var ishomedom = homedoms[lonhostitem.selectedIndex];
15352:         showSpares(balancer,ishomedom,balnum);
15353:     }
15354:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
15355:     return;
15356: }
15357: 
15358: function showSpares(balancer,ishomedom,balnum) {
15359:     var alltargets = new Array('$alltargets');
15360:     var insttypes = new Array('$allinsttypes');
15361:     var offloadtypes = new Array('primary','default');
15362: 
15363:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
15364:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
15365:  
15366:     for (var i=0; i<offloadtypes.length; i++) {
15367:         var count = 0;
15368:         for (var j=0; j<alltargets.length; j++) {
15369:             if (alltargets[j] != balancer) {
15370:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
15371:                 item.value = alltargets[j];
15372:                 item.style.textAlign='left';
15373:                 item.style.textFace='normal';
15374:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
15375:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
15376:                     item.disabled = '';
15377:                 } else {
15378:                     item.disabled = 'disabled';
15379:                     item.checked = false;
15380:                 }
15381:                 count ++;
15382:             }
15383:         }
15384:     }
15385:     for (var k=0; k<insttypes.length; k++) {
15386:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
15387:             if (ishomedom == 1) {
15388:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
15389:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
15390:             } else {
15391:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
15392:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
15393:             }
15394:         } else {
15395:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
15396:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
15397:         }
15398:         if ((insttypes[k] != '_LC_external') && 
15399:             ((insttypes[k] != '_LC_internetdom') ||
15400:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
15401:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
15402:             item.options.length = 0;
15403:             item.options[0] = new Option("","",true,true);
15404:             var idx = 0;
15405:             for (var m=0; m<alltargets.length; m++) {
15406:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
15407:                     idx ++;
15408:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
15409:                 }
15410:             }
15411:         }
15412:     }
15413:     return;
15414: }
15415: 
15416: function hideSpares(balnum) {
15417:     var alltargets = new Array('$alltargets');
15418:     var insttypes = new Array('$allinsttypes');
15419:     var offloadtypes = new Array('primary','default');
15420: 
15421:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
15422:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
15423: 
15424:     var total = alltargets.length - 1;
15425:     for (var i=0; i<offloadtypes; i++) {
15426:         for (var j=0; j<total; j++) {
15427:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
15428:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
15429:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
15430:         }
15431:     }
15432:     for (var k=0; k<insttypes.length; k++) {
15433:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
15434:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
15435:         if (insttypes[k] != '_LC_external') {
15436:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
15437:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
15438:         }
15439:     }
15440:     return;
15441: }
15442: 
15443: function checkOffloads(item,balnum,type) {
15444:     var alltargets = new Array('$alltargets');
15445:     var offloadtypes = new Array('primary','default');
15446:     if (item.checked) {
15447:         var total = alltargets.length - 1;
15448:         var other;
15449:         if (type == offloadtypes[0]) {
15450:             other = offloadtypes[1];
15451:         } else {
15452:             other = offloadtypes[0];
15453:         }
15454:         for (var i=0; i<total; i++) {
15455:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
15456:             if (server == item.value) {
15457:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
15458:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
15459:                 }
15460:             }
15461:         }
15462:     }
15463:     return;
15464: }
15465: 
15466: function singleServerToggle(balnum,type) {
15467:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
15468:     if (offloadtoSelIdx == 0) {
15469:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
15470:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
15471: 
15472:     } else {
15473:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
15474:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
15475:     }
15476:     return;
15477: }
15478: 
15479: function balanceruleChange(formname,balnum,type) {
15480:     if (type == '_LC_external') {
15481:         return;
15482:     }
15483:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
15484:     for (var i=0; i<typesRules.length; i++) {
15485:         if (formname.elements[typesRules[i]].checked) {
15486:             if (formname.elements[typesRules[i]].value != 'specific') {
15487:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
15488:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
15489:             } else {
15490:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
15491:             }
15492:         }
15493:     }
15494:     return;
15495: }
15496: 
15497: function balancerDeleteChange(balnum) {
15498:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
15499:     var baltotal = document.getElementById('loadbalancing_total').value;
15500:     var addtarget;
15501:     var removetarget;
15502:     var action = 'delete';
15503:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
15504:         var lonhost = hostitem.value;
15505:         var currIdx = currBalancers.indexOf(lonhost);
15506:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
15507:             if (currIdx != -1) {
15508:                 currBalancers.splice(currIdx,1);
15509:             }
15510:             addtarget = lonhost;
15511:         } else {
15512:             if (currIdx == -1) {
15513:                 currBalancers.push(lonhost);
15514:             }
15515:             removetarget = lonhost;
15516:             action = 'undelete';
15517:         }
15518:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
15519:     }
15520:     return;
15521: }
15522: 
15523: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
15524:     if (baltotal > 1) {
15525:         var offloadtypes = new Array('primary','default');
15526:         var alltargets = new Array('$alltargets');
15527:         var insttypes = new Array('$allinsttypes');
15528:         for (var i=0; i<baltotal; i++) {
15529:             if (i != balnum) {
15530:                 for (var j=0; j<offloadtypes.length; j++) {
15531:                     var total = alltargets.length - 1;
15532:                     for (var k=0; k<total; k++) {
15533:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
15534:                         var server = serveritem.value;
15535:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
15536:                             if (server == addtarget) {
15537:                                 serveritem.disabled = '';
15538:                             }
15539:                         }
15540:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
15541:                             if (server == removetarget) {
15542:                                 serveritem.disabled = 'disabled';
15543:                                 serveritem.checked = false;
15544:                             }
15545:                         }
15546:                     }
15547:                 }
15548:                 for (var j=0; j<insttypes.length; j++) {
15549:                     if (insttypes[j] != '_LC_external') {
15550:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
15551:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
15552:                             var currSel = singleserver.selectedIndex;
15553:                             var currVal = singleserver.options[currSel].value;
15554:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
15555:                                 var numoptions = singleserver.options.length;
15556:                                 var needsnew = 1;
15557:                                 for (var k=0; k<numoptions; k++) {
15558:                                     if (singleserver.options[k] == addtarget) {
15559:                                         needsnew = 0;
15560:                                         break;
15561:                                     }
15562:                                 }
15563:                                 if (needsnew == 1) {
15564:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
15565:                                 }
15566:                             }
15567:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
15568:                                 singleserver.options.length = 0;
15569:                                 if ((currVal) && (currVal != removetarget)) {
15570:                                     singleserver.options[0] = new Option("","",false,false);
15571:                                 } else {
15572:                                     singleserver.options[0] = new Option("","",true,true);
15573:                                 }
15574:                                 var idx = 0;
15575:                                 for (var m=0; m<alltargets.length; m++) {
15576:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
15577:                                         idx ++;
15578:                                         if (currVal == alltargets[m]) {
15579:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
15580:                                         } else {
15581:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
15582:                                         }
15583:                                     }
15584:                                 }
15585:                             }
15586:                         }
15587:                     }
15588:                 }
15589:             }
15590:         }
15591:     }
15592:     return;
15593: }
15594: 
15595: // ]]>
15596: </script>
15597: 
15598: END
15599: }
15600: 
15601: sub new_spares_js {
15602:     my @sparestypes = ('primary','default');
15603:     my $types = join("','",@sparestypes);
15604:     my $select = &mt('Select');
15605:     return <<"END";
15606: 
15607: <script type="text/javascript">
15608: // <![CDATA[
15609: 
15610: function updateNewSpares(formname,lonhost) {
15611:     var types = new Array('$types');
15612:     var include = new Array();
15613:     var exclude = new Array();
15614:     for (var i=0; i<types.length; i++) {
15615:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
15616:         for (var j=0; j<spareboxes.length; j++) {
15617:             if (formname.elements[spareboxes[j]].checked) {
15618:                 exclude.push(formname.elements[spareboxes[j]].value);
15619:             } else {
15620:                 include.push(formname.elements[spareboxes[j]].value);
15621:             }
15622:         }
15623:     }
15624:     for (var i=0; i<types.length; i++) {
15625:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
15626:         var selIdx = newSpare.selectedIndex;
15627:         var currnew = newSpare.options[selIdx].value;
15628:         var okSpares = new Array();
15629:         for (var j=0; j<newSpare.options.length; j++) {
15630:             var possible = newSpare.options[j].value;
15631:             if (possible != '') {
15632:                 if (exclude.indexOf(possible) == -1) {
15633:                     okSpares.push(possible);
15634:                 } else {
15635:                     if (currnew == possible) {
15636:                         selIdx = 0;
15637:                     }
15638:                 }
15639:             }
15640:         }
15641:         for (var k=0; k<include.length; k++) {
15642:             if (okSpares.indexOf(include[k]) == -1) {
15643:                 okSpares.push(include[k]);
15644:             }
15645:         }
15646:         okSpares.sort();
15647:         newSpare.options.length = 0;
15648:         if (selIdx == 0) {
15649:             newSpare.options[0] = new Option("$select","",true,true);
15650:         } else {
15651:             newSpare.options[0] = new Option("$select","",false,false);
15652:         }
15653:         for (var m=0; m<okSpares.length; m++) {
15654:             var idx = m+1;
15655:             var selThis = 0;
15656:             if (selIdx != 0) {
15657:                 if (okSpares[m] == currnew) {
15658:                     selThis = 1;
15659:                 }
15660:             }
15661:             if (selThis == 1) {
15662:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
15663:             } else {
15664:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
15665:             }
15666:         }
15667:     }
15668:     return;
15669: }
15670: 
15671: function checkNewSpares(lonhost,type) {
15672:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
15673:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
15674:     if (chosen != '') { 
15675:         var othertype;
15676:         var othernewSpare;
15677:         if (type == 'primary') {
15678:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
15679:         }
15680:         if (type == 'default') {
15681:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
15682:         }
15683:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
15684:             othernewSpare.selectedIndex = 0;
15685:         }
15686:     }
15687:     return;
15688: }
15689: 
15690: // ]]>
15691: </script>
15692: 
15693: END
15694: 
15695: }
15696: 
15697: sub common_domprefs_js {
15698:     return <<"END";
15699: 
15700: <script type="text/javascript">
15701: // <![CDATA[
15702: 
15703: function getIndicesByName(formname,item) {
15704:     var group = new Array();
15705:     for (var i=0;i<formname.elements.length;i++) {
15706:         if (formname.elements[i].name == item) {
15707:             group.push(formname.elements[i].id);
15708:         }
15709:     }
15710:     return group;
15711: }
15712: 
15713: // ]]>
15714: </script>
15715: 
15716: END
15717: 
15718: }
15719: 
15720: sub recaptcha_js {
15721:     my %lt = &captcha_phrases();
15722:     return <<"END";
15723: 
15724: <script type="text/javascript">
15725: // <![CDATA[
15726: 
15727: function updateCaptcha(caller,context) {
15728:     var privitem;
15729:     var pubitem;
15730:     var privtext;
15731:     var pubtext;
15732:     var versionitem;
15733:     var versiontext;
15734:     if (document.getElementById(context+'_recaptchapub')) {
15735:         pubitem = document.getElementById(context+'_recaptchapub');
15736:     } else {
15737:         return;
15738:     }
15739:     if (document.getElementById(context+'_recaptchapriv')) {
15740:         privitem = document.getElementById(context+'_recaptchapriv');
15741:     } else {
15742:         return;
15743:     }
15744:     if (document.getElementById(context+'_recaptchapubtxt')) {
15745:         pubtext = document.getElementById(context+'_recaptchapubtxt');
15746:     } else {
15747:         return;
15748:     }
15749:     if (document.getElementById(context+'_recaptchaprivtxt')) {
15750:         privtext = document.getElementById(context+'_recaptchaprivtxt');
15751:     } else {
15752:         return;
15753:     }
15754:     if (document.getElementById(context+'_recaptchaversion')) {
15755:         versionitem = document.getElementById(context+'_recaptchaversion');
15756:     } else {
15757:         return;
15758:     }
15759:     if (document.getElementById(context+'_recaptchavertxt')) {
15760:         versiontext = document.getElementById(context+'_recaptchavertxt');
15761:     } else {
15762:         return;
15763:     }
15764:     if (caller.checked) {
15765:         if (caller.value == 'recaptcha') {
15766:             pubitem.type = 'text';
15767:             privitem.type = 'text';
15768:             pubitem.size = '40';
15769:             privitem.size = '40';
15770:             pubtext.innerHTML = "$lt{'pub'}";
15771:             privtext.innerHTML = "$lt{'priv'}";
15772:             versionitem.type = 'text';
15773:             versionitem.size = '3';
15774:             versiontext.innerHTML = "$lt{'ver'}";
15775:         } else {
15776:             pubitem.type = 'hidden';
15777:             privitem.type = 'hidden';
15778:             versionitem.type = 'hidden';
15779:             pubtext.innerHTML = '';
15780:             privtext.innerHTML = '';
15781:             versiontext.innerHTML = '';
15782:         }
15783:     }
15784:     return;
15785: }
15786: 
15787: // ]]>
15788: </script>
15789: 
15790: END
15791: 
15792: }
15793: 
15794: sub toggle_display_js {
15795:     return <<"END";
15796: 
15797: <script type="text/javascript">
15798: // <![CDATA[
15799: 
15800: function toggleDisplay(domForm,caller) {
15801:     if (document.getElementById(caller)) {
15802:         var divitem = document.getElementById(caller);
15803:         var optionsElement = domForm.coursecredits;
15804:         var checkval = 1;
15805:         var dispval = 'block';
15806:         var selfcreateRegExp = /^cancreate_emailverified/;
15807:         if (caller == 'emailoptions') {
15808:             optionsElement = domForm.cancreate_email; 
15809:         }
15810:         if (caller == 'studentsubmission') {
15811:             optionsElement = domForm.postsubmit;
15812:         }
15813:         if (caller == 'cloneinstcode') {
15814:             optionsElement = domForm.canclone;
15815:             checkval = 'instcode';
15816:         }
15817:         if (selfcreateRegExp.test(caller)) {
15818:             optionsElement = domForm.elements[caller];
15819:             checkval = 'other';
15820:             dispval = 'inline'
15821:         }
15822:         if (optionsElement.length) {
15823:             var currval;
15824:             for (var i=0; i<optionsElement.length; i++) {
15825:                 if (optionsElement[i].checked) {
15826:                    currval = optionsElement[i].value;
15827:                 }
15828:             }
15829:             if (currval == checkval) {
15830:                 divitem.style.display = dispval;
15831:             } else {
15832:                 divitem.style.display = 'none';
15833:             }
15834:         }
15835:     }
15836:     return;
15837: }
15838: 
15839: // ]]>
15840: </script>
15841: 
15842: END
15843: 
15844: }
15845: 
15846: sub captcha_phrases {
15847:     return &Apache::lonlocal::texthash (
15848:                  priv => 'Private key',
15849:                  pub  => 'Public key',
15850:                  original  => 'original (CAPTCHA)',
15851:                  recaptcha => 'successor (ReCAPTCHA)',
15852:                  notused   => 'unused',
15853:                  ver => 'ReCAPTCHA version (1 or 2)',
15854:     );
15855: }
15856: 
15857: sub devalidate_remote_domconfs {
15858:     my ($dom,$cachekeys) = @_;
15859:     return unless (ref($cachekeys) eq 'HASH');
15860:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
15861:     my %thismachine;
15862:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
15863:     my @posscached = ('domainconfig','domdefaults','usersessions',
15864:                       'directorysrch','passwdconf','cats');
15865:     if (keys(%servers)) {
15866:         foreach my $server (keys(%servers)) {
15867:             next if ($thismachine{$server});
15868:             my @cached;
15869:             foreach my $name (@posscached) {
15870:                 if ($cachekeys->{$name}) {
15871:                     push(@cached,&escape($name).':'.&escape($dom));
15872:                 }
15873:             }
15874:             if (@cached) {
15875:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
15876:             }
15877:         }
15878:     }
15879:     return;
15880: }
15881: 
15882: 1;

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