File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.371: download - view: text, annotated - select for diffs
Sun Mar 15 23:04:15 2020 UTC (4 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Add domain configuration to offload users from other institutions, on next
  access (after recording any submission to a problem).
- Switching user session to a different server can jump to the same resource
  currently being viewed when encrypturl is in effect.

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.371 2020/03/15 23:04:15 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: #
   29: ###############################################################
   30: ###############################################################
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::domainprefs.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40: Handles configuration of a LON-CAPA domain.  
   41: 
   42: This is part of the LearningOnline Network with CAPA project
   43: described at http://www.lon-capa.org.
   44: 
   45: 
   46: =head1 OVERVIEW
   47: 
   48: Each institution using LON-CAPA will typically have a single domain designated 
   49: for use by individuals affiliated with the institution.  Accordingly, each domain
   50: may define a default set of logos and a color scheme which can be used to "brand"
   51: the LON-CAPA instance. In addition, an institution will typically have a language
   52: and timezone which are used for the majority of courses.
   53: 
   54: LON-CAPA provides a mechanism to display and modify these defaults, as well as a 
   55: host of other domain-wide settings which determine the types of functionality
   56: available to users and courses in the domain.
   57: 
   58: There is also a mechanism to configure cataloging of courses in the domain, and
   59: controls on the operation of automated processes which govern such things as
   60: roster updates, user directory updates and processing of course requests.
   61: 
   62: The domain coordination manual which is built dynamically on install/update of 
   63: LON-CAPA from the relevant help items provides more information about domain 
   64: configuration.
   65: 
   66: Most of the domain settings are stored in the configuration.db GDBM file which is
   67: housed on the primary library server for the domain in /home/httpd/lonUsers/$dom,
   68: where $dom is the domain.  The configuration.db stores settings in a number of 
   69: frozen hashes of hashes.  In a few cases, domain information must be uploaded to
   70: the domain as files (e.g., image files for logos etc., or plain text files for
   71: bubblesheet formats).  In this case the domainprefs.pm must be running in a user
   72: session hosted on the primary library server in the domain, as these files are 
   73: stored in author space belonging to a special $dom-domainconfig user.   
   74: 
   75: domainprefs.pm in combination with lonconfigsettings.pm will retrieve and display
   76: the current settings, and provides an interface to make modifications.
   77: 
   78: =head1 SUBROUTINES
   79: 
   80: =over
   81: 
   82: =item print_quotas()
   83: 
   84: Inputs: 4 
   85: 
   86: $dom,$settings,$rowtotal,$action.
   87: 
   88: $dom is the domain, $settings is a reference to a hash of current settings for
   89: the current context, $rowtotal is a reference to the scalar used to record the 
   90: number of rows displayed on the page, and $action is the context (quotas, 
   91: requestcourses or requestauthor).
   92: 
   93: The print_quotas routine was orginally created to display/store information
   94: about default quota sizes for portfolio spaces for the different types of 
   95: institutional affiliation in the domain (e.g., Faculty, Staff, Student etc.), 
   96: but is now also used to manage availability of user tools: 
   97: i.e., blogs, aboutme page, and portfolios, and the course request tool,
   98: used by course owners to request creation of a course, and to display/store
   99: default quota sizes for Authoring Spaces.
  100: 
  101: Outputs: 1
  102: 
  103: $datatable  - HTML containing form elements which allow settings to be changed. 
  104: 
  105: In the case of course requests, radio buttons are displayed for each institutional
  106: affiliate type (and also default, and _LC_adv) for each of the course types 
  107: (official, unofficial, community, textbook, placement, and lti).  
  108: In each case the radio buttons allow the selection of one of four values:  
  109: 
  110: 0, approval, validate, autolimit=N (where N is blank, or a positive integer).
  111: which have the following effects:
  112: 
  113: 0
  114: 
  115: =over
  116: 
  117: - course requests are not allowed for this course types/affiliation
  118: 
  119: =back
  120: 
  121: approval 
  122: 
  123: =over 
  124: 
  125: - course requests must be approved by a Doman Coordinator in the 
  126: course's domain
  127: 
  128: =back
  129: 
  130: validate 
  131: 
  132: =over
  133: 
  134: - an institutional validation (e.g., check requestor is instructor
  135: of record) needs to be passed before the course will be created.  The required
  136: validation is in localenroll.pm on the primary library server for the course 
  137: domain.
  138: 
  139: =back
  140: 
  141: autolimit 
  142: 
  143: =over
  144:  
  145: - course requests will be processed automatically up to a limit of
  146: N requests for the course type for the particular requestor.
  147: If N is undefined, there is no limit to the number of course requests
  148: which a course owner may submit and have processed automatically. 
  149: 
  150: =back
  151: 
  152: =item modify_quotas() 
  153: 
  154: =back
  155: 
  156: =cut
  157: 
  158: package Apache::domainprefs;
  159: 
  160: use strict;
  161: use Apache::Constants qw(:common :http);
  162: use Apache::lonnet;
  163: use Apache::loncommon();
  164: use Apache::lonhtmlcommon();
  165: use Apache::lonlocal;
  166: use Apache::lonmsg();
  167: use Apache::lonconfigsettings;
  168: use Apache::lonuserutils();
  169: use Apache::loncoursequeueadmin();
  170: use LONCAPA qw(:DEFAULT :match);
  171: use LONCAPA::Enrollment;
  172: use LONCAPA::lonauthcgi();
  173: use LONCAPA::SSL;
  174: use File::Copy;
  175: use Locale::Language;
  176: use DateTime::TimeZone;
  177: use DateTime::Locale;
  178: use Time::HiRes qw( sleep );
  179: 
  180: my $registered_cleanup;
  181: my $modified_urls;
  182: 
  183: sub handler {
  184:     my $r=shift;
  185:     if ($r->header_only) {
  186:         &Apache::loncommon::content_type($r,'text/html');
  187:         $r->send_http_header;
  188:         return OK;
  189:     }
  190: 
  191:     my $context = 'domain';
  192:     my $dom = $env{'request.role.domain'};
  193:     my $domdesc = &Apache::lonnet::domain($dom,'description');
  194:     if (&Apache::lonnet::allowed('mau',$dom)) {
  195:         &Apache::loncommon::content_type($r,'text/html');
  196:         $r->send_http_header;
  197:     } else {
  198:         $env{'user.error.msg'}=
  199:         "/adm/domainprefs:mau:0:0:Cannot modify domain settings";
  200:         return HTTP_NOT_ACCEPTABLE;
  201:     }
  202: 
  203:     $registered_cleanup=0;
  204:     @{$modified_urls}=();
  205: 
  206:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  207:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  208:                                             ['phase','actions']);
  209:     my $phase = 'pickactions';
  210:     if ( exists($env{'form.phase'}) ) {
  211:         $phase = $env{'form.phase'};
  212:     }
  213:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
  214:     my %domconfig =
  215:       &Apache::lonnet::get_dom('configuration',['login','rolecolors',
  216:                 'quotas','autoenroll','autoupdate','autocreate',
  217:                 'directorysrch','usercreation','usermodification',
  218:                 'contacts','defaults','scantron','coursecategories',
  219:                 'serverstatuses','requestcourses','helpsettings',
  220:                 'coursedefaults','usersessions','loadbalancing',
  221:                 'requestauthor','selfenrollment','inststatus',
  222:                 'ltitools','ssl','trust','lti','privacy','passwords'],$dom);
  223:     my %encconfig =
  224:         &Apache::lonnet::get_dom('encconfig',['ltitools','lti'],$dom);
  225:     if (ref($domconfig{'ltitools'}) eq 'HASH') {
  226:         if (ref($encconfig{'ltitools'}) eq 'HASH') {
  227:             foreach my $id (keys(%{$domconfig{'ltitools'}})) {
  228:                 if ((ref($domconfig{'ltitools'}{$id}) eq 'HASH') &&
  229:                     (ref($encconfig{'ltitools'}{$id}) eq 'HASH')) {
  230:                     foreach my $item ('key','secret') {
  231:                         $domconfig{'ltitools'}{$id}{$item} = $encconfig{'ltitools'}{$id}{$item};
  232:                     }
  233:                 }
  234:             }
  235:         }
  236:     }
  237:     if (ref($domconfig{'lti'}) eq 'HASH') {
  238:         if (ref($encconfig{'lti'}) eq 'HASH') {
  239:             foreach my $id (keys(%{$domconfig{'lti'}})) {
  240:                 if ((ref($domconfig{'lti'}{$id}) eq 'HASH') &&
  241:                     (ref($encconfig{'lti'}{$id}) eq 'HASH')) {
  242:                     foreach my $item ('key','secret') {
  243:                         $domconfig{'lti'}{$id}{$item} = $encconfig{'lti'}{$id}{$item};
  244:                     }
  245:                 }
  246:             }
  247:         }
  248:     }
  249:     my @prefs_order = ('rolecolors','login','defaults','passwords','quotas','autoenroll',
  250:                        'autoupdate','autocreate','directorysrch','contacts','privacy',
  251:                        'usercreation','selfcreation','usermodification','scantron',
  252:                        'requestcourses','requestauthor','coursecategories',
  253:                        'serverstatuses','helpsettings','coursedefaults',
  254:                        'ltitools','selfenrollment','usersessions','ssl','trust','lti');
  255:     my %existing;
  256:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  257:         %existing = %{$domconfig{'loadbalancing'}};
  258:     }
  259:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  260:         push(@prefs_order,'loadbalancing');
  261:     }
  262:     my %prefs = (
  263:         'rolecolors' =>
  264:                    { text => 'Default color schemes',
  265:                      help => 'Domain_Configuration_Color_Schemes',
  266:                      header => [{col1 => 'Student Settings',
  267:                                  col2 => '',},
  268:                                 {col1 => 'Coordinator Settings',
  269:                                  col2 => '',},
  270:                                 {col1 => 'Author Settings',
  271:                                  col2 => '',},
  272:                                 {col1 => 'Administrator Settings',
  273:                                  col2 => '',}],
  274:                       print => \&print_rolecolors,
  275:                       modify => \&modify_rolecolors,
  276:                     },
  277:         'login' =>
  278:                     { text => 'Log-in page options',
  279:                       help => 'Domain_Configuration_Login_Page',
  280:                       header => [{col1 => 'Log-in Page Items',
  281:                                   col2 => '',},
  282:                                  {col1 => 'Log-in Help',
  283:                                   col2 => 'Value'},
  284:                                  {col1 => 'Custom HTML in document head',
  285:                                   col2 => 'Value'}],
  286:                       print => \&print_login,
  287:                       modify => \&modify_login,
  288:                     },
  289:         'defaults' => 
  290:                     { text => 'Default authentication/language/timezone/portal/types',
  291:                       help => 'Domain_Configuration_LangTZAuth',
  292:                       header => [{col1 => 'Setting',
  293:                                   col2 => 'Value'},
  294:                                  {col1 => 'Institutional user types',
  295:                                   col2 => 'Name displayed'}],
  296:                       print => \&print_defaults,
  297:                       modify => \&modify_defaults,
  298:                     },
  299:         'passwords' =>
  300:                     { text => 'Passwords (Internal authentication)',
  301:                       help => 'Domain_Configuration_Passwords',
  302:                       header => [{col1 => 'Resetting Forgotten Password',
  303:                                   col2 => 'Settings'},
  304:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  305:                                   col2 => 'Settings'},
  306:                                  {col1 => 'Rules for LON-CAPA Passwords',
  307:                                   col2 => 'Settings'},
  308:                                  {col1 => 'Course Owner Changing Student Passwords',
  309:                                   col2 => 'Settings'}],
  310:                       print => \&print_passwords,
  311:                       modify => \&modify_passwords,
  312:                     },
  313:         'quotas' => 
  314:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  315:                       help => 'Domain_Configuration_Quotas',
  316:                       header => [{col1 => 'User affiliation',
  317:                                   col2 => 'Available tools',
  318:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  319:                       print => \&print_quotas,
  320:                       modify => \&modify_quotas,
  321:                     },
  322:         'autoenroll' =>
  323:                    { text => 'Auto-enrollment settings',
  324:                      help => 'Domain_Configuration_Auto_Enrollment',
  325:                      header => [{col1 => 'Configuration setting',
  326:                                  col2 => 'Value(s)'}],
  327:                      print => \&print_autoenroll,
  328:                      modify => \&modify_autoenroll,
  329:                    },
  330:         'autoupdate' => 
  331:                    { text => 'Auto-update settings',
  332:                      help => 'Domain_Configuration_Auto_Updates',
  333:                      header => [{col1 => 'Setting',
  334:                                  col2 => 'Value',},
  335:                                 {col1 => 'Setting',
  336:                                  col2 => 'Affiliation'},
  337:                                 {col1 => 'User population',
  338:                                  col2 => 'Updatable user data'}],
  339:                      print => \&print_autoupdate,
  340:                      modify => \&modify_autoupdate,
  341:                   },
  342:         'autocreate' => 
  343:                   { text => 'Auto-course creation settings',
  344:                      help => 'Domain_Configuration_Auto_Creation',
  345:                      header => [{col1 => 'Configuration Setting',
  346:                                  col2 => 'Value',}],
  347:                      print => \&print_autocreate,
  348:                      modify => \&modify_autocreate,
  349:                   },
  350:         'directorysrch' => 
  351:                   { text => 'Directory searches',
  352:                     help => 'Domain_Configuration_InstDirectory_Search',
  353:                     header => [{col1 => 'Institutional Directory Setting',
  354:                                 col2 => 'Value',},
  355:                                {col1 => 'LON-CAPA Directory Setting',
  356:                                 col2 => 'Value',}],
  357:                     print => \&print_directorysrch,
  358:                     modify => \&modify_directorysrch,
  359:                   },
  360:         'contacts' =>
  361:                   { text => 'E-mail addresses and helpform',
  362:                     help => 'Domain_Configuration_Contact_Info',
  363:                     header => [{col1 => 'Default e-mail addresses',
  364:                                 col2 => 'Value',},
  365:                                {col1 => 'Recipient(s) for notifications',
  366:                                 col2 => 'Value',},
  367:                                {col1 => 'Nightly status check e-mail',
  368:                                 col2 => 'Settings',},
  369:                                {col1 => 'Ask helpdesk form settings',
  370:                                 col2 => 'Value',},],
  371:                     print => \&print_contacts,
  372:                     modify => \&modify_contacts,
  373:                   },
  374:         'usercreation' => 
  375:                   { text => 'User creation',
  376:                     help => 'Domain_Configuration_User_Creation',
  377:                     header => [{col1 => 'Format rule type',
  378:                                 col2 => 'Format rules in force'},
  379:                                {col1 => 'User account creation',
  380:                                 col2 => 'Usernames which may be created',},
  381:                                {col1 => 'Context',
  382:                                 col2 => 'Assignable authentication types'}],
  383:                     print => \&print_usercreation,
  384:                     modify => \&modify_usercreation,
  385:                   },
  386:         'selfcreation' => 
  387:                   { text => 'Users self-creating accounts',
  388:                     help => 'Domain_Configuration_Self_Creation', 
  389:                     header => [{col1 => 'Self-creation with institutional username',
  390:                                 col2 => 'Enabled?'},
  391:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  392:                                 col2 => 'Information user can enter'},
  393:                                {col1 => 'Self-creation with e-mail verification',
  394:                                 col2 => 'Settings'}],
  395:                     print => \&print_selfcreation,
  396:                     modify => \&modify_selfcreation,
  397:                   },
  398:         'usermodification' =>
  399:                   { text => 'User modification',
  400:                     help => 'Domain_Configuration_User_Modification',
  401:                     header => [{col1 => 'Target user has role',
  402:                                 col2 => 'User information updatable in author context'},
  403:                                {col1 => 'Target user has role',
  404:                                 col2 => 'User information updatable in course context'}],
  405:                     print => \&print_usermodification,
  406:                     modify => \&modify_usermodification,
  407:                   },
  408:         'scantron' =>
  409:                   { text => 'Bubblesheet format',
  410:                     help => 'Domain_Configuration_Scantron_Format',
  411:                     header => [ {col1 => 'Bubblesheet format file',
  412:                                  col2 => ''},
  413:                                 {col1 => 'Bubblesheet data upload formats',
  414:                                  col2 => 'Settings'}],
  415:                     print => \&print_scantron,
  416:                     modify => \&modify_scantron,
  417:                   },
  418:         'requestcourses' => 
  419:                  {text => 'Request creation of courses',
  420:                   help => 'Domain_Configuration_Request_Courses',
  421:                   header => [{col1 => 'User affiliation',
  422:                               col2 => 'Availability/Processing of requests',},
  423:                              {col1 => 'Setting',
  424:                               col2 => 'Value'},
  425:                              {col1 => 'Available textbooks',
  426:                               col2 => ''},
  427:                              {col1 => 'Available templates',
  428:                               col2 => ''},
  429:                              {col1 => 'Validation (not official courses)',
  430:                               col2 => 'Value'},],
  431:                   print => \&print_quotas,
  432:                   modify => \&modify_quotas,
  433:                  },
  434:         'requestauthor' =>
  435:                  {text => 'Request Authoring Space',
  436:                   help => 'Domain_Configuration_Request_Author',
  437:                   header => [{col1 => 'User affiliation',
  438:                               col2 => 'Availability/Processing of requests',},
  439:                              {col1 => 'Setting',
  440:                               col2 => 'Value'}],
  441:                   print => \&print_quotas,
  442:                   modify => \&modify_quotas,
  443:                  },
  444:         'coursecategories' =>
  445:                   { text => 'Cataloging of courses/communities',
  446:                     help => 'Domain_Configuration_Cataloging_Courses',
  447:                     header => [{col1 => 'Catalog type/availability',
  448:                                 col2 => '',},
  449:                                {col1 => 'Category settings for standard catalog',
  450:                                 col2 => '',},
  451:                                {col1 => 'Categories',
  452:                                 col2 => '',
  453:                                }],
  454:                     print => \&print_coursecategories,
  455:                     modify => \&modify_coursecategories,
  456:                   },
  457:         'serverstatuses' =>
  458:                  {text   => 'Access to server status pages',
  459:                   help   => 'Domain_Configuration_Server_Status',
  460:                   header => [{col1 => 'Status Page',
  461:                               col2 => 'Other named users',
  462:                               col3 => 'Specific IPs',
  463:                             }],
  464:                   print => \&print_serverstatuses,
  465:                   modify => \&modify_serverstatuses,
  466:                  },
  467:         'helpsettings' =>
  468:                  {text   => 'Support settings',
  469:                   help   => 'Domain_Configuration_Help_Settings',
  470:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  471:                               col2 => 'Value'},
  472:                              {col1 => 'Helpdesk Roles',
  473:                               col2 => 'Settings'},],
  474:                   print  => \&print_helpsettings,
  475:                   modify => \&modify_helpsettings,
  476:                  },
  477:         'coursedefaults' => 
  478:                  {text => 'Course/Community defaults',
  479:                   help => 'Domain_Configuration_Course_Defaults',
  480:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  481:                               col2 => 'Value',},
  482:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  483:                               col2 => 'Value',},],
  484:                   print => \&print_coursedefaults,
  485:                   modify => \&modify_coursedefaults,
  486:                  },
  487:         'selfenrollment' => 
  488:                  {text   => 'Self-enrollment in Course/Community',
  489:                   help   => 'Domain_Configuration_Selfenrollment',
  490:                   header => [{col1 => 'Configuration Rights',
  491:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  492:                              {col1 => 'Defaults',
  493:                               col2 => 'Value'},
  494:                              {col1 => 'Self-enrollment validation (optional)',
  495:                               col2 => 'Value'},],
  496:                   print => \&print_selfenrollment,
  497:                   modify => \&modify_selfenrollment,
  498:                  },
  499:         'privacy' => 
  500:                  {text   => 'Availability of User Information',
  501:                   help   => 'Domain_Configuration_User_Privacy',
  502:                   header => [{col1 => 'Role assigned in different domain',
  503:                               col2 => 'Approval options'},
  504:                              {col1 => 'Role assigned in different domain to user of type',
  505:                               col2 => 'User information available in that domain'},
  506:                              {col1 => "Role assigned in user's domain",
  507:                               col2 => 'Information viewable by privileged user'},
  508:                              {col1 => "Role assigned in user's domain",
  509:                               col2 => 'Information viewable by unprivileged user'}],
  510:                   print => \&print_privacy,
  511:                   modify => \&modify_privacy,
  512:                  },
  513:         'usersessions' =>
  514:                  {text  => 'User session hosting/offloading',
  515:                   help  => 'Domain_Configuration_User_Sessions',
  516:                   header => [{col1 => 'Domain server',
  517:                               col2 => 'Servers to offload sessions to when busy'},
  518:                              {col1 => 'Hosting of users from other domains',
  519:                               col2 => 'Rules'},
  520:                              {col1 => "Hosting domain's own users elsewhere",
  521:                               col2 => 'Rules'}],
  522:                   print => \&print_usersessions,
  523:                   modify => \&modify_usersessions,
  524:                  },
  525:         'loadbalancing' =>
  526:                  {text  => 'Dedicated Load Balancer(s)',
  527:                   help  => 'Domain_Configuration_Load_Balancing',
  528:                   header => [{col1 => 'Balancers',
  529:                               col2 => 'Default destinations',
  530:                               col3 => 'User affiliation',
  531:                               col4 => 'Overrides'},
  532:                             ],
  533:                   print => \&print_loadbalancing,
  534:                   modify => \&modify_loadbalancing,
  535:                  },
  536:         'ltitools' => 
  537:                  {text => 'External Tools (LTI)',
  538:                   help => 'Domain_Configuration_LTI_Tools',
  539:                   header => [{col1 => 'Setting',
  540:                               col2 => 'Value',}],
  541:                   print => \&print_ltitools,
  542:                   modify => \&modify_ltitools,
  543:                  },
  544:         'ssl' =>
  545:                  {text  => 'LON-CAPA Network (SSL)',
  546:                   help  => 'Domain_Configuration_Network_SSL',
  547:                   header => [{col1 => 'Server',
  548:                               col2 => 'Certificate Status'},
  549:                              {col1 => 'Connections to other servers',
  550:                               col2 => 'Rules'},
  551:                              {col1 => 'Connections from other servers',
  552:                               col2 => 'Rules'},
  553:                              {col1 => "Replicating domain's published content",
  554:                               col2 => 'Rules'}],
  555:                   print => \&print_ssl,
  556:                   modify => \&modify_ssl,
  557:                  },
  558:         'trust' =>
  559:                  {text   => 'Trust Settings',
  560:                   help   => 'Domain_Configuration_Trust',
  561:                   header => [{col1 => "Access to this domain's content by others",
  562:                               col2 => 'Rules'},
  563:                              {col1 => "Access to other domain's content by this domain",
  564:                               col2 => 'Rules'},
  565:                              {col1 => "Enrollment in this domain's courses by others",
  566:                               col2 => 'Rules',},
  567:                              {col1 => "Co-author roles in this domain for others",
  568:                               col2 => 'Rules',},
  569:                              {col1 => "Co-author roles for this domain's users elsewhere",
  570:                               col2 => 'Rules',},
  571:                              {col1 => "Domain roles in this domain assignable to others",
  572:                               col2 => 'Rules'},
  573:                              {col1 => "Course catalog for this domain displayed elsewhere",
  574:                               col2 => 'Rules'},
  575:                              {col1 => "Requests for creation of courses in this domain by others",
  576:                               col2 => 'Rules'},
  577:                              {col1 => "Users in other domains can send messages to this domain",
  578:                               col2 => 'Rules'},],
  579:                   print => \&print_trust,
  580:                   modify => \&modify_trust,
  581:                  },
  582:           'lti' =>
  583:                  {text => 'LTI Provider',
  584:                   help => 'Domain_Configuration_LTI_Provider',
  585:                   header => [{col1 => 'Setting',
  586:                               col2 => 'Value',}],
  587:                   print => \&print_lti,
  588:                   modify => \&modify_lti,
  589:                  },
  590:     );
  591:     if (keys(%servers) > 1) {
  592:         $prefs{'login'}  = { text   => 'Log-in page options',
  593:                              help   => 'Domain_Configuration_Login_Page',
  594:                             header => [{col1 => 'Log-in Service',
  595:                                         col2 => 'Server Setting',},
  596:                                        {col1 => 'Log-in Page Items',
  597:                                         col2 => ''},
  598:                                        {col1 => 'Log-in Help',
  599:                                         col2 => 'Value'},
  600:                                        {col1 => 'Custom HTML in document head',
  601:                                         col2 => 'Value'}],
  602:                             print => \&print_login,
  603:                             modify => \&modify_login,
  604:                            };
  605:     }
  606: 
  607:     my @roles = ('student','coordinator','author','admin');
  608:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  609:     &Apache::lonhtmlcommon::add_breadcrumb
  610:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  611:       text=>"Settings to display/modify"});
  612:     my $confname = $dom.'-domainconfig';
  613: 
  614:     if ($phase eq 'process') {
  615:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  616:                                                               \%prefs,\%domconfig,$confname,\@roles);
  617:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  618:             $r->rflush();
  619:             &devalidate_remote_domconfs($dom,$result);
  620:         }
  621:     } elsif ($phase eq 'display') {
  622:         my $js = &recaptcha_js().
  623:                  &toggle_display_js();
  624:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  625:             my ($othertitle,$usertypes,$types) =
  626:                 &Apache::loncommon::sorted_inst_types($dom);
  627:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  628:                                           $domconfig{'loadbalancing'}).
  629:                    &new_spares_js().
  630:                    &common_domprefs_js().
  631:                    &Apache::loncommon::javascript_array_indexof();
  632:         }
  633:         if (grep(/^requestcourses$/,@actions)) {
  634:             my $javascript_validations;
  635:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  636:             $js .= <<END;
  637: <script type="text/javascript">
  638: $javascript_validations
  639: </script>
  640: $coursebrowserjs
  641: END
  642:         }
  643:         if (grep(/^selfcreation$/,@actions)) {
  644:             $js .= &selfcreate_javascript();
  645:         }
  646:         if (grep(/^contacts$/,@actions)) {
  647:             $js .= &contacts_javascript();
  648:         }
  649:         if (grep(/^scantron$/,@actions)) {
  650:             $js .= &scantron_javascript();
  651:         }
  652:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  653:     } else {
  654: # check if domconfig user exists for the domain.
  655:         my $servadm = $r->dir_config('lonAdmEMail');
  656:         my ($configuserok,$author_ok,$switchserver) =
  657:             &config_check($dom,$confname,$servadm);
  658:         unless ($configuserok eq 'ok') {
  659:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  660:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  661:                           $confname).
  662:                       '<br />'
  663:             );
  664:             if ($switchserver) {
  665:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  666:                           '<br />'.
  667:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  668:                           '<br />'.
  669:                           &mt('The "[_1]" user can be created automatically when a Domain Coordinator visits the web-based "Set domain configuration" screen, in a session hosted on the primary library server.',$confname).
  670:                           '<br />'.
  671:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  672:                 );
  673:             } else {
  674:                 $r->print(&mt('To create that user from the command line run the ./UPDATE script found in the top level directory of the extracted LON-CAPA tarball.').
  675:                           '<br />'.
  676:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  677:                 );
  678:             }
  679:             $r->print(&Apache::loncommon::end_page());
  680:             return OK;
  681:         }
  682:         if (keys(%domconfig) == 0) {
  683:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  684:             my @ids=&Apache::lonnet::current_machine_ids();
  685:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  686:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  687:                 my @loginimages = ('img','logo','domlogo','login');
  688:                 my $custom_img_count = 0;
  689:                 foreach my $img (@loginimages) {
  690:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  691:                         $custom_img_count ++;
  692:                     }
  693:                 }
  694:                 foreach my $role (@roles) {
  695:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  696:                         $custom_img_count ++;
  697:                     }
  698:                 }
  699:                 if ($custom_img_count > 0) {
  700:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  701:                     my $switch_server = &check_switchserver($dom,$confname);
  702:                     $r->print(
  703:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  704:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  705:     &mt("Thereafter, (with a Domain Coordinator role selected in the domain) you will be able to update settings when logged in to any server in the LON-CAPA network.").'<br />'.
  706:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  707:                     if ($switch_server) {
  708:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  709:                     }
  710:                     $r->print(&Apache::loncommon::end_page());
  711:                     return OK;
  712:                 }
  713:             }
  714:         }
  715:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  716:     }
  717:     return OK;
  718: }
  719: 
  720: sub process_changes {
  721:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  722:     my %domconfig;
  723:     if (ref($values) eq 'HASH') {
  724:         %domconfig = %{$values};
  725:     }
  726:     my $output;
  727:     if ($action eq 'login') {
  728:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  729:     } elsif ($action eq 'rolecolors') {
  730:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  731:                                      $lastactref,%domconfig);
  732:     } elsif ($action eq 'quotas') {
  733:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  734:     } elsif ($action eq 'autoenroll') {
  735:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  736:     } elsif ($action eq 'autoupdate') {
  737:         $output = &modify_autoupdate($dom,%domconfig);
  738:     } elsif ($action eq 'autocreate') {
  739:         $output = &modify_autocreate($dom,%domconfig);
  740:     } elsif ($action eq 'directorysrch') {
  741:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  742:     } elsif ($action eq 'usercreation') {
  743:         $output = &modify_usercreation($dom,%domconfig);
  744:     } elsif ($action eq 'selfcreation') {
  745:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  746:     } elsif ($action eq 'usermodification') {
  747:         $output = &modify_usermodification($dom,%domconfig);
  748:     } elsif ($action eq 'contacts') {
  749:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  750:     } elsif ($action eq 'defaults') {
  751:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  752:     } elsif ($action eq 'scantron') {
  753:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  754:     } elsif ($action eq 'coursecategories') {
  755:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  756:     } elsif ($action eq 'serverstatuses') {
  757:         $output = &modify_serverstatuses($dom,%domconfig);
  758:     } elsif ($action eq 'requestcourses') {
  759:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  760:     } elsif ($action eq 'requestauthor') {
  761:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  762:     } elsif ($action eq 'helpsettings') {
  763:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  764:     } elsif ($action eq 'coursedefaults') {
  765:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  766:     } elsif ($action eq 'selfenrollment') {
  767:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  768:     } elsif ($action eq 'usersessions') {
  769:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  770:     } elsif ($action eq 'loadbalancing') {
  771:         $output = &modify_loadbalancing($dom,%domconfig);
  772:     } elsif ($action eq 'ltitools') {
  773:         $output = &modify_ltitools($r,$dom,$action,$lastactref,%domconfig);
  774:     } elsif ($action eq 'ssl') {
  775:         $output = &modify_ssl($dom,$lastactref,%domconfig);
  776:     } elsif ($action eq 'trust') {
  777:         $output = &modify_trust($dom,$lastactref,%domconfig);
  778:     } elsif ($action eq 'lti') {
  779:         $output = &modify_lti($r,$dom,$action,$lastactref,%domconfig);
  780:     } elsif ($action eq 'privacy') {
  781:         $output = &modify_privacy($dom,%domconfig);
  782:     } elsif ($action eq 'passwords') {
  783:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  784:     }
  785:     return $output;
  786: }
  787: 
  788: sub print_config_box {
  789:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  790:     my $rowtotal = 0;
  791:     my $output;
  792:     if ($action eq 'coursecategories') {
  793:         $output = &coursecategories_javascript($settings);
  794:     } elsif ($action eq 'defaults') {
  795:         $output = &defaults_javascript($settings); 
  796:     } elsif ($action eq 'passwords') {
  797:         $output = &passwords_javascript();
  798:     } elsif ($action eq 'helpsettings') {
  799:         my (%privs,%levelscurrent);
  800:         my %full=();
  801:         my %levels=(
  802:                      course => {},
  803:                      domain => {},
  804:                      system => {},
  805:                    );
  806:         my $context = 'domain';
  807:         my $crstype = 'Course';
  808:         my $formname = 'display';
  809:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  810:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  811:         $output =
  812:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full, 
  813:                                                       \@templateroles);
  814:     } elsif ($action eq 'ltitools') {
  815:         $output .= &ltitools_javascript($settings);
  816:     } elsif ($action eq 'lti') {
  817:         $output .= &lti_javascript($settings);
  818:     }
  819:     $output .=
  820:          '<table class="LC_nested_outer">
  821:           <tr>
  822:            <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
  823:            &mt($item->{text}).'&nbsp;'.
  824:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  825:           '</tr>';
  826:     $rowtotal ++;
  827:     my $numheaders = 1;
  828:     if (ref($item->{'header'}) eq 'ARRAY') {
  829:         $numheaders = scalar(@{$item->{'header'}});
  830:     }
  831:     if ($numheaders > 1) {
  832:         my $colspan = '';
  833:         my $rightcolspan = '';
  834:         my $leftnobr = '';
  835:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  836:             ($action eq 'directorysrch') ||
  837:             (($action eq 'login') && ($numheaders < 4))) {
  838:             $colspan = ' colspan="2"';
  839:         }
  840:         if ($action eq 'usersessions') {
  841:             $rightcolspan = ' colspan="3"'; 
  842:         }
  843:         if ($action eq 'passwords') {
  844:             $leftnobr = ' LC_nobreak';
  845:         }
  846:         $output .= '
  847:           <tr>
  848:            <td>
  849:             <table class="LC_nested">
  850:              <tr class="LC_info_row">
  851:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  852:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  853:              </tr>';
  854:         $rowtotal ++;
  855:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  856:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  857:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'ssl') ||
  858:             ($action eq 'directorysrch') || ($action eq 'trust') || ($action eq 'helpsettings') ||
  859:             ($action eq 'contacts') || ($action eq 'privacy')) {
  860:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  861:         } elsif ($action eq 'passwords') {
  862:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  863:         } elsif ($action eq 'coursecategories') {
  864:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  865:         } elsif ($action eq 'scantron') {
  866:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  867:         } elsif ($action eq 'login') {
  868:             if ($numheaders == 4) {
  869:                 $colspan = ' colspan="2"';
  870:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  871:             } else {
  872:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  873:             }
  874:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  875:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  876:         } elsif ($action eq 'rolecolors') {
  877:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  878:         }
  879:         $output .= '
  880:            </table>
  881:           </td>
  882:          </tr>
  883:          <tr>
  884:            <td>
  885:             <table class="LC_nested">
  886:              <tr class="LC_info_row">
  887:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  888:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  889:              </tr>';
  890:             $rowtotal ++;
  891:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  892:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  893:             ($action eq 'usersessions') || ($action eq 'coursecategories') || 
  894:             ($action eq 'trust') || ($action eq 'contacts') ||
  895:             ($action eq 'privacy') || ($action eq 'passwords')) {
  896:             if ($action eq 'coursecategories') {
  897:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  898:                 $colspan = ' colspan="2"';
  899:             } elsif ($action eq 'trust') {
  900:                 $output .= $item->{'print'}->('shared',$dom,$settings,\$rowtotal);
  901:             } elsif ($action eq 'passwords') {
  902:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
  903:             } else {
  904:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  905:             }
  906:             if ($action eq 'trust') {
  907:                 $output .= '
  908:             </table>
  909:           </td>
  910:          </tr>';
  911:                 my @trusthdrs = qw(2 3 4 5 6 7);
  912:                 my @prefixes = qw(enroll othcoau coaurem domroles catalog reqcrs);
  913:                 for (my $i=0; $i<@trusthdrs; $i++) {
  914:                     $output .= '
  915:          <tr>
  916:            <td>
  917:             <table class="LC_nested">
  918:              <tr class="LC_info_row">
  919:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col1'}).'</td>
  920:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col2'}).'</td></tr>'.
  921:                            $item->{'print'}->($prefixes[$i],$dom,$settings,\$rowtotal).'
  922:             </table>
  923:           </td>
  924:          </tr>';
  925:                 }
  926:                 $output .= '
  927:          <tr>
  928:            <td>
  929:             <table class="LC_nested">
  930:              <tr class="LC_info_row">
  931:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col1'}).'</td>
  932:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col2'}).'</td></tr>'.
  933:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  934:             } else {
  935:                 $output .= '
  936:            </table>
  937:           </td>
  938:          </tr>
  939:          <tr>
  940:            <td>
  941:             <table class="LC_nested">
  942:              <tr class="LC_info_row">
  943:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  944:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  945:              </tr>'."\n";
  946:                 if ($action eq 'coursecategories') {
  947:                     $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
  948:                 } elsif (($action eq 'contacts') || ($action eq 'privacy') || ($action eq 'passwords')) {
  949:                     if ($action eq 'passwords') {
  950:                         $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal);
  951:                     } else {
  952:                         $output .= $item->{'print'}->('lower',$dom,$settings,\$rowtotal);
  953:                     }
  954:                     $output .= '
  955:              </tr>
  956:             </table>
  957:            </td>
  958:           </tr>
  959:           <tr>
  960:            <td>
  961:             <table class="LC_nested">
  962:              <tr class="LC_info_row">
  963:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
  964:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
  965:                     if ($action eq 'passwords') {
  966:                         $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
  967:                     } else {
  968:                         $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  969:                     }
  970:                     $output .= '
  971:             </table>
  972:           </td>
  973:          </tr>
  974:          <tr>';
  975:                 } else {
  976:                     $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  977:                 }
  978:             }
  979:             $rowtotal ++;
  980:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
  981:                  ($action eq 'defaults') || ($action eq 'directorysrch') ||
  982:                  ($action eq 'helpsettings')) {
  983:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  984:         } elsif ($action eq 'scantron') {
  985:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
  986:         } elsif ($action eq 'ssl') {
  987:             $output .= $item->{'print'}->('connto',$dom,$settings,\$rowtotal).'
  988:             </table>
  989:           </td>
  990:          </tr>
  991:          <tr>
  992:            <td>
  993:             <table class="LC_nested">
  994:              <tr class="LC_info_row">
  995:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  996:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
  997:                            $item->{'print'}->('connfrom',$dom,$settings,\$rowtotal).'
  998:             </table>
  999:           </td>
 1000:          </tr>
 1001:          <tr>
 1002:            <td>
 1003:             <table class="LC_nested">
 1004:              <tr class="LC_info_row">
 1005:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1006:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'.
 1007:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1008:         } elsif ($action eq 'login') {
 1009:             if ($numheaders == 4) {
 1010:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
 1011:            </table>
 1012:           </td>
 1013:          </tr>
 1014:          <tr>
 1015:            <td>
 1016:             <table class="LC_nested">
 1017:              <tr class="LC_info_row">
 1018:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1019:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1020:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1021:                 $rowtotal ++;
 1022:             } else {
 1023:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1024:             }
 1025:             $output .= '
 1026:            </table>
 1027:           </td>
 1028:          </tr>
 1029:          <tr>
 1030:            <td>
 1031:             <table class="LC_nested">
 1032:              <tr class="LC_info_row">';
 1033:             if ($numheaders == 4) {
 1034:                 $output .= '
 1035:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1036:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1037:              </tr>';
 1038:             } else {
 1039:                 $output .= '
 1040:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1041:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1042:              </tr>';
 1043:             }
 1044:             $rowtotal ++;
 1045:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal);
 1046:         } elsif ($action eq 'requestcourses') {
 1047:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1048:             $rowtotal ++;
 1049:             $output .= &print_studentcode($settings,\$rowtotal).'
 1050:            </table>
 1051:           </td>
 1052:          </tr>
 1053:          <tr>
 1054:            <td>
 1055:             <table class="LC_nested">
 1056:              <tr class="LC_info_row">
 1057:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1058:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
 1059:                        &textbookcourses_javascript($settings).
 1060:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
 1061:             </table>
 1062:            </td>
 1063:           </tr>
 1064:          <tr>
 1065:            <td>
 1066:             <table class="LC_nested">
 1067:              <tr class="LC_info_row">
 1068:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1069:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
 1070:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
 1071:             </table>
 1072:            </td>
 1073:           </tr>
 1074:           <tr>
 1075:            <td>
 1076:             <table class="LC_nested">
 1077:              <tr class="LC_info_row">
 1078:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1079:               <td class="LC_right_item" style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1080:              </tr>'.
 1081:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
 1082:         } elsif ($action eq 'requestauthor') {
 1083:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1084:             $rowtotal ++;
 1085:         } elsif ($action eq 'rolecolors') {
 1086:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
 1087:            </table>
 1088:           </td>
 1089:          </tr>
 1090:          <tr>
 1091:            <td>
 1092:             <table class="LC_nested">
 1093:              <tr class="LC_info_row">
 1094:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.
 1095:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
 1096:               <td class="LC_right_item" style="vertical-align: top">'.
 1097:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
 1098:              </tr>'.
 1099:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
 1100:            </table>
 1101:           </td>
 1102:          </tr>
 1103:          <tr>
 1104:            <td>
 1105:             <table class="LC_nested">
 1106:              <tr class="LC_info_row">
 1107:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1108:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1109:              </tr>'.
 1110:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
 1111:             $rowtotal += 2;
 1112:         }
 1113:     } else {
 1114:         $output .= '
 1115:           <tr>
 1116:            <td>
 1117:             <table class="LC_nested">
 1118:              <tr class="LC_info_row">';
 1119:         if ($action eq 'login') {
 1120:             $output .= '  
 1121:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1122:         } elsif ($action eq 'serverstatuses') {
 1123:             $output .= '
 1124:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).
 1125:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
 1126: 
 1127:         } else {
 1128:             $output .= '
 1129:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1130:         }
 1131:         if (defined($item->{'header'}->[0]->{'col3'})) {
 1132:             $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1133:                        &mt($item->{'header'}->[0]->{'col2'});
 1134:             if ($action eq 'serverstatuses') {
 1135:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
 1136:             } 
 1137:         } else {
 1138:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1139:                        &mt($item->{'header'}->[0]->{'col2'});
 1140:         }
 1141:         $output .= '</td>';
 1142:         if ($item->{'header'}->[0]->{'col3'}) {
 1143:             if (defined($item->{'header'}->[0]->{'col4'})) {
 1144:                 $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1145:                             &mt($item->{'header'}->[0]->{'col3'});
 1146:             } else {
 1147:                 $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1148:                            &mt($item->{'header'}->[0]->{'col3'});
 1149:             }
 1150:             if ($action eq 'serverstatuses') {
 1151:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
 1152:             }
 1153:             $output .= '</td>';
 1154:         }
 1155:         if ($item->{'header'}->[0]->{'col4'}) {
 1156:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1157:                        &mt($item->{'header'}->[0]->{'col4'});
 1158:         }
 1159:         $output .= '</tr>';
 1160:         $rowtotal ++;
 1161:         if ($action eq 'quotas') {
 1162:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
 1163:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
 1164:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') || 
 1165:                  ($action eq 'ltitools') || ($action eq 'lti')) {
 1166:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
 1167:         }
 1168:     }
 1169:     $output .= '
 1170:    </table>
 1171:   </td>
 1172:  </tr>
 1173: </table><br />';
 1174:     return ($output,$rowtotal);
 1175: }
 1176: 
 1177: sub print_login {
 1178:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
 1179:     my ($css_class,$datatable);
 1180:     my %choices = &login_choices();
 1181: 
 1182:     if ($caller eq 'service') {
 1183:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1184:         my $choice = $choices{'disallowlogin'};
 1185:         $css_class = ' class="LC_odd_row"';
 1186:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1187:                       '<td style="text-align: right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1188:                       '<th>'.$choices{'server'}.'</th>'.
 1189:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1190:                       '<th>'.$choices{'custompath'}.'</th>'.
 1191:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1192:         my %disallowed;
 1193:         if (ref($settings) eq 'HASH') {
 1194:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1195:                %disallowed = %{$settings->{'loginvia'}};
 1196:             }
 1197:         }
 1198:         foreach my $lonhost (sort(keys(%servers))) {
 1199:             my $direct = 'selected="selected"';
 1200:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1201:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1202:                     $direct = '';
 1203:                 }
 1204:             }
 1205:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1206:                           '<td><select name="'.$lonhost.'_server">'.
 1207:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1208:                           '</option>';
 1209:             foreach my $hostid (sort(keys(%servers))) {
 1210:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1211:                 my $selected = '';
 1212:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1213:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1214:                         $selected = 'selected="selected"';
 1215:                     }
 1216:                 }
 1217:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1218:                               $servers{$hostid}.'</option>';
 1219:             }
 1220:             $datatable .= '</select></td>'.
 1221:                           '<td><select name="'.$lonhost.'_serverpath">';
 1222:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1223:                 my $pathname = $path;
 1224:                 if ($path eq 'custom') {
 1225:                     $pathname = &mt('Custom Path').' ->';
 1226:                 }
 1227:                 my $selected = '';
 1228:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1229:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1230:                         $selected = 'selected="selected"';
 1231:                     }
 1232:                 } elsif ($path eq '') {
 1233:                     $selected = 'selected="selected"';
 1234:                 }
 1235:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1236:             }
 1237:             $datatable .= '</select></td>';
 1238:             my ($custom,$exempt);
 1239:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1240:                 $custom = $disallowed{$lonhost}{'custompath'};
 1241:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1242:             }
 1243:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1244:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1245:                           '</tr>';
 1246:         }
 1247:         $datatable .= '</table></td></tr>';
 1248:         return $datatable;
 1249:     } elsif ($caller eq 'page') {
 1250:         my %defaultchecked = ( 
 1251:                                'coursecatalog' => 'on',
 1252:                                'helpdesk'      => 'on',
 1253:                                'adminmail'     => 'off',
 1254:                                'newuser'       => 'off',
 1255:                              );
 1256:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1257:         my (%checkedon,%checkedoff);
 1258:         foreach my $item (@toggles) {
 1259:             if ($defaultchecked{$item} eq 'on') { 
 1260:                 $checkedon{$item} = ' checked="checked" ';
 1261:                 $checkedoff{$item} = ' ';
 1262:             } elsif ($defaultchecked{$item} eq 'off') {
 1263:                 $checkedoff{$item} = ' checked="checked" ';
 1264:                 $checkedon{$item} = ' ';
 1265:             }
 1266:         }
 1267:         my @images = ('img','logo','domlogo','login');
 1268:         my @logintext = ('textcol','bgcol');
 1269:         my @bgs = ('pgbg','mainbg','sidebg');
 1270:         my @links = ('link','alink','vlink');
 1271:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1272:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1273:         my (%is_custom,%designs);
 1274:         my %defaults = (
 1275:                        font => $defaultdesign{'login.font'},
 1276:                        );
 1277:         foreach my $item (@images) {
 1278:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1279:             $defaults{'showlogo'}{$item} = 1;
 1280:         }
 1281:         foreach my $item (@bgs) {
 1282:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1283:         }
 1284:         foreach my $item (@logintext) {
 1285:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1286:         }
 1287:         foreach my $item (@links) {
 1288:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1289:         }
 1290:         if (ref($settings) eq 'HASH') {
 1291:             foreach my $item (@toggles) {
 1292:                 if ($settings->{$item} eq '1') {
 1293:                     $checkedon{$item} =  ' checked="checked" ';
 1294:                     $checkedoff{$item} = ' ';
 1295:                 } elsif ($settings->{$item} eq '0') {
 1296:                     $checkedoff{$item} =  ' checked="checked" ';
 1297:                     $checkedon{$item} = ' ';
 1298:                 }
 1299:             }
 1300:             foreach my $item (@images) {
 1301:                 if (defined($settings->{$item})) {
 1302:                     $designs{$item} = $settings->{$item};
 1303:                     $is_custom{$item} = 1;
 1304:                 }
 1305:                 if (defined($settings->{'showlogo'}{$item})) {
 1306:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1307:                 }
 1308:             }
 1309:             foreach my $item (@logintext) {
 1310:                 if ($settings->{$item} ne '') {
 1311:                     $designs{'logintext'}{$item} = $settings->{$item};
 1312:                     $is_custom{$item} = 1;
 1313:                 }
 1314:             }
 1315:             if ($settings->{'font'} ne '') {
 1316:                 $designs{'font'} = $settings->{'font'};
 1317:                 $is_custom{'font'} = 1;
 1318:             }
 1319:             foreach my $item (@bgs) {
 1320:                 if ($settings->{$item} ne '') {
 1321:                     $designs{'bgs'}{$item} = $settings->{$item};
 1322:                     $is_custom{$item} = 1;
 1323:                 }
 1324:             }
 1325:             foreach my $item (@links) {
 1326:                 if ($settings->{$item} ne '') {
 1327:                     $designs{'links'}{$item} = $settings->{$item};
 1328:                     $is_custom{$item} = 1;
 1329:                 }
 1330:             }
 1331:         } else {
 1332:             if ($designhash{$dom.'.login.font'} ne '') {
 1333:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1334:                 $is_custom{'font'} = 1;
 1335:             }
 1336:             foreach my $item (@images) {
 1337:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1338:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1339:                     $is_custom{$item} = 1;
 1340:                 }
 1341:             }
 1342:             foreach my $item (@bgs) {
 1343:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1344:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1345:                     $is_custom{$item} = 1;
 1346:                 }
 1347:             }
 1348:             foreach my $item (@links) {
 1349:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1350:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1351:                     $is_custom{$item} = 1;
 1352:                 }
 1353:             }
 1354:         }
 1355:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1356:                                                       logo => 'Institution Logo',
 1357:                                                       domlogo => 'Domain Logo',
 1358:                                                       login => 'Login box');
 1359:         my $itemcount = 1;
 1360:         foreach my $item (@toggles) {
 1361:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1362:             $datatable .=  
 1363:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1364:                 '</td><td>'.
 1365:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1366:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1367:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1368:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1369:                 '</tr>';
 1370:             $itemcount ++;
 1371:         }
 1372:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1373:         $datatable .= '</tr></table></td></tr>';
 1374:     } elsif ($caller eq 'help') {
 1375:         my ($defaulturl,$defaulttype,%url,%type,%lt,%langchoices);
 1376:         my $switchserver = &check_switchserver($dom,$confname);
 1377:         my $itemcount = 1;
 1378:         $defaulturl = '/adm/loginproblems.html';
 1379:         $defaulttype = 'default';
 1380:         %lt = &Apache::lonlocal::texthash (
 1381:                      del     => 'Delete?',
 1382:                      rep     => 'Replace:',
 1383:                      upl     => 'Upload:',
 1384:                      default => 'Default',
 1385:                      custom  => 'Custom',
 1386:                                              );
 1387:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1388:         my @currlangs;
 1389:         if (ref($settings) eq 'HASH') {
 1390:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1391:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1392:                     next if ($settings->{'helpurl'}{$key} eq '');
 1393:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1394:                     $type{$key} = 'custom';
 1395:                     unless ($key eq 'nolang') {
 1396:                         push(@currlangs,$key);
 1397:                     }
 1398:                 }
 1399:             } elsif ($settings->{'helpurl'} ne '') {
 1400:                 $type{'nolang'} = 'custom';
 1401:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1402:             }
 1403:         }
 1404:         foreach my $lang ('nolang',sort(@currlangs)) {
 1405:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1406:             $datatable .= '<tr'.$css_class.'>';
 1407:             if ($url{$lang} eq '') {
 1408:                 $url{$lang} = $defaulturl;
 1409:             }
 1410:             if ($type{$lang} eq '') {
 1411:                 $type{$lang} = $defaulttype;
 1412:             }
 1413:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1414:             if ($lang eq 'nolang') {
 1415:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1416:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1417:             } else {
 1418:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1419:                                   $langchoices{$lang},
 1420:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1421:             }
 1422:             $datatable .= '</span></td>'."\n".
 1423:                           '<td class="LC_left_item">';
 1424:             if ($type{$lang} eq 'custom') {
 1425:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1426:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1427:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1428:             } else {
 1429:                 $datatable .= $lt{'upl'};
 1430:             }
 1431:             $datatable .='<br />';
 1432:             if ($switchserver) {
 1433:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1434:             } else {
 1435:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1436:             }
 1437:             $datatable .= '</td></tr>';
 1438:             $itemcount ++;
 1439:         }
 1440:         my @addlangs;
 1441:         foreach my $lang (sort(keys(%langchoices))) {
 1442:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1443:             push(@addlangs,$lang);
 1444:         }
 1445:         if (@addlangs > 0) {
 1446:             my %toadd;
 1447:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1448:             $toadd{''} = &mt('Select');
 1449:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1450:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1451:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1452:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1453:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1454:             if ($switchserver) {
 1455:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1456:             } else {
 1457:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1458:             }
 1459:             $datatable .= '</td></tr>';
 1460:             $itemcount ++;
 1461:         }
 1462:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1463:     } elsif ($caller eq 'headtag') {
 1464:         my %domservers = &Apache::lonnet::get_servers($dom);
 1465:         my $choice = $choices{'headtag'};
 1466:         $css_class = ' class="LC_odd_row"';
 1467:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1468:                       '<td style="text-align: left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1469:                       '<th>'.$choices{'current'}.'</th>'.
 1470:                       '<th>'.$choices{'action'}.'</th>'.
 1471:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1472:         my (%currurls,%currexempt);
 1473:         if (ref($settings) eq 'HASH') {
 1474:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1475:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1476:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1477:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1478:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1479:                     }
 1480:                 }
 1481:             }
 1482:         }
 1483:         my %lt = &Apache::lonlocal::texthash(
 1484:                                                del  => 'Delete?',
 1485:                                                rep  => 'Replace:',
 1486:                                                upl  => 'Upload:',
 1487:                                                curr => 'View contents',
 1488:                                                none => 'None',
 1489:         );
 1490:         my $switchserver = &check_switchserver($dom,$confname);
 1491:         foreach my $lonhost (sort(keys(%domservers))) {
 1492:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1493:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1494:             if ($currurls{$lonhost}) {
 1495:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1496:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1497:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1498:                               '">'.$lt{'curr'}.'</a></td>'.
 1499:                               '<td><span class="LC_nobreak"><label>'.
 1500:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1501:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1502:             } else {
 1503:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1504:             }
 1505:             $datatable .='<br />';
 1506:             if ($switchserver) {
 1507:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1508:             } else {
 1509:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1510:             }
 1511:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1512:         }
 1513:         $datatable .= '</table></td></tr>';
 1514:     }
 1515:     return $datatable;
 1516: }
 1517: 
 1518: sub login_choices {
 1519:     my %choices =
 1520:         &Apache::lonlocal::texthash (
 1521:             coursecatalog => 'Display Course/Community Catalog link?',
 1522:             adminmail     => "Display Administrator's E-mail Address?",
 1523:             helpdesk      => 'Display "Contact Helpdesk" link',
 1524:             disallowlogin => "Login page requests redirected",
 1525:             hostid        => "Server",
 1526:             server        => "Redirect to:",
 1527:             serverpath    => "Path",
 1528:             custompath    => "Custom", 
 1529:             exempt        => "Exempt IP(s)",
 1530:             directlogin   => "No redirect",
 1531:             newuser       => "Link to create a user account",
 1532:             img           => "Header",
 1533:             logo          => "Main Logo",
 1534:             domlogo       => "Domain Logo",
 1535:             login         => "Log-in Header", 
 1536:             textcol       => "Text color",
 1537:             bgcol         => "Box color",
 1538:             bgs           => "Background colors",
 1539:             links         => "Link colors",
 1540:             font          => "Font color",
 1541:             pgbg          => "Header",
 1542:             mainbg        => "Page",
 1543:             sidebg        => "Login box",
 1544:             link          => "Link",
 1545:             alink         => "Active link",
 1546:             vlink         => "Visited link",
 1547:             headtag       => "Custom markup",
 1548:             action        => "Action",
 1549:             current       => "Current",
 1550:         );
 1551:     return %choices;
 1552: }
 1553: 
 1554: sub print_rolecolors {
 1555:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1556:     my %choices = &color_font_choices();
 1557:     my @bgs = ('pgbg','tabbg','sidebg');
 1558:     my @links = ('link','alink','vlink');
 1559:     my @images = ('img');
 1560:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1561:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1562:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1563:     my (%is_custom,%designs);
 1564:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1565:     if (ref($settings) eq 'HASH') {
 1566:         if (ref($settings->{$role}) eq 'HASH') {
 1567:             if ($settings->{$role}->{'img'} ne '') {
 1568:                 $designs{'img'} = $settings->{$role}->{'img'};
 1569:                 $is_custom{'img'} = 1;
 1570:             }
 1571:             if ($settings->{$role}->{'font'} ne '') {
 1572:                 $designs{'font'} = $settings->{$role}->{'font'};
 1573:                 $is_custom{'font'} = 1;
 1574:             }
 1575:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1576:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1577:                 $is_custom{'fontmenu'} = 1;
 1578:             }
 1579:             foreach my $item (@bgs) {
 1580:                 if ($settings->{$role}->{$item} ne '') {
 1581:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1582:                     $is_custom{$item} = 1;
 1583:                 }
 1584:             }
 1585:             foreach my $item (@links) {
 1586:                 if ($settings->{$role}->{$item} ne '') {
 1587:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1588:                     $is_custom{$item} = 1;
 1589:                 }
 1590:             }
 1591:         }
 1592:     } else {
 1593:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1594:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1595:             $is_custom{'img'} = 1;
 1596:         }
 1597:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1598:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1599:             $is_custom{'fontmenu'} = 1; 
 1600:         }
 1601:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1602:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1603:             $is_custom{'font'} = 1;
 1604:         }
 1605:         foreach my $item (@bgs) {
 1606:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1607:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1608:                 $is_custom{$item} = 1;
 1609:             
 1610:             }
 1611:         }
 1612:         foreach my $item (@links) {
 1613:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1614:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1615:                 $is_custom{$item} = 1;
 1616:             }
 1617:         }
 1618:     }
 1619:     my $itemcount = 1;
 1620:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 1621:     $datatable .= '</tr></table></td></tr>';
 1622:     return $datatable;
 1623: }
 1624: 
 1625: sub role_defaults {
 1626:     my ($role,$bgs,$links,$images,$logintext) = @_;
 1627:     my %defaults;
 1628:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 1629:         return %defaults;
 1630:     }
 1631:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1632:     if ($role eq 'login') {
 1633:         %defaults = (
 1634:                        font => $defaultdesign{$role.'.font'},
 1635:                     );
 1636:         if (ref($logintext) eq 'ARRAY') {
 1637:             foreach my $item (@{$logintext}) {
 1638:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 1639:             }
 1640:         }
 1641:         foreach my $item (@{$images}) {
 1642:             $defaults{'showlogo'}{$item} = 1;
 1643:         }
 1644:     } else {
 1645:         %defaults = (
 1646:                        img => $defaultdesign{$role.'.img'},
 1647:                        font => $defaultdesign{$role.'.font'},
 1648:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 1649:                     );
 1650:     }
 1651:     foreach my $item (@{$bgs}) {
 1652:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 1653:     }
 1654:     foreach my $item (@{$links}) {
 1655:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 1656:     }
 1657:     foreach my $item (@{$images}) {
 1658:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 1659:     }
 1660:     return %defaults;
 1661: }
 1662: 
 1663: sub display_color_options {
 1664:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 1665:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 1666:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1667:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1668:     my $datatable = '<tr'.$css_class.'>'.
 1669:         '<td>'.$choices->{'font'}.'</td>';
 1670:     if (!$is_custom->{'font'}) {
 1671:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 1672:     } else {
 1673:         $datatable .= '<td>&nbsp;</td>';
 1674:     }
 1675:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 1676: 
 1677:     $datatable .= '<td><span class="LC_nobreak">'.
 1678:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 1679:                   ' value="'.$current_color.'" />&nbsp;'.
 1680:                   '&nbsp;</span></td></tr>';
 1681:     unless ($role eq 'login') { 
 1682:         $datatable .= '<tr'.$css_class.'>'.
 1683:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 1684:         if (!$is_custom->{'fontmenu'}) {
 1685:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 1686:         } else {
 1687:             $datatable .= '<td>&nbsp;</td>';
 1688:         }
 1689: 	$current_color = $designs->{'fontmenu'} ?
 1690: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 1691:         $datatable .= '<td><span class="LC_nobreak">'.
 1692:                       '<input class="colorchooser" type="text" size="10" name="'
 1693: 		      .$role.'_fontmenu"'.
 1694:                       ' value="'.$current_color.'" />&nbsp;'.
 1695:                       '&nbsp;</span></td></tr>';
 1696:     }
 1697:     my $switchserver = &check_switchserver($dom,$confname);
 1698:     foreach my $img (@{$images}) {
 1699: 	$itemcount ++;
 1700:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1701:         $datatable .= '<tr'.$css_class.'>'.
 1702:                       '<td>'.$choices->{$img};
 1703:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors);
 1704:         if ($role eq 'login') {
 1705:             if ($img eq 'login') {
 1706:                 $login_hdr_pick =
 1707:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 1708:                 $logincolors =
 1709:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 1710:                                        $designs,$defaults);
 1711:             } elsif ($img ne 'domlogo') {
 1712:                 $datatable.= &logo_display_options($img,$defaults,$designs);
 1713:             }
 1714:         }
 1715:         $datatable .= '</td>';
 1716:         if ($designs->{$img} ne '') {
 1717:             $imgfile = $designs->{$img};
 1718: 	    $img_import = ($imgfile =~ m{^/adm/});
 1719:         } else {
 1720:             $imgfile = $defaults->{$img};
 1721:         }
 1722:         if ($imgfile) {
 1723:             my ($showfile,$fullsize);
 1724:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 1725:                 my $urldir = $1;
 1726:                 my $filename = $2;
 1727:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 1728:                 if (@info) {
 1729:                     my $thumbfile = 'tn-'.$filename;
 1730:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 1731:                     if (@thumb) {
 1732:                         $showfile = $urldir.'/'.$thumbfile;
 1733:                     } else {
 1734:                         $showfile = $imgfile;
 1735:                     }
 1736:                 } else {
 1737:                     $showfile = '';
 1738:                 }
 1739:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 1740:                 $showfile = $imgfile;
 1741:                 my $imgdir = $1;
 1742:                 my $filename = $2;
 1743:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 1744:                     $showfile = "/$imgdir/tn-".$filename;
 1745:                 } else {
 1746:                     my $input = $londocroot.$imgfile;
 1747:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 1748:                     if (!-e $output) {
 1749:                         my ($width,$height) = &thumb_dimensions();
 1750:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 1751:                         if ($fullwidth ne '' && $fullheight ne '') {
 1752:                             if ($fullwidth > $width && $fullheight > $height) { 
 1753:                                 my $size = $width.'x'.$height;
 1754:                                 my @args = ('convert','-sample',$size,$input,$output);
 1755:                                 system({$args[0]} @args);
 1756:                                 $showfile = "/$imgdir/tn-".$filename;
 1757:                             }
 1758:                         }
 1759:                     }
 1760:                 }
 1761:             }
 1762:             if ($showfile) {
 1763:                 if ($showfile =~ m{^/(adm|res)/}) {
 1764:                     if ($showfile =~ m{^/res/}) {
 1765:                         my $local_showfile =
 1766:                             &Apache::lonnet::filelocation('',$showfile);
 1767:                         &Apache::lonnet::repcopy($local_showfile);
 1768:                     }
 1769:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 1770:                 }
 1771:                 if ($imgfile) {
 1772:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 1773:                         if ($imgfile =~ m{^/res/}) {
 1774:                             my $local_imgfile =
 1775:                                 &Apache::lonnet::filelocation('',$imgfile);
 1776:                             &Apache::lonnet::repcopy($local_imgfile);
 1777:                         }
 1778:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 1779:                     } else {
 1780:                         $fullsize = $imgfile;
 1781:                     }
 1782:                 }
 1783:                 $datatable .= '<td>';
 1784:                 if ($img eq 'login') {
 1785:                     $datatable .= $login_hdr_pick;
 1786:                 } 
 1787:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 1788:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 1789:             } else {
 1790:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1791:                               &mt('Upload:').'<br />';
 1792:             }
 1793:         } else {
 1794:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1795:                           &mt('Upload:').'<br />';
 1796:         }
 1797:         if ($switchserver) {
 1798:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1799:         } else {
 1800:             if ($img ne 'login') { # suppress file selection for Log-in header
 1801:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 1802:             }
 1803:         }
 1804:         $datatable .= '</td></tr>';
 1805:     }
 1806:     $itemcount ++;
 1807:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1808:     $datatable .= '<tr'.$css_class.'>'.
 1809:                   '<td>'.$choices->{'bgs'}.'</td>';
 1810:     my $bgs_def;
 1811:     foreach my $item (@{$bgs}) {
 1812:         if (!$is_custom->{$item}) {
 1813:             $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>';
 1814:         }
 1815:     }
 1816:     if ($bgs_def) {
 1817:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 1818:     } else {
 1819:         $datatable .= '<td>&nbsp;</td>';
 1820:     }
 1821:     $datatable .= '<td class="LC_right_item">'.
 1822:                   '<table border="0"><tr>';
 1823: 
 1824:     foreach my $item (@{$bgs}) {
 1825:         $datatable .= '<td style="text-align: center">'.$choices->{$item};
 1826: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 1827:         if ($designs->{'bgs'}{$item}) {
 1828:             $datatable .= '&nbsp;';
 1829:         }
 1830:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 1831:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 1832:     }
 1833:     $datatable .= '</tr></table></td></tr>';
 1834:     $itemcount ++;
 1835:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1836:     $datatable .= '<tr'.$css_class.'>'.
 1837:                   '<td>'.$choices->{'links'}.'</td>';
 1838:     my $links_def;
 1839:     foreach my $item (@{$links}) {
 1840:         if (!$is_custom->{$item}) {
 1841:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 1842:         }
 1843:     }
 1844:     if ($links_def) {
 1845:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 1846:     } else {
 1847:         $datatable .= '<td>&nbsp;</td>';
 1848:     }
 1849:     $datatable .= '<td class="LC_right_item">'.
 1850:                   '<table border="0"><tr>';
 1851:     foreach my $item (@{$links}) {
 1852: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 1853:         $datatable .= '<td style="text-align: center">'.$choices->{$item}."\n";
 1854:         if ($designs->{'links'}{$item}) {
 1855:             $datatable.='&nbsp;';
 1856:         }
 1857:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 1858:                       '" /></td>';
 1859:     }
 1860:     $$rowtotal += $itemcount;
 1861:     return $datatable;
 1862: }
 1863: 
 1864: sub logo_display_options {
 1865:     my ($img,$defaults,$designs) = @_;
 1866:     my $checkedon;
 1867:     if (ref($defaults) eq 'HASH') {
 1868:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 1869:             if ($defaults->{'showlogo'}{$img}) {
 1870:                 $checkedon = 'checked="checked" ';     
 1871:             }
 1872:         } 
 1873:     }
 1874:     if (ref($designs) eq 'HASH') {
 1875:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 1876:             if (defined($designs->{'showlogo'}{$img})) {
 1877:                 if ($designs->{'showlogo'}{$img} == 0) {
 1878:                     $checkedon = '';
 1879:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 1880:                     $checkedon = 'checked="checked" ';
 1881:                 }
 1882:             }
 1883:         }
 1884:     }
 1885:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 1886:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 1887:            &mt('show').'</label>'."\n";
 1888: }
 1889: 
 1890: sub login_header_options  {
 1891:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 1892:     my $output = '';
 1893:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 1894:         $output .= &mt('Text default(s):').'<br />';
 1895:         if (!$is_custom->{'textcol'}) {
 1896:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 1897:                        '&nbsp;&nbsp;&nbsp;';
 1898:         }
 1899:         if (!$is_custom->{'bgcol'}) {
 1900:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 1901:                        '<span id="css_'.$role.'_font" style="background-color: '.
 1902:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 1903:         }
 1904:         $output .= '<br />';
 1905:     }
 1906:     $output .='<br />';
 1907:     return $output;
 1908: }
 1909: 
 1910: sub login_text_colors {
 1911:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 1912:     my $color_menu = '<table border="0"><tr>';
 1913:     foreach my $item (@{$logintext}) {
 1914:         $color_menu .= '<td style="text-align: center">'.$choices->{$item};
 1915:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 1916:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 1917:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 1918:     }
 1919:     $color_menu .= '</tr></table><br />';
 1920:     return $color_menu;
 1921: }
 1922: 
 1923: sub image_changes {
 1924:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 1925:     my $output;
 1926:     if ($img eq 'login') {
 1927:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 1928:     } elsif (!$is_custom) {
 1929:         if ($img ne 'domlogo') {
 1930:             $output = &mt('Default image:').'<br />';
 1931:         } else {
 1932:             $output = &mt('Default in use:').'<br />';
 1933:         }
 1934:     }
 1935:     if ($img ne 'login') {
 1936:         if ($img_import) {
 1937:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 1938:         }
 1939:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 1940:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 1941:         if ($is_custom) {
 1942:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 1943:                        '<input type="checkbox" name="'.
 1944:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 1945:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 1946:         } else {
 1947:             $output .= '<td class="LC_middle">'.$logincolors.&mt('Upload:').'<br />';
 1948:         }
 1949:     }
 1950:     return $output;
 1951: }
 1952: 
 1953: sub print_quotas {
 1954:     my ($dom,$settings,$rowtotal,$action) = @_;
 1955:     my $context;
 1956:     if ($action eq 'quotas') {
 1957:         $context = 'tools';
 1958:     } else {
 1959:         $context = $action;
 1960:     }
 1961:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 1962:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 1963:     my $typecount = 0;
 1964:     my ($css_class,%titles);
 1965:     if ($context eq 'requestcourses') {
 1966:         @usertools = ('official','unofficial','community','textbook','placement','lti');
 1967:         @options =('norequest','approval','validate','autolimit');
 1968:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 1969:         %titles = &courserequest_titles();
 1970:     } elsif ($context eq 'requestauthor') {
 1971:         @usertools = ('author');
 1972:         @options = ('norequest','approval','automatic');
 1973:         %titles = &authorrequest_titles();
 1974:     } else {
 1975:         @usertools = ('aboutme','blog','webdav','portfolio');
 1976:         %titles = &tool_titles();
 1977:     }
 1978:     if (ref($types) eq 'ARRAY') {
 1979:         foreach my $type (@{$types}) {
 1980:             my ($currdefquota,$currauthorquota);
 1981:             unless (($context eq 'requestcourses') ||
 1982:                     ($context eq 'requestauthor')) {
 1983:                 if (ref($settings) eq 'HASH') {
 1984:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 1985:                         $currdefquota = $settings->{defaultquota}->{$type};
 1986:                     } else {
 1987:                         $currdefquota = $settings->{$type};
 1988:                     }
 1989:                     if (ref($settings->{authorquota}) eq 'HASH') {
 1990:                         $currauthorquota = $settings->{authorquota}->{$type};
 1991:                     }
 1992:                 }
 1993:             }
 1994:             if (defined($usertypes->{$type})) {
 1995:                 $typecount ++;
 1996:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 1997:                 $datatable .= '<tr'.$css_class.'>'.
 1998:                               '<td>'.$usertypes->{$type}.'</td>'.
 1999:                               '<td class="LC_left_item">';
 2000:                 if ($context eq 'requestcourses') {
 2001:                     $datatable .= '<table><tr>';
 2002:                 }
 2003:                 my %cell;  
 2004:                 foreach my $item (@usertools) {
 2005:                     if ($context eq 'requestcourses') {
 2006:                         my ($curroption,$currlimit);
 2007:                         if (ref($settings) eq 'HASH') {
 2008:                             if (ref($settings->{$item}) eq 'HASH') {
 2009:                                 $curroption = $settings->{$item}->{$type};
 2010:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 2011:                                     $currlimit = $1; 
 2012:                                 }
 2013:                             }
 2014:                         }
 2015:                         if (!$curroption) {
 2016:                             $curroption = 'norequest';
 2017:                         }
 2018:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 2019:                         foreach my $option (@options) {
 2020:                             my $val = $option;
 2021:                             if ($option eq 'norequest') {
 2022:                                 $val = 0;  
 2023:                             }
 2024:                             if ($option eq 'validate') {
 2025:                                 my $canvalidate = 0;
 2026:                                 if (ref($validations{$item}) eq 'HASH') { 
 2027:                                     if ($validations{$item}{$type}) {
 2028:                                         $canvalidate = 1;
 2029:                                     }
 2030:                                 }
 2031:                                 next if (!$canvalidate);
 2032:                             }
 2033:                             my $checked = '';
 2034:                             if ($option eq $curroption) {
 2035:                                 $checked = ' checked="checked"';
 2036:                             } elsif ($option eq 'autolimit') {
 2037:                                 if ($curroption =~ /^autolimit/) {
 2038:                                     $checked = ' checked="checked"';
 2039:                                 }                       
 2040:                             } 
 2041:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 2042:                                   '<input type="radio" name="crsreq_'.$item.
 2043:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 2044:                                   $titles{$option}.'</label>';
 2045:                             if ($option eq 'autolimit') {
 2046:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2047:                                                 $item.'_limit_'.$type.'" size="1" '.
 2048:                                                 'value="'.$currlimit.'" />';
 2049:                             }
 2050:                             $cell{$item} .= '</span> ';
 2051:                             if ($option eq 'autolimit') {
 2052:                                 $cell{$item} .= $titles{'unlimited'};
 2053:                             }
 2054:                         }
 2055:                     } elsif ($context eq 'requestauthor') {
 2056:                         my $curroption;
 2057:                         if (ref($settings) eq 'HASH') {
 2058:                             $curroption = $settings->{$type};
 2059:                         }
 2060:                         if (!$curroption) {
 2061:                             $curroption = 'norequest';
 2062:                         }
 2063:                         foreach my $option (@options) {
 2064:                             my $val = $option;
 2065:                             if ($option eq 'norequest') {
 2066:                                 $val = 0;
 2067:                             }
 2068:                             my $checked = '';
 2069:                             if ($option eq $curroption) {
 2070:                                 $checked = ' checked="checked"';
 2071:                             }
 2072:                             $datatable .= '<span class="LC_nobreak"><label>'.
 2073:                                   '<input type="radio" name="authorreq_'.$type.
 2074:                                   '" value="'.$val.'"'.$checked.' />'.
 2075:                                   $titles{$option}.'</label></span>&nbsp; ';
 2076:                         }
 2077:                     } else {
 2078:                         my $checked = 'checked="checked" ';
 2079:                         if (ref($settings) eq 'HASH') {
 2080:                             if (ref($settings->{$item}) eq 'HASH') {
 2081:                                 if ($settings->{$item}->{$type} == 0) {
 2082:                                     $checked = '';
 2083:                                 } elsif ($settings->{$item}->{$type} == 1) {
 2084:                                     $checked =  'checked="checked" ';
 2085:                                 }
 2086:                             }
 2087:                         }
 2088:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2089:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 2090:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 2091:                                       '</label></span>&nbsp; ';
 2092:                     }
 2093:                 }
 2094:                 if ($context eq 'requestcourses') {
 2095:                     $datatable .= '</tr><tr>';
 2096:                     foreach my $item (@usertools) {
 2097:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 2098:                     }
 2099:                     $datatable .= '</tr></table>';
 2100:                 }
 2101:                 $datatable .= '</td>';
 2102:                 unless (($context eq 'requestcourses') ||
 2103:                         ($context eq 'requestauthor')) {
 2104:                     $datatable .= 
 2105:                               '<td class="LC_right_item">'.
 2106:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2107:                               '<input type="text" name="quota_'.$type.
 2108:                               '" value="'.$currdefquota.
 2109:                               '" size="5" /></span>'.('&nbsp;' x 2).
 2110:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2111:                               '<input type="text" name="authorquota_'.$type.
 2112:                               '" value="'.$currauthorquota.
 2113:                               '" size="5" /></span></td>';
 2114:                 }
 2115:                 $datatable .= '</tr>';
 2116:             }
 2117:         }
 2118:     }
 2119:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2120:         $defaultquota = '20';
 2121:         $authorquota = '500';
 2122:         if (ref($settings) eq 'HASH') {
 2123:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 2124:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 2125:             } elsif (defined($settings->{'default'})) {
 2126:                 $defaultquota = $settings->{'default'};
 2127:             }
 2128:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 2129:                 $authorquota = $settings->{'authorquota'}->{'default'};
 2130:             }
 2131:         }
 2132:     }
 2133:     $typecount ++;
 2134:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2135:     $datatable .= '<tr'.$css_class.'>'.
 2136:                   '<td>'.$othertitle.'</td>'.
 2137:                   '<td class="LC_left_item">';
 2138:     if ($context eq 'requestcourses') {
 2139:         $datatable .= '<table><tr>';
 2140:     }
 2141:     my %defcell;
 2142:     foreach my $item (@usertools) {
 2143:         if ($context eq 'requestcourses') {
 2144:             my ($curroption,$currlimit);
 2145:             if (ref($settings) eq 'HASH') {
 2146:                 if (ref($settings->{$item}) eq 'HASH') {
 2147:                     $curroption = $settings->{$item}->{'default'};
 2148:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2149:                         $currlimit = $1;
 2150:                     }
 2151:                 }
 2152:             }
 2153:             if (!$curroption) {
 2154:                 $curroption = 'norequest';
 2155:             }
 2156:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2157:             foreach my $option (@options) {
 2158:                 my $val = $option;
 2159:                 if ($option eq 'norequest') {
 2160:                     $val = 0;
 2161:                 }
 2162:                 if ($option eq 'validate') {
 2163:                     my $canvalidate = 0;
 2164:                     if (ref($validations{$item}) eq 'HASH') {
 2165:                         if ($validations{$item}{'default'}) {
 2166:                             $canvalidate = 1;
 2167:                         }
 2168:                     }
 2169:                     next if (!$canvalidate);
 2170:                 }
 2171:                 my $checked = '';
 2172:                 if ($option eq $curroption) {
 2173:                     $checked = ' checked="checked"';
 2174:                 } elsif ($option eq 'autolimit') {
 2175:                     if ($curroption =~ /^autolimit/) {
 2176:                         $checked = ' checked="checked"';
 2177:                     }
 2178:                 }
 2179:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2180:                                   '<input type="radio" name="crsreq_'.$item.
 2181:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2182:                                   $titles{$option}.'</label>';
 2183:                 if ($option eq 'autolimit') {
 2184:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2185:                                        $item.'_limit_default" size="1" '.
 2186:                                        'value="'.$currlimit.'" />';
 2187:                 }
 2188:                 $defcell{$item} .= '</span> ';
 2189:                 if ($option eq 'autolimit') {
 2190:                     $defcell{$item} .= $titles{'unlimited'};
 2191:                 }
 2192:             }
 2193:         } elsif ($context eq 'requestauthor') {
 2194:             my $curroption;
 2195:             if (ref($settings) eq 'HASH') {
 2196:                 $curroption = $settings->{'default'};
 2197:             }
 2198:             if (!$curroption) {
 2199:                 $curroption = 'norequest';
 2200:             }
 2201:             foreach my $option (@options) {
 2202:                 my $val = $option;
 2203:                 if ($option eq 'norequest') {
 2204:                     $val = 0;
 2205:                 }
 2206:                 my $checked = '';
 2207:                 if ($option eq $curroption) {
 2208:                     $checked = ' checked="checked"';
 2209:                 }
 2210:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2211:                               '<input type="radio" name="authorreq_default"'.
 2212:                               ' value="'.$val.'"'.$checked.' />'.
 2213:                               $titles{$option}.'</label></span>&nbsp; ';
 2214:             }
 2215:         } else {
 2216:             my $checked = 'checked="checked" ';
 2217:             if (ref($settings) eq 'HASH') {
 2218:                 if (ref($settings->{$item}) eq 'HASH') {
 2219:                     if ($settings->{$item}->{'default'} == 0) {
 2220:                         $checked = '';
 2221:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2222:                         $checked = 'checked="checked" ';
 2223:                     }
 2224:                 }
 2225:             }
 2226:             $datatable .= '<span class="LC_nobreak"><label>'.
 2227:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2228:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2229:                           '</label></span>&nbsp; ';
 2230:         }
 2231:     }
 2232:     if ($context eq 'requestcourses') {
 2233:         $datatable .= '</tr><tr>';
 2234:         foreach my $item (@usertools) {
 2235:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2236:         }
 2237:         $datatable .= '</tr></table>';
 2238:     }
 2239:     $datatable .= '</td>';
 2240:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2241:         $datatable .= '<td class="LC_right_item">'.
 2242:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2243:                       '<input type="text" name="defaultquota" value="'.
 2244:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2245:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2246:                       '<input type="text" name="authorquota" value="'.
 2247:                       $authorquota.'" size="5" /></span></td>';
 2248:     }
 2249:     $datatable .= '</tr>';
 2250:     $typecount ++;
 2251:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2252:     $datatable .= '<tr'.$css_class.'>'.
 2253:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2254:     if ($context eq 'requestcourses') {
 2255:         $datatable .= &mt('(overrides affiliation, if set)').
 2256:                       '</td>'.
 2257:                       '<td class="LC_left_item">'.
 2258:                       '<table><tr>';
 2259:     } else {
 2260:         $datatable .= &mt('(overrides affiliation, if checked)').
 2261:                       '</td>'.
 2262:                       '<td class="LC_left_item" colspan="2">'.
 2263:                       '<br />';
 2264:     }
 2265:     my %advcell;
 2266:     foreach my $item (@usertools) {
 2267:         if ($context eq 'requestcourses') {
 2268:             my ($curroption,$currlimit);
 2269:             if (ref($settings) eq 'HASH') {
 2270:                 if (ref($settings->{$item}) eq 'HASH') {
 2271:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2272:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2273:                         $currlimit = $1;
 2274:                     }
 2275:                 }
 2276:             }
 2277:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2278:             my $checked = '';
 2279:             if ($curroption eq '') {
 2280:                 $checked = ' checked="checked"';
 2281:             }
 2282:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2283:                                '<input type="radio" name="crsreq_'.$item.
 2284:                                '__LC_adv" value=""'.$checked.' />'.
 2285:                                &mt('No override set').'</label></span>&nbsp; ';
 2286:             foreach my $option (@options) {
 2287:                 my $val = $option;
 2288:                 if ($option eq 'norequest') {
 2289:                     $val = 0;
 2290:                 }
 2291:                 if ($option eq 'validate') {
 2292:                     my $canvalidate = 0;
 2293:                     if (ref($validations{$item}) eq 'HASH') {
 2294:                         if ($validations{$item}{'_LC_adv'}) {
 2295:                             $canvalidate = 1;
 2296:                         }
 2297:                     }
 2298:                     next if (!$canvalidate);
 2299:                 }
 2300:                 my $checked = '';
 2301:                 if ($val eq $curroption) {
 2302:                     $checked = ' checked="checked"';
 2303:                 } elsif ($option eq 'autolimit') {
 2304:                     if ($curroption =~ /^autolimit/) {
 2305:                         $checked = ' checked="checked"';
 2306:                     }
 2307:                 }
 2308:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2309:                                   '<input type="radio" name="crsreq_'.$item.
 2310:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2311:                                   $titles{$option}.'</label>';
 2312:                 if ($option eq 'autolimit') {
 2313:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2314:                                        $item.'_limit__LC_adv" size="1" '.
 2315:                                        'value="'.$currlimit.'" />';
 2316:                 }
 2317:                 $advcell{$item} .= '</span> ';
 2318:                 if ($option eq 'autolimit') {
 2319:                     $advcell{$item} .= $titles{'unlimited'};
 2320:                 }
 2321:             }
 2322:         } elsif ($context eq 'requestauthor') {
 2323:             my $curroption;
 2324:             if (ref($settings) eq 'HASH') {
 2325:                 $curroption = $settings->{'_LC_adv'};
 2326:             }
 2327:             my $checked = '';
 2328:             if ($curroption eq '') {
 2329:                 $checked = ' checked="checked"';
 2330:             }
 2331:             $datatable .= '<span class="LC_nobreak"><label>'.
 2332:                           '<input type="radio" name="authorreq__LC_adv"'.
 2333:                           ' value=""'.$checked.' />'.
 2334:                           &mt('No override set').'</label></span>&nbsp; ';
 2335:             foreach my $option (@options) {
 2336:                 my $val = $option;
 2337:                 if ($option eq 'norequest') {
 2338:                     $val = 0;
 2339:                 }
 2340:                 my $checked = '';
 2341:                 if ($val eq $curroption) {
 2342:                     $checked = ' checked="checked"';
 2343:                 }
 2344:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2345:                               '<input type="radio" name="authorreq__LC_adv"'.
 2346:                               ' value="'.$val.'"'.$checked.' />'.
 2347:                               $titles{$option}.'</label></span>&nbsp; ';
 2348:             }
 2349:         } else {
 2350:             my $checked = 'checked="checked" ';
 2351:             if (ref($settings) eq 'HASH') {
 2352:                 if (ref($settings->{$item}) eq 'HASH') {
 2353:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2354:                         $checked = '';
 2355:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2356:                         $checked = 'checked="checked" ';
 2357:                     }
 2358:                 }
 2359:             }
 2360:             $datatable .= '<span class="LC_nobreak"><label>'.
 2361:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2362:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2363:                           '</label></span>&nbsp; ';
 2364:         }
 2365:     }
 2366:     if ($context eq 'requestcourses') {
 2367:         $datatable .= '</tr><tr>';
 2368:         foreach my $item (@usertools) {
 2369:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2370:         }
 2371:         $datatable .= '</tr></table>';
 2372:     }
 2373:     $datatable .= '</td></tr>';
 2374:     $$rowtotal += $typecount;
 2375:     return $datatable;
 2376: }
 2377: 
 2378: sub print_requestmail {
 2379:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2380:     my ($now,$datatable,%currapp);
 2381:     $now = time;
 2382:     if (ref($settings) eq 'HASH') {
 2383:         if (ref($settings->{'notify'}) eq 'HASH') {
 2384:             if ($settings->{'notify'}{'approval'} ne '') {
 2385:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2386:             }
 2387:         }
 2388:     }
 2389:     my $numinrow = 2;
 2390:     my $css_class;
 2391:     if ($$rowtotal%2) {
 2392:         $css_class = 'LC_odd_row';
 2393:     }
 2394:     if ($customcss) {
 2395:         $css_class .= " $customcss";
 2396:     }
 2397:     $css_class =~ s/^\s+//;
 2398:     if ($css_class) {
 2399:         $css_class = ' class="'.$css_class.'"';
 2400:     }
 2401:     if ($rowstyle) {
 2402:         $css_class .= ' style="'.$rowstyle.'"';
 2403:     }
 2404:     my $text;
 2405:     if ($action eq 'requestcourses') {
 2406:         $text = &mt('Receive notification of course requests requiring approval');
 2407:     } elsif ($action eq 'requestauthor') {
 2408:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2409:     } else {
 2410:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2411:     }
 2412:     $datatable = '<tr'.$css_class.'>'.
 2413:                  ' <td>'.$text.'</td>'.
 2414:                  ' <td class="LC_left_item">';
 2415:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2416:                                                  $action.'notifyapproval',%currapp);
 2417:     if ($numdc > 0) {
 2418:         $datatable .= $table;
 2419:     } else {
 2420:         $datatable .= &mt('There are no active Domain Coordinators');
 2421:     }
 2422:     $datatable .='</td></tr>';
 2423:     return $datatable;
 2424: }
 2425: 
 2426: sub print_studentcode {
 2427:     my ($settings,$rowtotal) = @_;
 2428:     my $rownum = 0; 
 2429:     my ($output,%current);
 2430:     my @crstypes = ('official','unofficial','community','textbook','placement','lti');
 2431:     if (ref($settings) eq 'HASH') {
 2432:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2433:             foreach my $type (@crstypes) {
 2434:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2435:             }
 2436:         }
 2437:     }
 2438:     $output .= '<tr>'.
 2439:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2440:                '<td class="LC_left_item">';
 2441:     foreach my $type (@crstypes) {
 2442:         my $check = ' ';
 2443:         if ($current{$type}) {
 2444:             $check = ' checked="checked" ';
 2445:         }
 2446:         $output .= '<span class="LC_nobreak"><label>'.
 2447:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2448:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2449:     }
 2450:     $output .= '</td></tr>';
 2451:     $$rowtotal ++;
 2452:     return $output;
 2453: }
 2454: 
 2455: sub print_textbookcourses {
 2456:     my ($dom,$type,$settings,$rowtotal) = @_;
 2457:     my $rownum = 0;
 2458:     my $css_class;
 2459:     my $itemcount = 1;
 2460:     my $maxnum = 0;
 2461:     my $bookshash;
 2462:     if (ref($settings) eq 'HASH') {
 2463:         $bookshash = $settings->{$type};
 2464:     }
 2465:     my %ordered;
 2466:     if (ref($bookshash) eq 'HASH') {
 2467:         foreach my $item (keys(%{$bookshash})) {
 2468:             if (ref($bookshash->{$item}) eq 'HASH') {
 2469:                 my $num = $bookshash->{$item}{'order'};
 2470:                 $ordered{$num} = $item;
 2471:             }
 2472:         }
 2473:     }
 2474:     my $confname = $dom.'-domainconfig';
 2475:     my $switchserver = &check_switchserver($dom,$confname);
 2476:     my $maxnum = scalar(keys(%ordered));
 2477:     my $datatable;
 2478:     if (keys(%ordered)) {
 2479:         my @items = sort { $a <=> $b } keys(%ordered);
 2480:         for (my $i=0; $i<@items; $i++) {
 2481:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2482:             my $key = $ordered{$items[$i]};
 2483:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2484:             my $coursetitle = $coursehash{'description'};
 2485:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2486:             if (ref($bookshash->{$key}) eq 'HASH') {
 2487:                 $subject = $bookshash->{$key}->{'subject'};
 2488:                 $title = $bookshash->{$key}->{'title'};
 2489:                 if ($type eq 'textbooks') {
 2490:                     $publisher = $bookshash->{$key}->{'publisher'};
 2491:                     $author = $bookshash->{$key}->{'author'};
 2492:                     $image = $bookshash->{$key}->{'image'};
 2493:                     if ($image ne '') {
 2494:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2495:                         my $imagethumb = "$path/tn-".$imagefile;
 2496:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2497:                     }
 2498:                 }
 2499:             }
 2500:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2501:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2502:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2503:             for (my $k=0; $k<=$maxnum; $k++) {
 2504:                 my $vpos = $k+1;
 2505:                 my $selstr;
 2506:                 if ($k == $i) {
 2507:                     $selstr = ' selected="selected" ';
 2508:                 }
 2509:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2510:             }
 2511:             $datatable .= '</select>'.('&nbsp;'x2).
 2512:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2513:                 &mt('Delete?').'</label></span></td>'.
 2514:                 '<td colspan="2">'.
 2515:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2516:                 ('&nbsp;'x2).
 2517:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2518:             if ($type eq 'textbooks') {
 2519:                 $datatable .= ('&nbsp;'x2).
 2520:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2521:                               ('&nbsp;'x2).
 2522:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2523:                               ('&nbsp;'x2).
 2524:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2525:                 if ($image) {
 2526:                     $datatable .= $imgsrc.
 2527:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2528:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2529:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2530:                 }
 2531:                 if ($switchserver) {
 2532:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2533:                 } else {
 2534:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2535:                 }
 2536:             }
 2537:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2538:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2539:                           $coursetitle.'</span></td></tr>'."\n";
 2540:             $itemcount ++;
 2541:         }
 2542:     }
 2543:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2544:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2545:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2546:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2547:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2548:     for (my $k=0; $k<$maxnum+1; $k++) {
 2549:         my $vpos = $k+1;
 2550:         my $selstr;
 2551:         if ($k == $maxnum) {
 2552:             $selstr = ' selected="selected" ';
 2553:         }
 2554:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2555:     }
 2556:     $datatable .= '</select>&nbsp;'."\n".
 2557:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2558:                   '<td colspan="2">'.
 2559:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2560:                   ('&nbsp;'x2).
 2561:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2562:                   ('&nbsp;'x2);
 2563:     if ($type eq 'textbooks') {
 2564:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2565:                       ('&nbsp;'x2).
 2566:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2567:                       ('&nbsp;'x2).
 2568:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2569:         if ($switchserver) {
 2570:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2571:         } else {
 2572:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2573:         }
 2574:         $datatable .= '</span>'."\n";
 2575:     }
 2576:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2577:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2578:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2579:                   &Apache::loncommon::selectcourse_link
 2580:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2581:                   '</span></td>'."\n".
 2582:                   '</tr>'."\n";
 2583:     $itemcount ++;
 2584:     return $datatable;
 2585: }
 2586: 
 2587: sub textbookcourses_javascript {
 2588:     my ($settings) = @_;
 2589:     return unless(ref($settings) eq 'HASH');
 2590:     my (%ordered,%total,%jstext);
 2591:     foreach my $type ('textbooks','templates') {
 2592:         $total{$type} = 0;
 2593:         if (ref($settings->{$type}) eq 'HASH') {
 2594:             foreach my $item (keys(%{$settings->{$type}})) {
 2595:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2596:                     my $num = $settings->{$type}->{$item}{'order'};
 2597:                     $ordered{$type}{$num} = $item;
 2598:                 }
 2599:             }
 2600:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2601:         }
 2602:         my @jsarray = ();
 2603:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 2604:             push(@jsarray,$ordered{$type}{$item});
 2605:         }
 2606:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 2607:     }
 2608:     return <<"ENDSCRIPT";
 2609: <script type="text/javascript">
 2610: // <![CDATA[
 2611: function reorderBooks(form,item,caller) {
 2612:     var changedVal;
 2613: $jstext{'textbooks'};
 2614: $jstext{'templates'};
 2615:     var newpos;
 2616:     var maxh;
 2617:     if (caller == 'textbooks') {  
 2618:         newpos = 'textbooks_addbook_pos';
 2619:         maxh = 1 + $total{'textbooks'};
 2620:     } else {
 2621:         newpos = 'templates_addbook_pos';
 2622:         maxh = 1 + $total{'templates'};
 2623:     }
 2624:     var current = new Array;
 2625:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2626:     if (item == newpos) {
 2627:         changedVal = newitemVal;
 2628:     } else {
 2629:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2630:         current[newitemVal] = newpos;
 2631:     }
 2632:     if (caller == 'textbooks') {
 2633:         for (var i=0; i<textbooks.length; i++) {
 2634:             var elementName = 'textbooks_'+textbooks[i];
 2635:             if (elementName != item) {
 2636:                 if (form.elements[elementName]) {
 2637:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2638:                     current[currVal] = elementName;
 2639:                 }
 2640:             }
 2641:         }
 2642:     }
 2643:     if (caller == 'templates') {
 2644:         for (var i=0; i<templates.length; i++) {
 2645:             var elementName = 'templates_'+templates[i];
 2646:             if (elementName != item) {
 2647:                 if (form.elements[elementName]) {
 2648:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2649:                     current[currVal] = elementName;
 2650:                 }
 2651:             }
 2652:         }
 2653:     }
 2654:     var oldVal;
 2655:     for (var j=0; j<maxh; j++) {
 2656:         if (current[j] == undefined) {
 2657:             oldVal = j;
 2658:         }
 2659:     }
 2660:     if (oldVal < changedVal) {
 2661:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2662:            var elementName = current[k];
 2663:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2664:         }
 2665:     } else {
 2666:         for (var k=changedVal; k<oldVal; k++) {
 2667:             var elementName = current[k];
 2668:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2669:         }
 2670:     }
 2671:     return;
 2672: }
 2673: 
 2674: // ]]>
 2675: </script>
 2676: 
 2677: ENDSCRIPT
 2678: }
 2679: 
 2680: sub ltitools_javascript {
 2681:     my ($settings) = @_;
 2682:     my $togglejs = &ltitools_toggle_js();
 2683:     unless (ref($settings) eq 'HASH') {
 2684:         return $togglejs;
 2685:     }
 2686:     my (%ordered,$total,%jstext);
 2687:     $total = 0;
 2688:     foreach my $item (keys(%{$settings})) {
 2689:         if (ref($settings->{$item}) eq 'HASH') {
 2690:             my $num = $settings->{$item}{'order'};
 2691:             $ordered{$num} = $item;
 2692:         }
 2693:     }
 2694:     $total = scalar(keys(%{$settings}));
 2695:     my @jsarray = ();
 2696:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 2697:         push(@jsarray,$ordered{$item});
 2698:     }
 2699:     my $jstext = '    var ltitools = Array('."'".join("','",@jsarray)."'".');'."\n";
 2700:     return <<"ENDSCRIPT";
 2701: <script type="text/javascript">
 2702: // <![CDATA[
 2703: function reorderLTITools(form,item) {
 2704:     var changedVal;
 2705: $jstext
 2706:     var newpos = 'ltitools_add_pos';
 2707:     var maxh = 1 + $total;
 2708:     var current = new Array;
 2709:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2710:     if (item == newpos) {
 2711:         changedVal = newitemVal;
 2712:     } else {
 2713:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2714:         current[newitemVal] = newpos;
 2715:     }
 2716:     for (var i=0; i<ltitools.length; i++) {
 2717:         var elementName = 'ltitools_'+ltitools[i];
 2718:         if (elementName != item) {
 2719:             if (form.elements[elementName]) {
 2720:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2721:                 current[currVal] = elementName;
 2722:             }
 2723:         }
 2724:     }
 2725:     var oldVal;
 2726:     for (var j=0; j<maxh; j++) {
 2727:         if (current[j] == undefined) {
 2728:             oldVal = j;
 2729:         }
 2730:     }
 2731:     if (oldVal < changedVal) {
 2732:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2733:            var elementName = current[k];
 2734:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2735:         }
 2736:     } else {
 2737:         for (var k=changedVal; k<oldVal; k++) {
 2738:             var elementName = current[k];
 2739:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2740:         }
 2741:     }
 2742:     return;
 2743: }
 2744: 
 2745: // ]]>
 2746: </script>
 2747: 
 2748: $togglejs
 2749: 
 2750: ENDSCRIPT
 2751: }
 2752: 
 2753: sub ltitools_toggle_js {
 2754:     return <<"ENDSCRIPT";
 2755: <script type="text/javascript">
 2756: // <![CDATA[
 2757: 
 2758: function toggleLTITools(form,setting,item) {
 2759:     var radioname = '';
 2760:     var divid = '';
 2761:     if ((setting == 'passback') || (setting == 'roster')) {
 2762:         radioname = 'ltitools_'+setting+'_'+item;
 2763:         divid = 'ltitools_'+setting+'time_'+item;
 2764:         var num = form.elements[radioname].length;
 2765:         if (num) {
 2766:             var setvis = '';
 2767:             for (var i=0; i<num; i++) {
 2768:                 if (form.elements[radioname][i].checked) {
 2769:                     if (form.elements[radioname][i].value == '1') {
 2770:                         if (document.getElementById(divid)) {
 2771:                             document.getElementById(divid).style.display = 'inline-block';
 2772:                         }
 2773:                         setvis = 1;
 2774:                     }
 2775:                     break;
 2776:                 }
 2777:             }
 2778:         }
 2779:         if (!setvis) {
 2780:             if (document.getElementById(divid)) {
 2781:                 document.getElementById(divid).style.display = 'none';
 2782:             }
 2783:         }
 2784:     }
 2785:     if (setting == 'user') {
 2786:         divid = 'ltitools_'+setting+'_div_'+item;
 2787:         var checkid = 'ltitools_'+setting+'_field_'+item;
 2788:         if (document.getElementById(divid)) {
 2789:             if (document.getElementById(checkid)) {
 2790:                 if (document.getElementById(checkid).checked) {
 2791:                     document.getElementById(divid).style.display = 'inline-block';
 2792:                 } else {
 2793:                     document.getElementById(divid).style.display = 'none';
 2794:                 }
 2795:             }
 2796:         }
 2797:     }
 2798:     return;
 2799: }
 2800: // ]]>
 2801: </script>
 2802: 
 2803: ENDSCRIPT
 2804: }
 2805: 
 2806: sub lti_javascript {
 2807:     my ($settings) = @_;
 2808:     my $togglejs = &lti_toggle_js();
 2809:     unless (ref($settings) eq 'HASH') {
 2810:         return $togglejs;
 2811:     }
 2812:     my (%ordered,$total,%jstext);
 2813:     $total = 0;
 2814:     foreach my $item (keys(%{$settings})) {
 2815:         if (ref($settings->{$item}) eq 'HASH') {
 2816:             my $num = $settings->{$item}{'order'};
 2817:             $ordered{$num} = $item;
 2818:         }
 2819:     }
 2820:     $total = scalar(keys(%{$settings}));
 2821:     my @jsarray = ();
 2822:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 2823:         push(@jsarray,$ordered{$item});
 2824:     }
 2825:     my $jstext = '    var lti = Array('."'".join("','",@jsarray)."'".');'."\n";
 2826:     return <<"ENDSCRIPT";
 2827: <script type="text/javascript">
 2828: // <![CDATA[
 2829: function reorderLTI(form,item) {
 2830:     var changedVal;
 2831: $jstext
 2832:     var newpos = 'lti_pos_add';
 2833:     var maxh = 1 + $total;
 2834:     var current = new Array;
 2835:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2836:     if (item == newpos) {
 2837:         changedVal = newitemVal;
 2838:     } else {
 2839:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2840:         current[newitemVal] = newpos;
 2841:     }
 2842:     for (var i=0; i<lti.length; i++) {
 2843:         var elementName = 'lti_pos_'+lti[i];
 2844:         if (elementName != item) {
 2845:             if (form.elements[elementName]) {
 2846:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2847:                 current[currVal] = elementName;
 2848:             }
 2849:         }
 2850:     }
 2851:     var oldVal;
 2852:     for (var j=0; j<maxh; j++) {
 2853:         if (current[j] == undefined) {
 2854:             oldVal = j;
 2855:         }
 2856:     }
 2857:     if (oldVal < changedVal) {
 2858:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2859:            var elementName = current[k];
 2860:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2861:         }
 2862:     } else {
 2863:         for (var k=changedVal; k<oldVal; k++) {
 2864:             var elementName = current[k];
 2865:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2866:         }
 2867:     }
 2868:     return;
 2869: }
 2870: // ]]>
 2871: </script>
 2872: 
 2873: $togglejs
 2874: 
 2875: ENDSCRIPT
 2876: }
 2877: 
 2878: sub lti_toggle_js {
 2879:     my %lcauthparmtext = &Apache::lonlocal::texthash (
 2880:                             localauth => 'Local auth argument',
 2881:                             krb       => 'Kerberos domain',
 2882:                          );
 2883:     return <<"ENDSCRIPT";
 2884: <script type="text/javascript">
 2885: // <![CDATA[
 2886: 
 2887: function toggleLTI(form,setting,item) {
 2888:     if (setting == 'requser') {
 2889:         var fieldsets = document.getElementsByClassName('ltioption_'+item);
 2890:         if (fieldsets.length) {
 2891:             var radioname = 'lti_'+setting+'_'+item;
 2892:             var num = form.elements[radioname].length;
 2893:             if (num) {
 2894:                 var setvis = '';
 2895:                 for (var i=0; i<num; i++) {
 2896:                     if (form.elements[radioname][i].checked) {
 2897:                         if (form.elements[radioname][i].value == '1') {
 2898:                            setvis = 1;
 2899:                            break;
 2900:                         }
 2901:                     }
 2902:                 }
 2903:                 for (var j=0; j<fieldsets.length; j++) {
 2904:                     if (setvis) {
 2905:                         fieldsets[j].style.display = 'block';
 2906:                     } else {
 2907:                         fieldsets[j].style.display = 'none';
 2908:                     }
 2909:                 }
 2910:             }
 2911:         }
 2912:     } else if ((setting == 'user') || (setting == 'crs') || (setting == 'passback') || (setting == 'callback')) {
 2913:         var radioname = '';
 2914:         var divid = '';
 2915:         if (setting == 'user') {
 2916:             radioname = 'lti_mapuser_'+item;
 2917:             divid = 'lti_userfield_'+item;
 2918:         } else if (setting == 'crs') {
 2919:             radioname = 'lti_mapcrs_'+item;
 2920:             divid = 'lti_crsfield_'+item;
 2921:         } else if (setting == 'callback') {
 2922:             radioname = 'lti_callback_'+item;
 2923:             divid = 'lti_callbackfield_'+item;
 2924:         } else {
 2925:             radioname = 'lti_passback_'+item;
 2926:             divid =  'lti_passback_'+item;
 2927:         }
 2928:         var num = form.elements[radioname].length;
 2929:         if (num) {
 2930:             var setvis = '';
 2931:             for (var i=0; i<num; i++) {
 2932:                if (form.elements[radioname][i].checked) {
 2933:                    if ((setting == 'passback') || (setting == 'callback')) {
 2934:                        if (form.elements[radioname][i].value == '1') {
 2935:                            if (document.getElementById(divid)) {
 2936:                                document.getElementById(divid).style.display = 'inline-block';
 2937:                            }
 2938:                            setvis = 1;
 2939:                            break;
 2940:                        }
 2941:                    } else {
 2942:                        if (form.elements[radioname][i].value == 'other') {
 2943:                            if (document.getElementById(divid)) {
 2944:                                document.getElementById(divid).style.display = 'inline-block';
 2945:                            }
 2946:                            setvis = 1;
 2947:                            break;
 2948:                        }
 2949:                    }
 2950:                } 
 2951:             }
 2952:             if (!setvis) {
 2953:                 if (document.getElementById(divid)) {
 2954:                     document.getElementById(divid).style.display = 'none';
 2955:                 }
 2956:             }
 2957:         }
 2958:     } else if ((setting == 'sec') || (setting == 'secsrc')) {
 2959:         var numsec = form.elements['lti_crssec_'+item].length;
 2960:         if (numsec) {
 2961:             var setvis = '';
 2962:             for (var i=0; i<numsec; i++) {
 2963:                 if (form.elements['lti_crssec_'+item][i].checked) {
 2964:                     if (form.elements['lti_crssec_'+item][i].value == '1') {
 2965:                         if (document.getElementById('lti_crssecfield_'+item)) {
 2966:                             document.getElementById('lti_crssecfield_'+item).style.display = 'inline-block';
 2967:                             setvis = 1;
 2968:                             var numsrcsec = form.elements['lti_crssecsrc_'+item].length;
 2969:                             if (numsrcsec) {
 2970:                                 var setsrcvis = '';
 2971:                                 for (var j=0; j<numsrcsec; j++) {
 2972:                                     if (form.elements['lti_crssecsrc_'+item][j].checked) {
 2973:                                         if (form.elements['lti_crssecsrc_'+item][j].value == 'other') {
 2974:                                             if (document.getElementById('lti_secsrcfield_'+item)) {
 2975:                                                 document.getElementById('lti_secsrcfield_'+item).style.display = 'inline-block';
 2976:                                                 setsrcvis = 1;
 2977:                                             }
 2978:                                         }
 2979:                                     }
 2980:                                 }
 2981:                                 if (!setsrcvis) {
 2982:                                     if (document.getElementById('lti_secsrcfield_'+item)) {
 2983:                                         document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 2984:                                     }
 2985:                                 }
 2986:                             }
 2987:                         }
 2988:                     }
 2989:                 }
 2990:             }
 2991:             if (!setvis) {
 2992:                 if (document.getElementById('lti_crssecfield_'+item)) {
 2993:                     document.getElementById('lti_crssecfield_'+item).style.display = 'none';
 2994:                 }
 2995:                 if (document.getElementById('lti_secsrcfield_'+item)) {
 2996:                     document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 2997:                 }
 2998:             }
 2999:         }
 3000:     } else if (setting == 'lcauth') {
 3001:         var numauth = form.elements['lti_lcauth_'+item].length;
 3002:         if (numauth) {
 3003:             for (var i=0; i<numauth; i++) {
 3004:                 if (form.elements['lti_lcauth_'+item][i].checked) {
 3005:                     if (document.getElementById('lti_'+setting+'_parmrow_'+item)) {
 3006:                         if ((form.elements['lti_'+setting+'_'+item][i].value == 'internal') || (form.elements['lti_'+setting+'_'+item][i].value == 'lti')) {
 3007:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'none';
 3008:                         } else {
 3009:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'table-row';
 3010:                             if (document.getElementById('lti_'+setting+'_parmtext_'+item)) {
 3011:                                 if (form.elements['lti_'+setting+'_'+item][i].value == 'localauth') {
 3012:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'localauth'}";
 3013:                                 } else {
 3014:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'krb'}";
 3015:                                 }
 3016:                             }
 3017:                         }
 3018:                     }
 3019:                 }
 3020:             }
 3021:         }
 3022:     } else if (setting == 'lcmenu') {
 3023:         var menus = new Array('lti_topmenu_'+item,'lti_inlinemenu_'+item);
 3024:         var divid = 'lti_menufield_'+item;
 3025:         var setvis = '';
 3026:         for (var i=0; i<menus.length; i++) {
 3027:             var radioname = menus[i];  
 3028:             var num = form.elements[radioname].length;
 3029:             if (num) {
 3030:                 for (var j=0; j<num; j++) {
 3031:                     if (form.elements[radioname][j].checked) {
 3032:                         if (form.elements[radioname][j].value == '1') {
 3033:                             if (document.getElementById(divid)) {
 3034:                                 document.getElementById(divid).style.display = 'inline-block';
 3035:                             }
 3036:                             setvis = 1;
 3037:                             break;
 3038:                         }
 3039:                     }
 3040:                 }
 3041:             }
 3042:             if (setvis == 1) {
 3043:                 break;
 3044:             }
 3045:         }
 3046:         if (!setvis) {
 3047:             if (document.getElementById(divid)) {
 3048:                 document.getElementById(divid).style.display = 'none';
 3049:             }
 3050:         }
 3051:     }
 3052:     return;
 3053: }
 3054: // ]]>
 3055: </script>
 3056: 
 3057: ENDSCRIPT
 3058: }
 3059: 
 3060: sub print_autoenroll {
 3061:     my ($dom,$settings,$rowtotal) = @_;
 3062:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 3063:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,$failsafe);
 3064:     if (ref($settings) eq 'HASH') {
 3065:         if (exists($settings->{'run'})) {
 3066:             if ($settings->{'run'} eq '0') {
 3067:                 $runoff = ' checked="checked" ';
 3068:                 $runon = ' ';
 3069:             } else {
 3070:                 $runon = ' checked="checked" ';
 3071:                 $runoff = ' ';
 3072:             }
 3073:         } else {
 3074:             if ($autorun) {
 3075:                 $runon = ' checked="checked" ';
 3076:                 $runoff = ' ';
 3077:             } else {
 3078:                 $runoff = ' checked="checked" ';
 3079:                 $runon = ' ';
 3080:             }
 3081:         }
 3082:         if (exists($settings->{'co-owners'})) {
 3083:             if ($settings->{'co-owners'} eq '0') {
 3084:                 $coownersoff = ' checked="checked" ';
 3085:                 $coownerson = ' ';
 3086:             } else {
 3087:                 $coownerson = ' checked="checked" ';
 3088:                 $coownersoff = ' ';
 3089:             }
 3090:         } else {
 3091:             $coownersoff = ' checked="checked" ';
 3092:             $coownerson = ' ';
 3093:         }
 3094:         if (exists($settings->{'sender_domain'})) {
 3095:             $defdom = $settings->{'sender_domain'};
 3096:         }
 3097:         if (exists($settings->{'autofailsafe'})) {
 3098:             $failsafe = $settings->{'autofailsafe'};
 3099:         }
 3100:     } else {
 3101:         if ($autorun) {
 3102:             $runon = ' checked="checked" ';
 3103:             $runoff = ' ';
 3104:         } else {
 3105:             $runoff = ' checked="checked" ';
 3106:             $runon = ' ';
 3107:         }
 3108:     }
 3109:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 3110:     my $notif_sender;
 3111:     if (ref($settings) eq 'HASH') {
 3112:         $notif_sender = $settings->{'sender_uname'};
 3113:     }
 3114:     my $datatable='<tr class="LC_odd_row">'.
 3115:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 3116:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3117:                   '<input type="radio" name="autoenroll_run"'.
 3118:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3119:                   '<label><input type="radio" name="autoenroll_run"'.
 3120:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3121:                   '</tr><tr>'.
 3122:                   '<td>'.&mt('Notification messages - sender').
 3123:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 3124:                   &mt('username').':&nbsp;'.
 3125:                   '<input type="text" name="sender_uname" value="'.
 3126:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 3127:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 3128:                   '<tr class="LC_odd_row">'.
 3129:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 3130:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3131:                   '<input type="radio" name="autoassign_coowners"'.
 3132:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3133:                   '<label><input type="radio" name="autoassign_coowners"'.
 3134:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3135:                   '</tr><tr>'.
 3136:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 3137:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 3138:                   '<input type="text" name="autoenroll_failsafe"'.
 3139:                   ' value="'.$failsafe.'" size="4" /></span></td></tr>';
 3140:     $$rowtotal += 4;
 3141:     return $datatable;
 3142: }
 3143: 
 3144: sub print_autoupdate {
 3145:     my ($position,$dom,$settings,$rowtotal) = @_;
 3146:     my $datatable;
 3147:     if ($position eq 'top') {
 3148:         my $updateon = ' ';
 3149:         my $updateoff = ' checked="checked" ';
 3150:         my $classlistson = ' ';
 3151:         my $classlistsoff = ' checked="checked" ';
 3152:         if (ref($settings) eq 'HASH') {
 3153:             if ($settings->{'run'} eq '1') {
 3154:                 $updateon = $updateoff;
 3155:                 $updateoff = ' ';
 3156:             }
 3157:             if ($settings->{'classlists'} eq '1') {
 3158:                 $classlistson = $classlistsoff;
 3159:                 $classlistsoff = ' ';
 3160:             }
 3161:         }
 3162:         my %title = (
 3163:                    run => 'Auto-update active?',
 3164:                    classlists => 'Update information in classlists?',
 3165:                     );
 3166:         $datatable = '<tr class="LC_odd_row">'. 
 3167:                   '<td>'.&mt($title{'run'}).'</td>'.
 3168:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3169:                   '<input type="radio" name="autoupdate_run"'.
 3170:                   $updateon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3171:                   '<label><input type="radio" name="autoupdate_run"'.
 3172:                   $updateoff.'value="0" />'.&mt('No').'</label></span></td>'.
 3173:                   '</tr><tr>'.
 3174:                   '<td>'.&mt($title{'classlists'}).'</td>'.
 3175:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 3176:                   '<label><input type="radio" name="classlists"'.
 3177:                   $classlistson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3178:                   '<label><input type="radio" name="classlists"'.
 3179:                   $classlistsoff.'value="0" />'.&mt('No').'</label></span></td>'.
 3180:                   '</tr>';
 3181:         $$rowtotal += 2;
 3182:     } elsif ($position eq 'middle') {
 3183:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3184:         my $numinrow = 3;
 3185:         my $locknamesettings;
 3186:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 3187:                                      $dom,$numinrow,$othertitle,
 3188:                                     'lockablenames',$rowtotal);
 3189:         $$rowtotal ++;
 3190:     } else {
 3191:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3192:         my @fields = ('lastname','firstname','middlename','generation',
 3193:                       'permanentemail','id');
 3194:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3195:         my $numrows = 0;
 3196:         if (ref($types) eq 'ARRAY') {
 3197:             if (@{$types} > 0) {
 3198:                 $datatable = 
 3199:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 3200:                                          \@fields,$types,\$numrows);
 3201:                     $$rowtotal += @{$types}; 
 3202:             }
 3203:         }
 3204:         $datatable .= 
 3205:             &usertype_update_row($settings,{'default' => $othertitle},
 3206:                                  \%fieldtitles,\@fields,['default'],
 3207:                                  \$numrows);
 3208:         $$rowtotal ++;     
 3209:     }
 3210:     return $datatable;
 3211: }
 3212: 
 3213: sub print_autocreate {
 3214:     my ($dom,$settings,$rowtotal) = @_;
 3215:     my (%createon,%createoff,%currhash);
 3216:     my @types = ('xml','req');
 3217:     if (ref($settings) eq 'HASH') {
 3218:         foreach my $item (@types) {
 3219:             $createoff{$item} = ' checked="checked" ';
 3220:             $createon{$item} = ' ';
 3221:             if (exists($settings->{$item})) {
 3222:                 if ($settings->{$item}) {
 3223:                     $createon{$item} = ' checked="checked" ';
 3224:                     $createoff{$item} = ' ';
 3225:                 }
 3226:             }
 3227:         }
 3228:         if ($settings->{'xmldc'} ne '') {
 3229:             $currhash{$settings->{'xmldc'}} = 1;
 3230:         }
 3231:     } else {
 3232:         foreach my $item (@types) {
 3233:             $createoff{$item} = ' checked="checked" ';
 3234:             $createon{$item} = ' ';
 3235:         }
 3236:     }
 3237:     $$rowtotal += 2;
 3238:     my $numinrow = 2;
 3239:     my $datatable='<tr class="LC_odd_row">'.
 3240:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 3241:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3242:                   '<input type="radio" name="autocreate_xml"'.
 3243:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3244:                   '<label><input type="radio" name="autocreate_xml"'.
 3245:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 3246:                   '</td></tr><tr>'.
 3247:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 3248:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3249:                   '<input type="radio" name="autocreate_req"'.
 3250:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3251:                   '<label><input type="radio" name="autocreate_req"'.
 3252:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 3253:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 3254:                                                    'autocreate_xmldc',%currhash);
 3255:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 3256:     if ($numdc > 1) {
 3257:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 3258:                       '</td><td class="LC_left_item">';
 3259:     } else {
 3260:         $datatable .= &mt('Course creation processed as:').
 3261:                       '</td><td class="LC_right_item">';
 3262:     }
 3263:     $datatable .= $dctable.'</td></tr>';
 3264:     $$rowtotal += $rows;
 3265:     return $datatable;
 3266: }
 3267: 
 3268: sub print_directorysrch {
 3269:     my ($position,$dom,$settings,$rowtotal) = @_;
 3270:     my $datatable;
 3271:     if ($position eq 'top') {
 3272:         my $instsrchon = ' ';
 3273:         my $instsrchoff = ' checked="checked" ';
 3274:         my ($exacton,$containson,$beginson);
 3275:         my $instlocalon = ' ';
 3276:         my $instlocaloff = ' checked="checked" ';
 3277:         if (ref($settings) eq 'HASH') {
 3278:             if ($settings->{'available'} eq '1') {
 3279:                 $instsrchon = $instsrchoff;
 3280:                 $instsrchoff = ' ';
 3281:             }
 3282:             if ($settings->{'localonly'} eq '1') {
 3283:                 $instlocalon = $instlocaloff;
 3284:                 $instlocaloff = ' ';
 3285:             }
 3286:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 3287:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 3288:                     if ($type eq 'exact') {
 3289:                         $exacton = ' checked="checked" ';
 3290:                     } elsif ($type eq 'contains') {
 3291:                         $containson = ' checked="checked" ';
 3292:                     } elsif ($type eq 'begins') {
 3293:                         $beginson = ' checked="checked" ';
 3294:                     }
 3295:                 }
 3296:             } else {
 3297:                 if ($settings->{'searchtypes'} eq 'exact') {
 3298:                     $exacton = ' checked="checked" ';
 3299:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 3300:                     $containson = ' checked="checked" ';
 3301:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 3302:                     $exacton = ' checked="checked" ';
 3303:                     $containson = ' checked="checked" ';
 3304:                 }
 3305:             }
 3306:         }
 3307:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 3308:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3309: 
 3310:         my $numinrow = 4;
 3311:         my $cansrchrow = 0;
 3312:         $datatable='<tr class="LC_odd_row">'.
 3313:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 3314:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3315:                    '<input type="radio" name="dirsrch_available"'.
 3316:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3317:                    '<label><input type="radio" name="dirsrch_available"'.
 3318:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3319:                    '</tr><tr>'.
 3320:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 3321:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3322:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 3323:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3324:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 3325:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3326:                    '</tr>';
 3327:         $$rowtotal += 2;
 3328:         if (ref($usertypes) eq 'HASH') {
 3329:             if (keys(%{$usertypes}) > 0) {
 3330:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 3331:                                              $numinrow,$othertitle,'cansearch',
 3332:                                              $rowtotal);
 3333:                 $cansrchrow = 1;
 3334:             }
 3335:         }
 3336:         if ($cansrchrow) {
 3337:             $$rowtotal ++;
 3338:             $datatable .= '<tr>';
 3339:         } else {
 3340:             $datatable .= '<tr class="LC_odd_row">';
 3341:         }
 3342:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 3343:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 3344:         foreach my $title (@{$titleorder}) {
 3345:             if (defined($searchtitles->{$title})) {
 3346:                 my $check = ' ';
 3347:                 if (ref($settings) eq 'HASH') {
 3348:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 3349:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 3350:                             $check = ' checked="checked" ';
 3351:                         }
 3352:                     }
 3353:                 }
 3354:                 $datatable .= '<td class="LC_left_item">'.
 3355:                               '<span class="LC_nobreak"><label>'.
 3356:                               '<input type="checkbox" name="searchby" '.
 3357:                               'value="'.$title.'"'.$check.'/>'.
 3358:                               $searchtitles->{$title}.'</label></span></td>';
 3359:             }
 3360:         }
 3361:         $datatable .= '</tr></table></td></tr>';
 3362:         $$rowtotal ++;
 3363:         if ($cansrchrow) {
 3364:             $datatable .= '<tr class="LC_odd_row">';
 3365:         } else {
 3366:             $datatable .= '<tr>';
 3367:         }
 3368:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 3369:                       '<td class="LC_left_item" colspan="2">'.
 3370:                       '<span class="LC_nobreak"><label>'.
 3371:                       '<input type="checkbox" name="searchtypes" '.
 3372:                       $exacton.' value="exact" />'.&mt('Exact match').
 3373:                       '</label>&nbsp;'.
 3374:                       '<label><input type="checkbox" name="searchtypes" '.
 3375:                       $beginson.' value="begins" />'.&mt('Begins with').
 3376:                       '</label>&nbsp;'.
 3377:                       '<label><input type="checkbox" name="searchtypes" '.
 3378:                       $containson.' value="contains" />'.&mt('Contains').
 3379:                       '</label></span></td></tr>';
 3380:         $$rowtotal ++;
 3381:     } else {
 3382:         my $domsrchon = ' checked="checked" ';
 3383:         my $domsrchoff = ' ';
 3384:         my $domlocalon = ' ';
 3385:         my $domlocaloff = ' checked="checked" ';
 3386:         if (ref($settings) eq 'HASH') {
 3387:             if ($settings->{'lclocalonly'} eq '1') {
 3388:                 $domlocalon = $domlocaloff;
 3389:                 $domlocaloff = ' ';
 3390:             }
 3391:             if ($settings->{'lcavailable'} eq '0') {
 3392:                 $domsrchoff = $domsrchon;
 3393:                 $domsrchon = ' ';
 3394:             }
 3395:         }
 3396:         $datatable='<tr class="LC_odd_row">'.
 3397:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 3398:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3399:                       '<input type="radio" name="dirsrch_domavailable"'.
 3400:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3401:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 3402:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3403:                       '</tr><tr>'.
 3404:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 3405:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3406:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 3407:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3408:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 3409:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3410:                       '</tr>';
 3411:         $$rowtotal += 2;
 3412:     }
 3413:     return $datatable;
 3414: }
 3415: 
 3416: sub print_contacts {
 3417:     my ($position,$dom,$settings,$rowtotal) = @_;
 3418:     my $datatable;
 3419:     my @contacts = ('adminemail','supportemail');
 3420:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 3421:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings,%lonstatus);
 3422:     if ($position eq 'top') {
 3423:         if (ref($settings) eq 'HASH') {
 3424:             foreach my $item (@contacts) {
 3425:                 if (exists($settings->{$item})) {
 3426:                     $to{$item} = $settings->{$item};
 3427:                 }
 3428:             }
 3429:         }
 3430:     } elsif ($position eq 'middle') {
 3431:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 3432:                      'updatesmail','idconflictsmail','hostipmail');
 3433:         foreach my $type (@mailings) {
 3434:             $otheremails{$type} = '';
 3435:         }
 3436:     } elsif ($position eq 'lower') {
 3437:         if (ref($settings) eq 'HASH') {
 3438:             if (ref($settings->{'lonstatus'}) eq 'HASH') {
 3439:                 %lonstatus = %{$settings->{'lonstatus'}};
 3440:             }
 3441:         }
 3442:     } else {
 3443:         @mailings = ('helpdeskmail','otherdomsmail');
 3444:         foreach my $type (@mailings) {
 3445:             $otheremails{$type} = '';
 3446:         }
 3447:         $bccemails{'helpdeskmail'} = '';
 3448:         $bccemails{'otherdomsmail'} = '';
 3449:         $includestr{'helpdeskmail'} = '';
 3450:         $includestr{'otherdomsmail'} = '';
 3451:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 3452:     }
 3453:     if (ref($settings) eq 'HASH') {
 3454:         unless (($position eq 'top') || ($position eq 'lower')) {
 3455:             foreach my $type (@mailings) {
 3456:                 if (exists($settings->{$type})) {
 3457:                     if (ref($settings->{$type}) eq 'HASH') {
 3458:                         foreach my $item (@contacts) {
 3459:                             if ($settings->{$type}{$item}) {
 3460:                                 $checked{$type}{$item} = ' checked="checked" ';
 3461:                             }
 3462:                         }
 3463:                         $otheremails{$type} = $settings->{$type}{'others'};
 3464:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3465:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 3466:                             if ($settings->{$type}{'include'} ne '') {
 3467:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3468:                                 $includestr{$type} = &unescape($includestr{$type});
 3469:                             }
 3470:                         }
 3471:                     }
 3472:                 } elsif ($type eq 'lonstatusmail') {
 3473:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3474:                 }
 3475:             }
 3476:         }
 3477:         if ($position eq 'bottom') {
 3478:             foreach my $type (@mailings) {
 3479:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 3480:                 if ($settings->{$type}{'include'} ne '') {
 3481:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3482:                     $includestr{$type} = &unescape($includestr{$type});
 3483:                 }
 3484:             }
 3485:             if (ref($settings->{'helpform'}) eq 'HASH') {
 3486:                 if (ref($fields) eq 'ARRAY') {
 3487:                     foreach my $field (@{$fields}) {
 3488:                         $currfield{$field} = $settings->{'helpform'}{$field};
 3489:                     }
 3490:                 }
 3491:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 3492:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 3493:                 } else {
 3494:                     $maxsize = '1.0';
 3495:                 }
 3496:             } else {
 3497:                 if (ref($fields) eq 'ARRAY') {
 3498:                     foreach my $field (@{$fields}) {
 3499:                         $currfield{$field} = 'yes';
 3500:                     }
 3501:                 }
 3502:                 $maxsize = '1.0';
 3503:             }
 3504:         }
 3505:     } else {
 3506:         if ($position eq 'top') {
 3507:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 3508:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 3509:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 3510:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 3511:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3512:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 3513:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 3514:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 3515:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 3516:         } elsif ($position eq 'bottom') {
 3517:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 3518:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 3519:             if (ref($fields) eq 'ARRAY') {
 3520:                 foreach my $field (@{$fields}) {
 3521:                     $currfield{$field} = 'yes';
 3522:                 }
 3523:             }
 3524:             $maxsize = '1.0';
 3525:         }
 3526:     }
 3527:     my ($titles,$short_titles) = &contact_titles();
 3528:     my $rownum = 0;
 3529:     my $css_class;
 3530:     if ($position eq 'top') {
 3531:         foreach my $item (@contacts) {
 3532:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3533:             $datatable .= '<tr'.$css_class.'>'. 
 3534:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 3535:                           '</span></td><td class="LC_right_item">'.
 3536:                           '<input type="text" name="'.$item.'" value="'.
 3537:                           $to{$item}.'" /></td></tr>';
 3538:             $rownum ++;
 3539:         }
 3540:     } elsif ($position eq 'bottom') {
 3541:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3542:         $datatable .= '<tr'.$css_class.'>'.
 3543:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 3544:                       &mt('(e-mail, subject, and description always shown)').
 3545:                       '</td><td class="LC_left_item">';
 3546:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 3547:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 3548:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 3549:             foreach my $field (@{$fields}) {
 3550:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 3551:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 3552:                     $datatable .= ' '.&mt('(logged-in users)');
 3553:                 }
 3554:                 $datatable .='</td><td>';
 3555:                 my $clickaction;
 3556:                 if ($field eq 'screenshot') {
 3557:                     $clickaction = ' onclick="screenshotSize(this);"';
 3558:                 }
 3559:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 3560:                     foreach my $option (@{$possoptions->{$field}}) {
 3561:                         my $checked;
 3562:                         if ($currfield{$field} eq $option) {
 3563:                             $checked = ' checked="checked"';
 3564:                         }
 3565:                         $datatable .= '<span class="LC_nobreak"><label>'.
 3566:                                       '<input type="radio" name="helpform_'.$field.'" '.
 3567:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 3568:                                       '</label></span>'.('&nbsp;'x2);
 3569:                     }
 3570:                 }
 3571:                 if ($field eq 'screenshot') {
 3572:                     my $display;
 3573:                     if ($currfield{$field} eq 'no') {
 3574:                         $display = ' style="display:none"';
 3575:                     }
 3576:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 3577:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 3578:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 3579:                 }
 3580:                 $datatable .= '</td></tr>';
 3581:             }
 3582:             $datatable .= '</table>';
 3583:         }
 3584:         $datatable .= '</td></tr>'."\n";
 3585:         $rownum ++;
 3586:     }
 3587:     unless (($position eq 'top') || ($position eq 'lower')) {
 3588:         foreach my $type (@mailings) {
 3589:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3590:             $datatable .= '<tr'.$css_class.'>'.
 3591:                           '<td><span class="LC_nobreak">'.
 3592:                           $titles->{$type}.': </span></td>'.
 3593:                           '<td class="LC_left_item">';
 3594:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3595:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 3596:             }
 3597:             $datatable .= '<span class="LC_nobreak">';
 3598:             foreach my $item (@contacts) {
 3599:                 $datatable .= '<label>'.
 3600:                               '<input type="checkbox" name="'.$type.'"'.
 3601:                               $checked{$type}{$item}.
 3602:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 3603:                               '</label>&nbsp;';
 3604:             }
 3605:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 3606:                           '<input type="text" name="'.$type.'_others" '.
 3607:                           'value="'.$otheremails{$type}.'"  />';
 3608:             my %locchecked;
 3609:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3610:                 foreach my $loc ('s','b') {
 3611:                     if ($includeloc{$type} eq $loc) {
 3612:                         $locchecked{$loc} = ' checked="checked"';
 3613:                         last;
 3614:                     }
 3615:                 }
 3616:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 3617:                               '<input type="text" name="'.$type.'_bcc" '.
 3618:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 3619:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 3620:                               &mt('Text automatically added to e-mail:').' '.
 3621:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 3622:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 3623:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 3624:                               ('&nbsp;'x2).
 3625:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 3626:                               '</span></fieldset>';
 3627:             }
 3628:             $datatable .= '</td></tr>'."\n";
 3629:             $rownum ++;
 3630:         }
 3631:     }
 3632:     if ($position eq 'middle') {
 3633:         my %choices;
 3634:         my $corelink = &core_link_msu();
 3635:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',$corelink);
 3636:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 3637:                                         $corelink);
 3638:         $choices{'reportstatus'} = &mt('E-mail status if errors above threshold to [_1]',$corelink);
 3639:         my @toggles = ('reporterrors','reportupdates','reportstatus');
 3640:         my %defaultchecked = ('reporterrors'  => 'on',
 3641:                               'reportupdates' => 'on',
 3642:                               'reportstatus'  => 'on');
 3643:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3644:                                                    \%choices,$rownum);
 3645:         $datatable .= $reports;
 3646:     } elsif ($position eq 'lower') {
 3647:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3648:         my ($threshold,$sysmail,%excluded,%weights);
 3649:         my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 3650:         if ($lonstatus{'threshold'} =~ /^\d+$/) {
 3651:             $threshold = $lonstatus{'threshold'};
 3652:         } else {
 3653:             $threshold = $defaults->{'threshold'};
 3654:         }
 3655:         if ($lonstatus{'sysmail'} =~ /^\d+$/) {
 3656:             $sysmail = $lonstatus{'sysmail'};
 3657:         } else {
 3658:             $sysmail = $defaults->{'sysmail'};
 3659:         }
 3660:         if (ref($lonstatus{'weights'}) eq 'HASH') {
 3661:             foreach my $type ('E','W','N','U') {
 3662:                 if ($lonstatus{'weights'}{$type} =~ /^\d+$/) {
 3663:                     $weights{$type} = $lonstatus{'weights'}{$type};
 3664:                 } else {
 3665:                     $weights{$type} = $defaults->{$type};
 3666:                 }
 3667:             }
 3668:         } else {
 3669:             foreach my $type ('E','W','N','U') {
 3670:                 $weights{$type} = $defaults->{$type};
 3671:             }
 3672:         }
 3673:         if (ref($lonstatus{'excluded'}) eq 'ARRAY') {
 3674:             if (@{$lonstatus{'excluded'}} > 0) {
 3675:                 map {$excluded{$_} = 1; } @{$lonstatus{'excluded'}};
 3676:             }
 3677:         }
 3678:         $datatable .= '<tr'.$css_class.'>'.
 3679:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 3680:                       $titles->{'errorthreshold'}.
 3681:                       '</span></td><td class="LC_left_item">'.
 3682:                       '<input type="text" name="errorthreshold" value="'.
 3683:                       $threshold.'" size="5" /></td></tr>';
 3684:         $rownum ++;
 3685:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3686:         $datatable .= '<tr'.$css_class.'>'.
 3687:                       '<td class="LC_left_item">'.
 3688:                       '<span class="LC_nobreak">'.$titles->{'errorweights'}.
 3689:                       '</span></td><td class="LC_left_item"><table><tr>';
 3690:         foreach my $type ('E','W','N','U') {
 3691:             $datatable .= '<td>'.$names->{$type}.'<br />'.
 3692:                           '<input type="text" name="errorweights_'.$type.'" value="'.
 3693:                           $weights{$type}.'" size="5" /></td>';
 3694:         }
 3695:         $datatable .= '</tr></table></tr>';
 3696:         $rownum ++;
 3697:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3698:         $datatable .= '<tr'.$css_class.'><td class="LC_left_item">'.
 3699:                       $titles->{'errorexcluded'}.'</td>'.
 3700:                       '<td class="LC_left_item"><table>';
 3701:         my $numinrow = 4;
 3702:         my @ids = sort(values(%Apache::lonnet::serverhomeIDs));
 3703:         for (my $i=0; $i<@ids; $i++) {
 3704:             my $rem = $i%($numinrow);
 3705:             if ($rem == 0) {
 3706:                 if ($i > 0) {
 3707:                     $datatable .= '</tr>';
 3708:                 }
 3709:                 $datatable .= '<tr>';
 3710:             }
 3711:             my $check;
 3712:             if ($excluded{$ids[$i]}) {
 3713:                 $check = ' checked="checked" ';
 3714:             }
 3715:             $datatable .= '<td class="LC_left_item">'.
 3716:                           '<span class="LC_nobreak"><label>'.
 3717:                           '<input type="checkbox" name="errorexcluded" '.
 3718:                           'value="'.$ids[$i].'"'.$check.' />'.
 3719:                           $ids[$i].'</label></span></td>';
 3720:         }
 3721:         my $colsleft = $numinrow - @ids%($numinrow);
 3722:         if ($colsleft > 1 ) {
 3723:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 3724:                           '&nbsp;</td>';
 3725:         } elsif ($colsleft == 1) {
 3726:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 3727:         }
 3728:         $datatable .= '</tr></table></td></tr>';
 3729:         $rownum ++;
 3730:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3731:         $datatable .= '<tr'.$css_class.'>'.
 3732:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 3733:                       $titles->{'errorsysmail'}.
 3734:                       '</span></td><td class="LC_left_item">'.
 3735:                       '<input type="text" name="errorsysmail" value="'.
 3736:                       $sysmail.'" size="5" /></td></tr>';
 3737:         $rownum ++;
 3738:     } elsif ($position eq 'bottom') {
 3739:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3740:         my (@posstypes,%usertypeshash);
 3741:         if (ref($types) eq 'ARRAY') {
 3742:             @posstypes = @{$types};
 3743:         }
 3744:         if (@posstypes) {
 3745:             if (ref($usertypes) eq 'HASH') {
 3746:                 %usertypeshash = %{$usertypes};
 3747:             }
 3748:             my @overridden;
 3749:             my $numinrow = 4;
 3750:             if (ref($settings) eq 'HASH') {
 3751:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 3752:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 3753:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 3754:                             push(@overridden,$key);
 3755:                             foreach my $item (@contacts) {
 3756:                                 if ($settings->{'overrides'}{$key}{$item}) {
 3757:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 3758:                                 }
 3759:                             }
 3760:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 3761:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 3762:                             $includeloc{'override_'.$key} = '';
 3763:                             $includestr{'override_'.$key} = '';
 3764:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 3765:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) = 
 3766:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 3767:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 3768:                             }
 3769:                         }
 3770:                     }
 3771:                 }
 3772:             }
 3773:             my $customclass = 'LC_helpdesk_override';
 3774:             my $optionsprefix = 'LC_options_helpdesk_';
 3775: 
 3776:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 3777:  
 3778:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 3779:                                          $numinrow,$othertitle,'overrides',
 3780:                                          \$rownum,$onclicktypes,$customclass);
 3781:             $rownum ++;
 3782:             $usertypeshash{'default'} = $othertitle;
 3783:             foreach my $status (@posstypes) {
 3784:                 my $css_class;
 3785:                 if ($rownum%2) {
 3786:                     $css_class = 'LC_odd_row ';
 3787:                 }
 3788:                 $css_class .= $customclass;
 3789:                 my $rowid = $optionsprefix.$status;
 3790:                 my $hidden = 1;
 3791:                 my $currstyle = 'display:none';
 3792:                 if (grep(/^\Q$status\E$/,@overridden)) {
 3793:                     $currstyle = 'display:table-row';
 3794:                     $hidden = 0;
 3795:                 }
 3796:                 my $key = 'override_'.$status;
 3797:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 3798:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 3799:                                                   $usertypeshash{$status},$css_class,$currstyle,
 3800:                                                   \@contacts,$short_titles);
 3801:                 unless ($hidden) {
 3802:                     $rownum ++;
 3803:                 }
 3804:             }
 3805:         }
 3806:     }
 3807:     $$rowtotal += $rownum;
 3808:     return $datatable;
 3809: }
 3810: 
 3811: sub core_link_msu {
 3812:     return &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 3813:                                           &mt('LON-CAPA core group - MSU'),600,500);
 3814: }
 3815: 
 3816: sub overridden_helpdesk {
 3817:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 3818:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 3819:     my $class = 'LC_left_item';
 3820:     if ($css_class) {
 3821:         $css_class = ' class="'.$css_class.'"';
 3822:     }
 3823:     if ($rowid) {
 3824:         $rowid = ' id="'.$rowid.'"';
 3825:     }
 3826:     if ($rowstyle) {
 3827:         $rowstyle = ' style="'.$rowstyle.'"';
 3828:     }
 3829:     my ($output,$description);
 3830:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 3831:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 3832:               "<td>$description</td>\n".
 3833:               '<td class="'.$class.'" colspan="2">'.
 3834:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 3835:               '<span class="LC_nobreak">';
 3836:     if (ref($contacts) eq 'ARRAY') {
 3837:         foreach my $item (@{$contacts}) {
 3838:             my $check;
 3839:             if (ref($checked) eq 'HASH') {
 3840:                $check = $checked->{$item};
 3841:             }
 3842:             my $title;
 3843:             if (ref($short_titles) eq 'HASH') {
 3844:                 $title = $short_titles->{$item}; 
 3845:             }
 3846:             $output .= '<label>'.
 3847:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 3848:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 3849:         }
 3850:     }
 3851:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 3852:                '<input type="text" name="override_'.$type.'_others" '.
 3853:                'value="'.$otheremails.'"  />';
 3854:     my %locchecked;
 3855:     foreach my $loc ('s','b') {
 3856:         if ($includeloc eq $loc) {
 3857:             $locchecked{$loc} = ' checked="checked"';
 3858:             last;
 3859:         }
 3860:     }
 3861:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 3862:                '<input type="text" name="override_'.$type.'_bcc" '.
 3863:                'value="'.$bccemails.'"  /></fieldset>'.
 3864:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 3865:                &mt('Text automatically added to e-mail:').' '.
 3866:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 3867:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 3868:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 3869:                ('&nbsp;'x2).
 3870:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 3871:                '</span></fieldset>'.
 3872:                '</td></tr>'."\n";
 3873:     return $output;
 3874: }
 3875: 
 3876: sub contacts_javascript {
 3877:     return <<"ENDSCRIPT";
 3878: 
 3879: <script type="text/javascript">
 3880: // <![CDATA[
 3881: 
 3882: function screenshotSize(field) {
 3883:     if (document.getElementById('help_screenshotsize')) {
 3884:         if (field.value == 'no') {
 3885:             document.getElementById('help_screenshotsize').style.display="none";
 3886:         } else {
 3887:             document.getElementById('help_screenshotsize').style.display="";
 3888:         }
 3889:     }
 3890:     return;
 3891: }
 3892: 
 3893: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 3894:     if (form.elements[checkbox].length != undefined) {
 3895:         var count = 0;
 3896:         if (docount) {
 3897:             for (var i=0; i<form.elements[checkbox].length; i++) {
 3898:                 if (form.elements[checkbox][i].checked) {
 3899:                     count ++;
 3900:                 }
 3901:             }
 3902:         }
 3903:         for (var i=0; i<form.elements[checkbox].length; i++) {
 3904:             var type = form.elements[checkbox][i].value;
 3905:             if (document.getElementById(prefix+type)) {
 3906:                 if (form.elements[checkbox][i].checked) {
 3907:                     document.getElementById(prefix+type).style.display = 'table-row';
 3908:                     if (count % 2 == 1) {
 3909:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 3910:                     } else {
 3911:                         document.getElementById(prefix+type).className = target;
 3912:                     }
 3913:                     count ++;
 3914:                 } else {
 3915:                     document.getElementById(prefix+type).style.display = 'none';
 3916:                 }
 3917:             }
 3918:         }
 3919:     }
 3920:     return;
 3921: }
 3922: 
 3923: 
 3924: // ]]>
 3925: </script>
 3926: 
 3927: ENDSCRIPT
 3928: }
 3929: 
 3930: sub print_helpsettings {
 3931:     my ($position,$dom,$settings,$rowtotal) = @_;
 3932:     my $confname = $dom.'-domainconfig';
 3933:     my $formname = 'display';
 3934:     my ($datatable,$itemcount);
 3935:     if ($position eq 'top') {
 3936:         $itemcount = 1;
 3937:         my (%choices,%defaultchecked,@toggles);
 3938:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 3939:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 3940:                                      &mt('LON-CAPA bug tracker'),600,500));
 3941:         %defaultchecked = ('submitbugs' => 'on');
 3942:         @toggles = ('submitbugs');
 3943:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3944:                                                      \%choices,$itemcount);
 3945:         $$rowtotal ++;
 3946:     } else {
 3947:         my $css_class;
 3948:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 3949:         my (%customroles,%ordered,%current);
 3950:         if (ref($settings) eq 'HASH') {
 3951:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 3952:                 %current = %{$settings->{'adhoc'}};
 3953:             }
 3954:         }
 3955:         my $count = 0;
 3956:         foreach my $key (sort(keys(%existing))) {
 3957:             if ($key=~/^rolesdef\_(\w+)$/) {
 3958:                 my $rolename = $1;
 3959:                 my (%privs,$order);
 3960:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 3961:                 $customroles{$rolename} = \%privs;
 3962:                 if (ref($current{$rolename}) eq 'HASH') {
 3963:                     $order = $current{$rolename}{'order'};
 3964:                 }
 3965:                 if ($order eq '') {
 3966:                     $order = $count;
 3967:                 }
 3968:                 $ordered{$order} = $rolename;
 3969:                 $count++;
 3970:             }
 3971:         }
 3972:         my $maxnum = scalar(keys(%ordered));
 3973:         my @roles_by_num = ();
 3974:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3975:             push(@roles_by_num,$item);
 3976:         }
 3977:         my $context = 'domprefs';
 3978:         my $crstype = 'Course';
 3979:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3980:         my @accesstypes = ('all','dh','da','none');
 3981:         my ($numstatustypes,@jsarray);
 3982:         if (ref($types) eq 'ARRAY') {
 3983:             if (@{$types} > 0) {
 3984:                 $numstatustypes = scalar(@{$types});
 3985:                 push(@accesstypes,'status');
 3986:                 @jsarray = ('bystatus');
 3987:             }
 3988:         }
 3989:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 3990:         if (keys(%domhelpdesk)) {
 3991:             push(@accesstypes,('inc','exc'));
 3992:             push(@jsarray,('notinc','notexc'));
 3993:         }
 3994:         my $hiddenstr = join("','",@jsarray);
 3995:         my $context = 'domprefs';
 3996:         my $crstype = 'Course';
 3997:         my $prefix = 'helproles_';
 3998:         my $add_class = 'LC_hidden';
 3999:         foreach my $num (@roles_by_num) {
 4000:             my $role = $ordered{$num};
 4001:             my ($desc,$access,@statuses);
 4002:             if (ref($current{$role}) eq 'HASH') {
 4003:                 $desc = $current{$role}{'desc'};
 4004:                 $access = $current{$role}{'access'};
 4005:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 4006:                     @statuses = @{$current{$role}{'insttypes'}};
 4007:                 }
 4008:             }
 4009:             if ($desc eq '') {
 4010:                 $desc = $role;
 4011:             }
 4012:             my $identifier = 'custhelp'.$num;
 4013:             my %full=();
 4014:             my %levels= (
 4015:                          course => {},
 4016:                          domain => {},
 4017:                          system => {},
 4018:                         );
 4019:             my %levelscurrent=(
 4020:                                course => {},
 4021:                                domain => {},
 4022:                                system => {},
 4023:                               );
 4024:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 4025:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4026:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4027:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 4028:             $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><b>'.$role.'</b><br />'.
 4029:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 4030:             for (my $k=0; $k<=$maxnum; $k++) {
 4031:                 my $vpos = $k+1;
 4032:                 my $selstr;
 4033:                 if ($k == $num) {
 4034:                     $selstr = ' selected="selected" ';
 4035:                 }
 4036:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4037:             }
 4038:             $datatable .= '</select>'.('&nbsp;'x2).
 4039:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 4040:                           '</td>'.
 4041:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4042:                           &mt('Name shown to users:').
 4043:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 4044:                           '</fieldset>'.
 4045:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 4046:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 4047:                           '<fieldset>'.
 4048:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 4049:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4050:                                                                    \%levelscurrent,$identifier,
 4051:                                                                    'LC_hidden',$prefix.$num.'_privs').
 4052:                           '</fieldset></td>';
 4053:             $itemcount ++;
 4054:         }
 4055:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4056:         my $newcust = 'custhelp'.$count;
 4057:         my (%privs,%levelscurrent);
 4058:         my %full=();
 4059:         my %levels= (
 4060:                      course => {},
 4061:                      domain => {},
 4062:                      system => {},
 4063:                     );
 4064:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4065:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4066:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 4067:         $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><span class="LC_nobreak"><label>'.
 4068:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 4069:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 4070:         for (my $k=0; $k<$maxnum+1; $k++) {
 4071:             my $vpos = $k+1;
 4072:             my $selstr;
 4073:             if ($k == $maxnum) {
 4074:                 $selstr = ' selected="selected" ';
 4075:             }
 4076:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4077:         }
 4078:         $datatable .= '</select>&nbsp;'."\n".
 4079:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 4080:                       '</label></span></td>'.
 4081:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4082:                       '<span class="LC_nobreak">'.
 4083:                       &mt('Internal name:').
 4084:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 4085:                       '</span>'.('&nbsp;'x4).
 4086:                       '<span class="LC_nobreak">'.
 4087:                       &mt('Name shown to users:').
 4088:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 4089:                       '</span></fieldset>'.
 4090:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 4091:                                              $usertypes,$types,\%domhelpdesk).
 4092:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 4093:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 4094:                                                                 \@templateroles,$newcust).
 4095:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 4096:                                                                \%levelscurrent,$newcust).
 4097:                       '</fieldset>'.
 4098:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 4099:                       '</td></tr>';
 4100:         $count ++;
 4101:         $$rowtotal += $count;
 4102:     }
 4103:     return $datatable;
 4104: }
 4105: 
 4106: sub adhocbutton {
 4107:     my ($prefix,$num,$field,$visibility) = @_;
 4108:     my %lt = &Apache::lonlocal::texthash(
 4109:                                           show => 'Show details',
 4110:                                           hide => 'Hide details',
 4111:                                         );
 4112:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 4113:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 4114:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 4115:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 4116: }
 4117: 
 4118: sub helpsettings_javascript {
 4119:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 4120:     return unless(ref($roles_by_num) eq 'ARRAY');
 4121:     my %html_js_lt = &Apache::lonlocal::texthash(
 4122:                                           show => 'Show details',
 4123:                                           hide => 'Hide details',
 4124:                                         );
 4125:     &html_escape(\%html_js_lt);
 4126:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 4127:     return <<"ENDSCRIPT";
 4128: <script type="text/javascript">
 4129: // <![CDATA[
 4130: 
 4131: function reorderHelpRoles(form,item) {
 4132:     var changedVal;
 4133: $jstext
 4134:     var newpos = 'helproles_${total}_pos';
 4135:     var maxh = 1 + $total;
 4136:     var current = new Array();
 4137:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 4138:     if (item == newpos) {
 4139:         changedVal = newitemVal;
 4140:     } else {
 4141:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 4142:         current[newitemVal] = newpos;
 4143:     }
 4144:     for (var i=0; i<helproles.length; i++) {
 4145:         var elementName = 'helproles_'+helproles[i]+'_pos';
 4146:         if (elementName != item) {
 4147:             if (form.elements[elementName]) {
 4148:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 4149:                 current[currVal] = elementName;
 4150:             }
 4151:         }
 4152:     }
 4153:     var oldVal;
 4154:     for (var j=0; j<maxh; j++) {
 4155:         if (current[j] == undefined) {
 4156:             oldVal = j;
 4157:         }
 4158:     }
 4159:     if (oldVal < changedVal) {
 4160:         for (var k=oldVal+1; k<=changedVal ; k++) {
 4161:            var elementName = current[k];
 4162:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 4163:         }
 4164:     } else {
 4165:         for (var k=changedVal; k<oldVal; k++) {
 4166:             var elementName = current[k];
 4167:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 4168:         }
 4169:     }
 4170:     return;
 4171: }
 4172: 
 4173: function helpdeskAccess(num) {
 4174:     var curraccess = null;
 4175:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 4176:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 4177:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 4178:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 4179:             }
 4180:         }
 4181:     }
 4182:     var shown = Array();
 4183:     var hidden = Array();
 4184:     if (curraccess == 'none') {
 4185:         hidden = Array('$hiddenstr');
 4186:     } else {
 4187:         if (curraccess == 'status') {
 4188:             shown = Array('bystatus');
 4189:             hidden = Array('notinc','notexc');
 4190:         } else {
 4191:             if (curraccess == 'exc') {
 4192:                 shown = Array('notexc');
 4193:                 hidden = Array('notinc','bystatus');
 4194:             }
 4195:             if (curraccess == 'inc') {
 4196:                 shown = Array('notinc');
 4197:                 hidden = Array('notexc','bystatus');
 4198:             }
 4199:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 4200:                 hidden = Array('notinc','notexc','bystatus');
 4201:             }
 4202:         }
 4203:     }
 4204:     if (hidden.length > 0) {
 4205:         for (var i=0; i<hidden.length; i++) {
 4206:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 4207:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 4208:             }
 4209:         }
 4210:     }
 4211:     if (shown.length > 0) {
 4212:         for (var i=0; i<shown.length; i++) {
 4213:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 4214:                 if (shown[i] == 'privs') {
 4215:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 4216:                 } else {
 4217:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 4218:                 }
 4219:             }
 4220:         }
 4221:     }
 4222:     return;
 4223: }
 4224: 
 4225: function toggleHelpdeskItem(num,field) {
 4226:     if (document.getElementById('helproles_'+num+'_'+field)) {
 4227:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 4228:             document.getElementById('helproles_'+num+'_'+field).className =
 4229:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 4230:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4231:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 4232:             }
 4233:         } else {
 4234:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 4235:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4236:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 4237:             }
 4238:         }
 4239:     }
 4240:     return;
 4241: }
 4242: 
 4243: // ]]>
 4244: </script>
 4245: 
 4246: ENDSCRIPT
 4247: }
 4248: 
 4249: sub helpdeskroles_access {
 4250:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 4251:         $usertypes,$types,$domhelpdesk) = @_;
 4252:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 4253:     my %lt = &Apache::lonlocal::texthash(
 4254:                     'rou'    => 'Role usage',
 4255:                     'whi'    => 'Which helpdesk personnel may use this role?',
 4256:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 4257:                     'dh'     => 'All with domain helpdesk role',
 4258:                     'da'     => 'All with domain helpdesk assistant role',
 4259:                     'none'   => 'None',
 4260:                     'status' => 'Determined based on institutional status',
 4261:                     'inc'    => 'Include all, but exclude specific personnel',
 4262:                     'exc'    => 'Exclude all, but include specific personnel',
 4263:                   );
 4264:     my %usecheck = (
 4265:                      all => ' checked="checked"',
 4266:                    );
 4267:     my %displaydiv = (
 4268:                       status => 'none',
 4269:                       inc    => 'none',
 4270:                       exc    => 'none',
 4271:                       priv   => 'block',
 4272:                      );
 4273:     my $output;
 4274:     if (ref($current) eq 'HASH') {
 4275:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 4276:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 4277:                 $usecheck{$current->{access}} = $usecheck{'all'};
 4278:                 delete($usecheck{'all'});
 4279:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 4280:                     my $access = $1;
 4281:                     $displaydiv{$access} = 'inline';
 4282:                 } elsif ($current->{access} eq 'none') {
 4283:                     $displaydiv{'priv'} = 'none';
 4284:                 }
 4285:             }
 4286:         }
 4287:     }
 4288:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 4289:               '<p>'.$lt{'whi'}.'</p>';
 4290:     foreach my $access (@{$accesstypes}) {
 4291:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 4292:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 4293:                    $lt{$access}.'</label>';
 4294:         if ($access eq 'status') {
 4295:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 4296:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 4297:                                                                  $othertitle,$usertypes,$types).
 4298:                        '</div>';
 4299:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 4300:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 4301:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4302:                        '</div>';
 4303:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 4304:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 4305:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4306:                        '</div>';
 4307:         }
 4308:         $output .= '</p>';
 4309:     }
 4310:     $output .= '</fieldset>';
 4311:     return $output;
 4312: }
 4313: 
 4314: sub radiobutton_prefs {
 4315:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 4316:         $additional,$align) = @_;
 4317:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 4318:                    (ref($choices) eq 'HASH'));
 4319: 
 4320:     my (%checkedon,%checkedoff,$datatable,$css_class);
 4321: 
 4322:     foreach my $item (@{$toggles}) {
 4323:         if ($defaultchecked->{$item} eq 'on') {
 4324:             $checkedon{$item} = ' checked="checked" ';
 4325:             $checkedoff{$item} = ' ';
 4326:         } elsif ($defaultchecked->{$item} eq 'off') {
 4327:             $checkedoff{$item} = ' checked="checked" ';
 4328:             $checkedon{$item} = ' ';
 4329:         }
 4330:     }
 4331:     if (ref($settings) eq 'HASH') {
 4332:         foreach my $item (@{$toggles}) {
 4333:             if ($settings->{$item} eq '1') {
 4334:                 $checkedon{$item} =  ' checked="checked" ';
 4335:                 $checkedoff{$item} = ' ';
 4336:             } elsif ($settings->{$item} eq '0') {
 4337:                 $checkedoff{$item} =  ' checked="checked" ';
 4338:                 $checkedon{$item} = ' ';
 4339:             }
 4340:         }
 4341:     }
 4342:     if ($onclick) {
 4343:         $onclick = ' onclick="'.$onclick.'"';
 4344:     }
 4345:     foreach my $item (@{$toggles}) {
 4346:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4347:         $datatable .=
 4348:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 4349:             '<span class="LC_nobreak">'.$choices->{$item}.
 4350:             '</span></td>';
 4351:         if ($align eq 'left') {
 4352:             $datatable .= '<td class="LC_left_item">';
 4353:         } else {
 4354:             $datatable .= '<td class="LC_right_item">';
 4355:         }
 4356:         $datatable .=
 4357:             '<span class="LC_nobreak">'.
 4358:             '<label><input type="radio" name="'.
 4359:             $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 4360:             '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 4361:             $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>'.
 4362:             '</span>'.$additional.
 4363:             '</td>'.
 4364:             '</tr>';
 4365:         $itemcount ++;
 4366:     }
 4367:     return ($datatable,$itemcount);
 4368: }
 4369: 
 4370: sub print_ltitools {
 4371:     my ($dom,$settings,$rowtotal) = @_;
 4372:     my $rownum = 0;
 4373:     my $css_class;
 4374:     my $itemcount = 1;
 4375:     my $maxnum = 0;
 4376:     my %ordered;
 4377:     if (ref($settings) eq 'HASH') {
 4378:         foreach my $item (keys(%{$settings})) {
 4379:             if (ref($settings->{$item}) eq 'HASH') {
 4380:                 my $num = $settings->{$item}{'order'};
 4381:                 $ordered{$num} = $item;
 4382:             }
 4383:         }
 4384:     }
 4385:     my $confname = $dom.'-domainconfig';
 4386:     my $switchserver = &check_switchserver($dom,$confname);
 4387:     my $maxnum = scalar(keys(%ordered));
 4388:     my $datatable;
 4389:     my %lt = &ltitools_names();
 4390:     my @courseroles = ('cc','in','ta','ep','st');
 4391:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
 4392:     my @fields = ('fullname','firstname','lastname','email','roles','user');
 4393:     if (keys(%ordered)) {
 4394:         my @items = sort { $a <=> $b } keys(%ordered);
 4395:         for (my $i=0; $i<@items; $i++) {
 4396:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4397:             my $item = $ordered{$items[$i]};
 4398:             my ($title,$key,$secret,$url,$lifetime,$imgsrc,%sigsel);
 4399:             if (ref($settings->{$item}) eq 'HASH') {
 4400:                 $title = $settings->{$item}->{'title'};
 4401:                 $url = $settings->{$item}->{'url'};
 4402:                 $key = $settings->{$item}->{'key'};
 4403:                 $secret = $settings->{$item}->{'secret'};
 4404:                 $lifetime = $settings->{$item}->{'lifetime'};
 4405:                 my $image = $settings->{$item}->{'image'};
 4406:                 if ($image ne '') {
 4407:                     $imgsrc = '<img src="'.$image.'" alt="'.&mt('Tool Provider icon').'" />';
 4408:                 }
 4409:                 if ($settings->{$item}->{'sigmethod'} eq 'HMAC-256') {
 4410:                     $sigsel{'HMAC-256'} = ' selected="selected"';
 4411:                 } else {
 4412:                     $sigsel{'HMAC-SHA1'} = ' selected="selected"';
 4413:                 }
 4414:             }
 4415:             my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_".$item."'".');"';
 4416:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 4417:                          .'<select name="ltitools_'.$item.'"'.$chgstr.'>';
 4418:             for (my $k=0; $k<=$maxnum; $k++) {
 4419:                 my $vpos = $k+1;
 4420:                 my $selstr;
 4421:                 if ($k == $i) {
 4422:                     $selstr = ' selected="selected" ';
 4423:                 }
 4424:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4425:             }
 4426:             $datatable .= '</select>'.('&nbsp;'x2).
 4427:                 '<label><input type="checkbox" name="ltitools_del" value="'.$item.'" />'.
 4428:                 &mt('Delete?').'</label></span></td>'.
 4429:                 '<td colspan="2">'.
 4430:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 4431:                 '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_title_'.$i.'" value="'.$title.'" /></span> '.
 4432:                 ('&nbsp;'x2).
 4433:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_version_'.$i.'">'.
 4434:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 4435:                 ('&nbsp;'x2).
 4436:                 '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_msgtype_'.$i.'">'.
 4437:                 '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 4438:                 ('&nbsp;'x2).
 4439:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_sigmethod_'.$i.'">'.
 4440:                 '<option value="HMAC-SHA1"'.$sigsel{'HMAC-SHA1'}.'>HMAC-SHA1</option>'.
 4441:                 '<option value="HMAC-SHA256"'.$sigsel{'HMAC-SHA256'}.'>HMAC-SHA256</option></select></span>'.
 4442:                 '<br /><br />'.
 4443:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_url_'.$i.'"'.
 4444:                 ' value="'.$url.'" /></span>'.
 4445:                 ('&nbsp;'x2).
 4446:                 '<span class="LC_nobreak">'.$lt{'key'}.':'.
 4447:                 '<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" /></span> '.
 4448:                 ('&nbsp;'x2).
 4449:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':'.
 4450:                 '<input type="text" size="5" name="ltitools_lifetime_'.$i.'" value="'.$lifetime.'" /></span> '.
 4451:                 ('&nbsp;'x2).
 4452:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 4453:                 '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="'.$secret.'" />'.
 4454:                 '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltitools_secret_'.$i.'.type='."'text'".' } else { this.form.ltitools_secret_'.$i.'.type='."'password'".' }" />'.&mt('Visible input').'</label>'.
 4455:                 '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span>'.
 4456:                 '</fieldset>'.
 4457:                 '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 4458:                 '<span class="LC_nobreak">'.&mt('Display target:');
 4459:             my %currdisp;
 4460:             if (ref($settings->{$item}->{'display'}) eq 'HASH') {
 4461:                 if ($settings->{$item}->{'display'}->{'target'} eq 'window') {
 4462:                     $currdisp{'window'} = ' checked="checked"';
 4463:                 } elsif ($settings->{$item}->{'display'}->{'target'} eq 'tab') {
 4464:                     $currdisp{'tab'} = ' checked="checked"';
 4465:                 } else {
 4466:                     $currdisp{'iframe'} = ' checked="checked"';
 4467:                 }
 4468:                 if ($settings->{$item}->{'display'}->{'width'} =~ /^(\d+)$/) {
 4469:                     $currdisp{'width'} = $1;
 4470:                 }
 4471:                 if ($settings->{$item}->{'display'}->{'height'} =~ /^(\d+)$/) {
 4472:                      $currdisp{'height'} = $1;
 4473:                 }
 4474:                 $currdisp{'linktext'} = $settings->{$item}->{'display'}->{'linktext'};
 4475:                 $currdisp{'explanation'} = $settings->{$item}->{'display'}->{'explanation'};
 4476:             } else {
 4477:                 $currdisp{'iframe'} = ' checked="checked"';
 4478:             }
 4479:             foreach my $disp ('iframe','tab','window') {
 4480:                 $datatable .= '<label><input type="radio" name="ltitools_target_'.$i.'" value="'.$disp.'"'.$currdisp{$disp}.' />'.
 4481:                               $lt{$disp}.'</label>'.('&nbsp;'x2);
 4482:             }
 4483:             $datatable .= ('&nbsp;'x4);
 4484:             foreach my $dimen ('width','height') {
 4485:                 $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 4486:                               '<input type="text" name="ltitools_'.$dimen.'_'.$i.'" size="5" value="'.$currdisp{$dimen}.'" /></label>'.
 4487:                               ('&nbsp;'x2);
 4488:             }
 4489:             $datatable .= '</span><br />'.
 4490:                           '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 4491:                           '<input type="text" name="ltitools_linktext_'.$i.'" size="25" value="'.$currdisp{'linktext'}.'" /></div>'.
 4492:                           '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 4493:                           '<textarea name="ltitools_explanation_'.$i.'" rows="5" cols="40">'.$currdisp{'explanation'}.
 4494:                           '</textarea></div><div style=""></div><br />';
 4495:             my %units = (
 4496:                           'passback' => 'days',
 4497:                           'roster'   => 'seconds',
 4498:                         );
 4499:             foreach my $extra ('passback','roster') {
 4500:                 my $validsty = 'none';
 4501:                 my $currvalid;
 4502:                 my $checkedon = '';
 4503:                 my $checkedoff = ' checked="checked"';
 4504:                 if ($settings->{$item}->{$extra}) {
 4505:                     $checkedon = $checkedoff;
 4506:                     $checkedoff = '';
 4507:                     $validsty = 'inline-block';
 4508:                     if ($settings->{$item}->{$extra.'valid'} =~ /^\d+\.?\d*$/) {
 4509:                         $currvalid = $settings->{$item}->{$extra.'valid'};
 4510:                     }
 4511:                 }
 4512:                 my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','$i'".');"';
 4513:                 $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 4514:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="0"'.$checkedoff.$onclick.' />'.
 4515:                               &mt('No').'</label>'.('&nbsp;'x2).
 4516:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="1"'.$checkedon.$onclick.' />'.
 4517:                               &mt('Yes').'</label></span></div>'.
 4518:                               '<div class="LC_floatleft" style="display:'.$validsty.';" id="ltitools_'.$extra.'time_'.$i.'">'.
 4519:                               '<span class="LC_nobreak">'.
 4520:                               &mt("at least [_1] $units{$extra} after launch",
 4521:                                   '<input type="text" name="ltitools_'.$extra.'valid_'.$i.'" value="'.$currvalid.'" />').
 4522:                               '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 4523:             }
 4524:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 4525:             if ($imgsrc) {
 4526:                 $datatable .= $imgsrc.
 4527:                               '<label><input type="checkbox" name="ltitools_image_del"'.
 4528:                               ' value="'.$item.'" />'.&mt('Delete?').'</label></span> '.
 4529:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 4530:             } else {
 4531:                 $datatable .= '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 4532:             }
 4533:             if ($switchserver) {
 4534:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 4535:             } else {
 4536:                 $datatable .= '<input type="file" name="ltitools_image_'.$i.'" value="" />';
 4537:             }
 4538:             $datatable .= '</span></fieldset>';
 4539:             my (%checkedfields,%rolemaps,$userincdom);
 4540:             if (ref($settings->{$item}) eq 'HASH') {
 4541:                 if (ref($settings->{$item}->{'fields'}) eq 'HASH') {
 4542:                     %checkedfields = %{$settings->{$item}->{'fields'}};
 4543:                 }
 4544:                 $userincdom = $settings->{$item}->{'incdom'};
 4545:                 if (ref($settings->{$item}->{'roles'}) eq 'HASH') {
 4546:                     %rolemaps = %{$settings->{$item}->{'roles'}};
 4547:                     $checkedfields{'roles'} = 1;
 4548:                 }
 4549:             }
 4550:             $datatable .= '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 4551:                           '<span class="LC_nobreak">';
 4552:             my $userfieldstyle = 'display:none;';
 4553:             my $seluserdom = '';
 4554:             my $unseluserdom = ' selected="selected"';
 4555:             foreach my $field (@fields) {
 4556:                 my ($checked,$onclick,$id,$spacer);
 4557:                 if ($checkedfields{$field}) {
 4558:                     $checked = ' checked="checked"';
 4559:                 }
 4560:                 if ($field eq 'user') {
 4561:                     $id = ' id="ltitools_user_field_'.$i.'"';
 4562:                     $onclick = ' onclick="toggleLTITools(this.form,'."'$field','$i'".')"';
 4563:                     if ($checked) {
 4564:                         $userfieldstyle = 'display:inline-block';
 4565:                         if ($userincdom) {
 4566:                             $seluserdom = $unseluserdom;
 4567:                             $unseluserdom = '';
 4568:                         }
 4569:                     }
 4570:                 } else {
 4571:                     $spacer = ('&nbsp;' x2);
 4572:                 }
 4573:                 $datatable .= '<label>'.
 4574:                               '<input type="checkbox" name="ltitools_fields_'.$i.'" value="'.$field.'"'.$id.$checked.$onclick.' />'.
 4575:                               $lt{$field}.'</label>'.$spacer;
 4576:             }
 4577:             $datatable .= '</span>';
 4578:             $datatable .= '<div style="'.$userfieldstyle.'" id="ltitools_user_div_'.$i.'">'.
 4579:                           '<span class="LC_nobreak"> : '.
 4580:                           '<select name="ltitools_userincdom_'.$i.'">'.
 4581:                           '<option value="">'.&mt('Select').'</option>'.
 4582:                           '<option value="0"'.$unseluserdom.'>'.&mt('username').'</option>'.
 4583:                           '<option value="1"'.$seluserdom.'>'.&mt('username:domain').'</option>'.
 4584:                           '</select></span></div>';
 4585:             $datatable .= '</fieldset>'.
 4586:                           '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 4587:             foreach my $role (@courseroles) {
 4588:                 my ($selected,$selectnone);
 4589:                 if (!$rolemaps{$role}) {
 4590:                     $selectnone = ' selected="selected"';
 4591:                 }
 4592:                 $datatable .= '<td style="text-align: center">'. 
 4593:                               &Apache::lonnet::plaintext($role,'Course').'<br />'.
 4594:                               '<select name="ltitools_roles_'.$role.'_'.$i.'">'.
 4595:                               '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 4596:                 foreach my $ltirole (@ltiroles) {
 4597:                     unless ($selectnone) {
 4598:                         if ($rolemaps{$role} eq $ltirole) {
 4599:                             $selected = ' selected="selected"';
 4600:                         } else {
 4601:                             $selected = '';
 4602:                         }
 4603:                     }
 4604:                     $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 4605:                 }
 4606:                 $datatable .= '</select></td>';
 4607:             }
 4608:             $datatable .= '</tr></table></fieldset>';
 4609:             my %courseconfig;
 4610:             if (ref($settings->{$item}) eq 'HASH') {
 4611:                 if (ref($settings->{$item}->{'crsconf'}) eq 'HASH') {
 4612:                     %courseconfig = %{$settings->{$item}->{'crsconf'}};
 4613:                 }
 4614:             }
 4615:             $datatable .= '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 4616:             foreach my $item ('label','title','target','linktext','explanation','append') {
 4617:                 my $checked;
 4618:                 if ($courseconfig{$item}) {
 4619:                     $checked = ' checked="checked"';
 4620:                 }
 4621:                 $datatable .= '<label>'.
 4622:                        '<input type="checkbox" name="ltitools_courseconfig_'.$i.'" value="'.$item.'"'.$checked.' />'.
 4623:                        $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 4624:             }
 4625:             $datatable .= '</span></fieldset>'.
 4626:                           '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 4627:                           '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>';
 4628:             if (ref($settings->{$item}->{'custom'}) eq 'HASH') {
 4629:                 my %custom = %{$settings->{$item}->{'custom'}};
 4630:                 if (keys(%custom) > 0) {
 4631:                     foreach my $key (sort(keys(%custom))) {
 4632:                         $datatable .= '<tr><td><span class="LC_nobreak">'.
 4633:                                       '<label><input type="checkbox" name="ltitools_customdel_'.$i.'" value="'.
 4634:                                       $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 4635:                                       '<td><input type="text" name="ltitools_customval_'.$key.'_'.$i.'"'.
 4636:                                       ' value="'.$custom{$key}.'" /></td></tr>';
 4637:                     }
 4638:                 }
 4639:             }
 4640:             $datatable .= '<tr><td><span class="LC_nobreak">'.
 4641:                           '<label><input type="checkbox" name="ltitools_customadd" value="'.$i.'" />'.
 4642:                           &mt('Add').'</label></span></td><td><input type="text" name="ltitools_custom_name_'.$i.'" />'.
 4643:                           '</td><td><input type="text" name="ltitools_custom_value_'.$i.'" /></td></tr>';
 4644:             $datatable .= '</table></fieldset></td></tr>'."\n";
 4645:             $itemcount ++;
 4646:         }
 4647:     }
 4648:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4649:     my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_add_pos'".');"';
 4650:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 4651:                   '<input type="hidden" name="ltitools_maxnum" value="'.$maxnum.'" />'."\n".
 4652:                   '<select name="ltitools_add_pos"'.$chgstr.'>';
 4653:     for (my $k=0; $k<$maxnum+1; $k++) {
 4654:         my $vpos = $k+1;
 4655:         my $selstr;
 4656:         if ($k == $maxnum) {
 4657:             $selstr = ' selected="selected" ';
 4658:         }
 4659:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4660:     }
 4661:     $datatable .= '</select>&nbsp;'."\n".
 4662:                   '<input type="checkbox" name="ltitools_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 4663:                   '<td colspan="2">'.
 4664:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 4665:                   '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_add_title" value="" /></span> '."\n".
 4666:                   ('&nbsp;'x2).
 4667:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_add_version">'.
 4668:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 4669:                   ('&nbsp;'x2).
 4670:                   '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_add_msgtype">'.
 4671:                   '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 4672:                   '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_add_sigmethod">'.
 4673:                   '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 4674:                   '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 4675:                   '<br />'.
 4676:                   '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_add_url" value="" /></span> '."\n".
 4677:                   ('&nbsp;'x2).
 4678:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="ltitools_add_key" value="" /></span> '."\n".
 4679:                   ('&nbsp;'x2).
 4680:                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="ltitools_add_lifetime" value="300" /></span> '."\n".
 4681:                   ('&nbsp;'x2).
 4682:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="ltitools_add_secret" value="" />'.
 4683:                   '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltitools_add_secret.type='."'text'".' } else { this.form.ltitools_add_secret.type='."'password'".' }" />'.&mt('Visible input').'</label></span> '."\n".
 4684:                   '</fieldset>'.
 4685:                   '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 4686:                   '<span class="LC_nobreak">'.&mt('Display target:');
 4687:     my %defaultdisp;
 4688:     $defaultdisp{'iframe'} = ' checked="checked"';
 4689:     foreach my $disp ('iframe','tab','window') {
 4690:         $datatable .= '<label><input type="radio" name="ltitools_add_target" value="'.$disp.'"'.$defaultdisp{$disp}.' />'.
 4691:                       $lt{$disp}.'</label>'.('&nbsp;'x2);
 4692:     }
 4693:     $datatable .= ('&nbsp;'x4);
 4694:     foreach my $dimen ('width','height') {
 4695:         $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 4696:                       '<input type="text" name="ltitools_add_'.$dimen.'" size="5" /></label>'.
 4697:                       ('&nbsp;'x2);
 4698:     }
 4699:     $datatable .= '</span><br />'.
 4700:                   '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 4701:                   '<input type="text" name="ltitools_add_linktext" size="5" /></div>'.
 4702:                   '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 4703:                   '<textarea name="ltitools_add_explanation" rows="5" cols="40"></textarea>'.
 4704:                   '</div><div style=""></div><br />';
 4705:     my %units = (
 4706:                   'passback' => 'days',
 4707:                   'roster'   => 'seconds',
 4708:                 );
 4709:     my %defaulttimes = (
 4710:                      'passback' => '7',
 4711:                      'roster'   => '300',
 4712:                    );
 4713:     foreach my $extra ('passback','roster') {
 4714:         my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','add'".');"';
 4715:         $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 4716:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="0" checked="checked"'.$onclick.' />'.
 4717:                       &mt('No').'</label></span>'.('&nbsp;'x2).'<span class="LC_nobreak">'.
 4718:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="1"'.$onclick.' />'.
 4719:                       &mt('Yes').'</label></span></div>'.
 4720:                       '<div class="LC_floatleft" style="display:none;" id="ltitools_'.$extra.'time_add">'.
 4721:                       '<span class="LC_nobreak">'.
 4722:                       &mt("at least [_1] $units{$extra} after launch",
 4723:                           '<input type="text" name="ltitools_'.$extra.'valid_add" value="'.$defaulttimes{$extra}.'" />').
 4724:                       '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 4725:     }
 4726:     $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;'.
 4727:                   '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 4728:     if ($switchserver) {
 4729:         $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 4730:     } else {
 4731:         $datatable .= '<input type="file" name="ltitools_add_image" value="" />';
 4732:     }
 4733:     $datatable .= '</span></fieldset>'.
 4734:                   '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 4735:                   '<span class="LC_nobreak">';
 4736:     foreach my $field (@fields) {
 4737:         my ($id,$onclick,$spacer);
 4738:         if ($field eq 'user') {
 4739:             $id = ' id="ltitools_user_field_add"';
 4740:             $onclick = ' onclick="toggleLTITools(this.form,'."'$field','add'".')"';
 4741:         } else {
 4742:             $spacer = ('&nbsp;' x2);
 4743:         }
 4744:         $datatable .= '<label>'.
 4745:                       '<input type="checkbox" name="ltitools_add_fields" value="'.$field.'"'.$id.$onclick.' />'.
 4746:                       $lt{$field}.'</label>'.$spacer;
 4747:     }
 4748:     $datatable .= '</span>'.
 4749:                   '<div style="display:none;" id="ltitools_user_div_add">'.
 4750:                   '<span class="LC_nobreak"> : '.
 4751:                   '<select name="ltitools_userincdom_add">'.
 4752:                   '<option value="" selected="selected">'.&mt('Select').'</option>'.
 4753:                   '<option value="0">'.&mt('username').'</option>'.
 4754:                   '<option value="1">'.&mt('username:domain').'</option>'.
 4755:                   '</select></span></div></fieldset>';
 4756:     $datatable .= '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 4757:     foreach my $role (@courseroles) {
 4758:         my ($checked,$checkednone);
 4759:         $datatable .= '<td style="text-align: center">'.
 4760:                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 4761:                       '<select name="ltitools_add_roles_'.$role.'">'.
 4762:                       '<option value="" selected="selected">'.&mt('Select').'</option>';
 4763:         foreach my $ltirole (@ltiroles) {
 4764:             $datatable .= '<option value="'.$ltirole.'">'.$ltirole.'</option>';
 4765:         }
 4766:         $datatable .= '</select></td>';
 4767:     }
 4768:     $datatable .= '</tr></table></fieldset>'.
 4769:                   '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 4770:     foreach my $item ('label','title','target','linktext','explanation','append') {
 4771:         $datatable .= '<label>'.
 4772:                       '<input type="checkbox" name="ltitools_courseconfig" value="'.$item.'" checked="checked" />'.
 4773:                       $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 4774:     }
 4775:     $datatable .= '</span></fieldset>'.
 4776:                   '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 4777:                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 4778:                   '<tr><td><span class="LC_nobreak">'.
 4779:                   '<label><input type="checkbox" name="ltitools_add_custom" value="1" />'.
 4780:                   &mt('Add').'</label></span></td><td><input type="text" name="ltitools_add_custom_name" />'.
 4781:                   '</td><td><input type="text" name="ltitools_add_custom_value" /></td></tr>'.
 4782:                   '</table></fieldset>'."\n".
 4783:                   '</td>'."\n".
 4784:                   '</tr>'."\n";
 4785:     $itemcount ++;
 4786:     return $datatable;
 4787: }
 4788: 
 4789: sub ltitools_names {
 4790:     my %lt = &Apache::lonlocal::texthash(
 4791:                                           'title'          => 'Title',
 4792:                                           'version'        => 'Version',
 4793:                                           'msgtype'        => 'Message Type',
 4794:                                           'sigmethod'      => 'Signature Method',
 4795:                                           'url'            => 'URL',
 4796:                                           'key'            => 'Key',
 4797:                                           'lifetime'       => 'Nonce lifetime (s)',
 4798:                                           'secret'         => 'Secret',
 4799:                                           'icon'           => 'Icon',   
 4800:                                           'user'           => 'User',
 4801:                                           'fullname'       => 'Full Name',
 4802:                                           'firstname'      => 'First Name',
 4803:                                           'lastname'       => 'Last Name',
 4804:                                           'email'          => 'E-mail',
 4805:                                           'roles'          => 'Role',
 4806:                                           'window'         => 'Window',
 4807:                                           'tab'            => 'Tab',
 4808:                                           'iframe'         => 'iFrame',
 4809:                                           'height'         => 'Height',
 4810:                                           'width'          => 'Width',
 4811:                                           'linktext'       => 'Default Link Text',
 4812:                                           'explanation'    => 'Default Explanation',
 4813:                                           'passback'       => 'Tool can return grades:',
 4814:                                           'roster'         => 'Tool can retrieve roster:',
 4815:                                           'crstarget'      => 'Display target',
 4816:                                           'crslabel'       => 'Course label',
 4817:                                           'crstitle'       => 'Course title', 
 4818:                                           'crslinktext'    => 'Link Text',
 4819:                                           'crsexplanation' => 'Explanation',
 4820:                                           'crsappend'      => 'Provider URL',
 4821:                                         );
 4822:     return %lt;
 4823: }
 4824: 
 4825: sub print_lti {
 4826:     my ($dom,$settings,$rowtotal) = @_;
 4827:     my $itemcount = 1;
 4828:     my $maxnum = 0;
 4829:     my $css_class;
 4830:     my %ordered;
 4831:     if (ref($settings) eq 'HASH') {
 4832:         foreach my $item (keys(%{$settings})) {
 4833:             if (ref($settings->{$item}) eq 'HASH') {
 4834:                 my $num = $settings->{$item}{'order'};
 4835:                 $ordered{$num} = $item;
 4836:             }
 4837:         }
 4838:     }
 4839:     my $maxnum = scalar(keys(%ordered));
 4840:     my $datatable;
 4841:     my %lt = &lti_names();
 4842:     if (keys(%ordered)) {
 4843:         my @items = sort { $a <=> $b } keys(%ordered);
 4844:         for (my $i=0; $i<@items; $i++) {
 4845:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4846:             my $item = $ordered{$items[$i]};
 4847:             my ($key,$secret,$lifetime,$consumer,$requser,$current);
 4848:             if (ref($settings->{$item}) eq 'HASH') {
 4849:                 $key = $settings->{$item}->{'key'};
 4850:                 $secret = $settings->{$item}->{'secret'};
 4851:                 $lifetime = $settings->{$item}->{'lifetime'};
 4852:                 $consumer = $settings->{$item}->{'consumer'};
 4853:                 $requser = $settings->{$item}->{'requser'};
 4854:                 $current = $settings->{$item};
 4855:             }
 4856:             my $onclickrequser = ' onclick="toggleLTI(this.form,'."'requser','$i'".');"';
 4857:             my %checkedrequser = (
 4858:                                    yes => ' checked="checked"',
 4859:                                    no  => '',
 4860:                                  );
 4861:             if (!$requser) {
 4862:                 $checkedrequser{'no'} = $checkedrequser{'yes'};
 4863:                 $checkedrequser{'yes'} = '';
 4864:             }
 4865:             my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_".$item."'".');"';
 4866:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 4867:                          .'<select name="lti_pos_'.$item.'"'.$chgstr.'>';
 4868:             for (my $k=0; $k<=$maxnum; $k++) {
 4869:                 my $vpos = $k+1;
 4870:                 my $selstr;
 4871:                 if ($k == $i) {
 4872:                     $selstr = ' selected="selected" ';
 4873:                 }
 4874:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4875:             }
 4876:             $datatable .= '</select>'.('&nbsp;'x2).
 4877:                 '<label><input type="checkbox" name="lti_del" value="'.$item.'" />'.
 4878:                 &mt('Delete?').'</label></span></td>'.
 4879:                 '<td colspan="2">'.
 4880:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 4881:                 '<span class="LC_nobreak">'.$lt{'consumer'}.
 4882:                 ':<input type="text" size="15" name="lti_consumer_'.$i.'" value="'.$consumer.'" /></span> '.
 4883:                 ('&nbsp;'x2).
 4884:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_'.$i.'">'.
 4885:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 4886:                 ('&nbsp;'x2).
 4887:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" name="lti_lifetime_'.$i.'"'.
 4888:                 'value="'.$lifetime.'" size="3" /></span>'.
 4889:                 ('&nbsp;'x2).
 4890:                  '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 4891:                  '<label><input type="radio" name="lti_requser_'.$i.'" value="1"'.$onclickrequser.$checkedrequser{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 4892:                  '<label><input type="radio" name="lti_requser_'.$i.'" value="0"'.$onclickrequser.$checkedrequser{no}.' />'.&mt('No').'</label></span>'."\n".
 4893:                 '<br /><br />'.
 4894:                 '<span class="LC_nobreak">'.$lt{'key'}.
 4895:                 ':<input type="text" size="25" name="lti_key_'.$i.'" value="'.$key.'" /></span> '.
 4896:                 ('&nbsp;'x2).
 4897:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 4898:                 '<input type="password" size="20" name="lti_secret_'.$i.'" value="'.$secret.'" />'.
 4899:                 '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.lti_secret_'.$i.'.type='."'text'".' } else { this.form.lti_secret_'.$i.'.type='."'password'".' }" />'.&mt('Visible input').'</label>'.
 4900:                 '<input type="hidden" name="lti_id_'.$i.'" value="'.$item.'" /></span>'.
 4901:                 '</fieldset>'.&lti_options($i,$current,$itemcount,%lt).'</td></tr>';
 4902:             $itemcount ++;
 4903:         }
 4904:     }
 4905:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4906:     my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_add'".');"';
 4907:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 4908:                   '<input type="hidden" name="lti_maxnum" value="'.$maxnum.'" />'."\n".
 4909:                   '<select name="lti_pos_add"'.$chgstr.'>';
 4910:     for (my $k=0; $k<$maxnum+1; $k++) {
 4911:         my $vpos = $k+1;
 4912:         my $selstr;
 4913:         if ($k == $maxnum) {
 4914:             $selstr = ' selected="selected" ';
 4915:         }
 4916:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4917:     }
 4918:     $datatable .= '</select>&nbsp;'."\n".
 4919:                   '<input type="checkbox" name="lti_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 4920:                   '<td colspan="2">'.
 4921:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 4922:                   '<span class="LC_nobreak">'.$lt{'consumer'}.
 4923:                   ':<input type="text" size="15" name="lti_consumer_add" value="" /></span> '."\n".
 4924:                   ('&nbsp;'x2).
 4925:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_add">'.
 4926:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 4927:                   ('&nbsp;'x2).
 4928:                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="3" name="lti_lifetime_add" value="300" /></span> '."\n".
 4929:                   ('&nbsp;'x2).
 4930:                   '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 4931:                   '<label><input type="radio" name="lti_requser_add" value="1" onclick="toggleLTI(this.form,'."'requser','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 4932:                   '<label><input type="radio" name="lti_requser_add" value="0" onclick="toggleLTI(this.form,'."'requser','add'".');" />'.&mt('No').'</label></span>'."\n".
 4933:                   '<br /><br />'.
 4934:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="lti_key_add" value="" /></span> '."\n".
 4935:                   ('&nbsp;'x2).
 4936:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="lti_secret_add" value="" />'.
 4937:                   '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.lti_secret_add.type='."'text'".' } else { this.form.lti_secret_add.type='."'password'".' }" />'.&mt('Visible input').'</label></span> '."\n".
 4938:                   '</fieldset>'.&lti_options('add',undef,$itemcount,%lt).
 4939:                   '</td>'."\n".
 4940:                   '</tr>'."\n";
 4941:     $$rowtotal ++;
 4942:     return $datatable;;
 4943: }
 4944: 
 4945: sub lti_names {
 4946:     my %lt = &Apache::lonlocal::texthash(
 4947:                                           'version'   => 'LTI Version',
 4948:                                           'url'       => 'URL',
 4949:                                           'key'       => 'Key',
 4950:                                           'lifetime'  => 'Nonce lifetime (s)',
 4951:                                           'consumer'  => 'Consumer',
 4952:                                           'secret'    => 'Secret',
 4953:                                           'requser'   => "User's identity sent",
 4954:                                           'email'     => 'Email address',
 4955:                                           'sourcedid' => 'User ID',
 4956:                                           'other'     => 'Other',
 4957:                                           'passback'  => 'Can return grades to Consumer:',
 4958:                                           'roster'    => 'Can retrieve roster from Consumer:',
 4959:                                           'topmenu'   => 'Display LON-CAPA page header',
 4960:                                           'inlinemenu'=> 'Display LON-CAPA inline menu',
 4961:                                         );
 4962:     return %lt;
 4963: }
 4964: 
 4965: sub lti_options {
 4966:     my ($num,$current,$itemcount,%lt) = @_;
 4967:     my (%checked,%rolemaps,$crssecsrc,$userfield,$cidfield,$callback);
 4968:     $checked{'mapuser'}{'sourcedid'} = ' checked="checked"';
 4969:     $checked{'mapcrs'}{'course_offering_sourcedid'} = ' checked="checked"';
 4970:     $checked{'makecrs'}{'N'} = '  checked="checked"';
 4971:     $checked{'mapcrstype'} = {};
 4972:     $checked{'makeuser'} = {};
 4973:     $checked{'selfenroll'} = {};
 4974:     $checked{'crssec'} = {};
 4975:     $checked{'crssecsrc'} = {};
 4976:     $checked{'lcauth'} = {};
 4977:     $checked{'menuitem'} = {};
 4978:     if ($num eq 'add') {
 4979:         $checked{'lcauth'}{'lti'} = ' checked="checked"';
 4980:     }
 4981:     my $userfieldsty = 'none';
 4982:     my $crsfieldsty = 'none';
 4983:     my $crssecfieldsty = 'none';
 4984:     my $secsrcfieldsty = 'none';
 4985:     my $callbacksty = 'none';
 4986:     my $passbacksty = 'none';
 4987:     my $optionsty = 'block';
 4988:     my $lcauthparm;
 4989:     my $lcauthparmstyle = 'display:none';
 4990:     my $lcauthparmtext;
 4991:     my $menusty;
 4992:     my $numinrow = 4;
 4993:     my %menutitles = &ltimenu_titles();
 4994: 
 4995:     if (ref($current) eq 'HASH') {
 4996:         if (!$current->{'requser'}) {
 4997:             $optionsty = 'none';
 4998:         }
 4999:         if (($current->{'mapuser'} ne '') && ($current->{'mapuser'} ne 'lis_person_sourcedid')) {
 5000:             $checked{'mapuser'}{'sourcedid'} = '';
 5001:             if ($current->{'mapuser'} eq 'lis_person_contact_email_primary') {
 5002:                 $checked{'mapuser'}{'email'} = ' checked="checked"'; 
 5003:             } else {
 5004:                 $checked{'mapuser'}{'other'} = ' checked="checked"';
 5005:                 $userfield = $current->{'mapuser'};
 5006:                 $userfieldsty = 'inline-block';
 5007:             }
 5008:         }
 5009:         if (($current->{'mapcrs'} ne '') && ($current->{'mapcrs'} ne 'course_offering_sourcedid')) {
 5010:             $checked{'mapcrs'}{'course_offering_sourcedid'} = '';
 5011:             if ($current->{'mapcrs'} eq 'context_id') {
 5012:                 $checked{'mapcrs'}{'context_id'} = ' checked="checked"'; 
 5013:             } else {
 5014:                 $checked{'mapcrs'}{'other'} = ' checked="checked"';
 5015:                 $cidfield = $current->{'mapcrs'};
 5016:                 $crsfieldsty = 'inline-block';
 5017:             }
 5018:         }
 5019:         if (ref($current->{'mapcrstype'}) eq 'ARRAY') {
 5020:             foreach my $type (@{$current->{'mapcrstype'}}) {
 5021:                 $checked{'mapcrstype'}{$type} = ' checked="checked"';
 5022:             }
 5023:         }
 5024:         if ($current->{'makecrs'}) {
 5025:             $checked{'makecrs'}{'Y'} = '  checked="checked"';
 5026:         }
 5027:         if (ref($current->{'makeuser'}) eq 'ARRAY') {
 5028:             foreach my $role (@{$current->{'makeuser'}}) {
 5029:                 $checked{'makeuser'}{$role} = ' checked="checked"';
 5030:             }
 5031:         }
 5032:         if ($current->{'lcauth'} =~ /^(internal|localauth|krb4|krb5|lti)$/) {
 5033:             $checked{'lcauth'}{$1} = ' checked="checked"';
 5034:             unless (($current->{'lcauth'} eq 'lti') || ($current->{'lcauth'} eq 'internal')) {
 5035:                 $lcauthparm = $current->{'lcauthparm'};
 5036:                 $lcauthparmstyle = 'display:table-row'; 
 5037:                 if ($current->{'lcauth'} eq 'localauth') {
 5038:                     $lcauthparmtext = &mt('Local auth argument');
 5039:                 } else {
 5040:                     $lcauthparmtext = &mt('Kerberos domain');
 5041:                 }
 5042:             }
 5043:         }
 5044:         if (ref($current->{'selfenroll'}) eq 'ARRAY') {
 5045:             foreach my $role (@{$current->{'selfenroll'}}) {
 5046:                 $checked{'selfenroll'}{$role} = ' checked="checked"';
 5047:             }
 5048:         }
 5049:         if (ref($current->{'maproles'}) eq 'HASH') {
 5050:             %rolemaps = %{$current->{'maproles'}};
 5051:         }
 5052:         if ($current->{'section'} ne '') {
 5053:             $checked{'crssec'}{'Y'} = '  checked="checked"'; 
 5054:             $crssecfieldsty = 'inline-block';
 5055:             if ($current->{'section'} eq 'course_section_sourcedid') {
 5056:                 $checked{'crssecsrc'}{'sourcedid'} = ' checked="checked"';
 5057:             } else {
 5058:                 $checked{'crssecsrc'}{'other'} = ' checked="checked"';
 5059:                 $crssecsrc = $current->{'section'};
 5060:                 $secsrcfieldsty = 'inline-block';
 5061:             }
 5062:         } else {
 5063:             $checked{'crssec'}{'N'} = ' checked="checked"';
 5064:         }
 5065:         if ($current->{'callback'} ne '') {
 5066:             $callback = $current->{'callback'};
 5067:             $checked{'callback'}{'Y'} = ' checked="checked"';
 5068:             $callbacksty = 'inline-block';
 5069:         } else {
 5070:             $checked{'callback'}{'N'} = ' checked="checked"';
 5071:         }
 5072:         if ($current->{'topmenu'}) {
 5073:             $checked{'topmenu'}{'Y'} = ' checked="checked"';
 5074:         } else {
 5075:             $checked{'topmenu'}{'N'} = ' checked="checked"';
 5076:         }
 5077:         if ($current->{'inlinemenu'}) {
 5078:             $checked{'inlinemenu'}{'Y'} = ' checked="checked"';
 5079:         } else {
 5080:             $checked{'inlinemenu'}{'N'} = ' checked="checked"';
 5081:         }
 5082:         if (($current->{'topmenu'}) || ($current->{'inlinemenu'})) {
 5083:             $menusty = 'inline-block';
 5084:             if (ref($current->{'lcmenu'}) eq 'ARRAY') {
 5085:                 foreach my $item (@{$current->{'lcmenu'}}) {
 5086:                     if (exists($menutitles{$item})) {
 5087:                         $checked{'menuitem'}{$item} = ' checked="checked"';
 5088:                     }
 5089:                 }
 5090:             }
 5091:         } else {
 5092:             $menusty = 'none';
 5093:         }
 5094:     } else {
 5095:         $checked{'makecrs'}{'N'} = ' checked="checked"';
 5096:         $checked{'crssec'}{'N'} = ' checked="checked"';
 5097:         $checked{'callback'}{'N'} = ' checked="checked"';
 5098:         $checked{'topmenu'}{'N'} = ' checked="checked"';
 5099:         $checked{'inlinemenu'}{'Y'} = ' checked="checked"'; 
 5100:         $checked{'menuitem'}{'grades'} = ' checked="checked"';
 5101:         $menusty = 'inline-block'; 
 5102:     }
 5103:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
 5104:     my %coursetypetitles = &Apache::lonlocal::texthash (
 5105:                                official   => 'Official',
 5106:                                unofficial => 'Unofficial',
 5107:                                community  => 'Community',
 5108:                                textbook   => 'Textbook',
 5109:                                placement  => 'Placement Test',
 5110:                                lti        => 'LTI Provider',
 5111:     );
 5112:     my @authtypes = ('internal','krb4','krb5','localauth');
 5113:     my %shortauth = (
 5114:                      internal => 'int',
 5115:                      krb4 => 'krb4',
 5116:                      krb5 => 'krb5',
 5117:                      localauth  => 'loc'
 5118:                     );
 5119:     my %authnames = &authtype_names();
 5120:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
 5121:     my @lticourseroles = qw(Learner Instructor TeachingAssistant Mentor);
 5122:     my @courseroles = ('cc','in','ta','ep','st');
 5123:     my $onclickuser = ' onclick="toggleLTI(this.form,'."'user','$num'".');"';
 5124:     my $onclickcrs = ' onclick="toggleLTI(this.form,'."'crs','$num'".');"';
 5125:     my $onclicksec = ' onclick="toggleLTI(this.form,'."'sec','$num'".');"';
 5126:     my $onclickcallback = ' onclick="toggleLTI(this.form,'."'callback','$num'".');"';
 5127:     my $onclicksecsrc = ' onclick="toggleLTI(this.form,'."'secsrc','$num'".')"';
 5128:     my $onclicklcauth = ' onclick="toggleLTI(this.form,'."'lcauth','$num'".')"';
 5129:     my $onclickmenu = ' onclick="toggleLTI(this.form,'."'lcmenu','$num'".');"';
 5130:     my $output = '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping users').'</legend>'.
 5131:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('LON-CAPA username').':&nbsp;';
 5132:     foreach my $option ('sourcedid','email','other') {
 5133:         $output .= '<label><input type="radio" name="lti_mapuser_'.$num.'" value="'.$option.'"'.
 5134:                    $checked{'mapuser'}{$option}.$onclickuser.' />'.$lt{$option}.'</label>'.
 5135:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 5136:     }
 5137:     $output .= '</span></div>'.
 5138:                '<div class="LC_floatleft" style="display:'.$userfieldsty.';" id="lti_userfield_'.$num.'">'.
 5139:                '<input type="text" name="lti_customuser_'.$num.'" '.
 5140:                'value="'.$userfield.'" /></div></fieldset>'. 
 5141:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping course roles').'</legend><table><tr>';
 5142:     foreach my $ltirole (@lticourseroles) {
 5143:         my ($selected,$selectnone);
 5144:         if ($rolemaps{$ltirole} eq '') {
 5145:             $selectnone = ' selected="selected"';
 5146:         }
 5147:         $output .= '<td style="text-align: center">'.$ltirole.'<br />'.
 5148:                    '<select name="lti_maprole_'.$ltirole.'_'.$num.'">'.
 5149:                    '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 5150:         foreach my $role (@courseroles) {
 5151:             unless ($selectnone) {
 5152:                 if ($rolemaps{$ltirole} eq $role) {
 5153:                     $selected = ' selected="selected"';
 5154:                 } else {
 5155:                     $selected = '';
 5156:                 }
 5157:             }
 5158:             $output .= '<option value="'.$role.'"'.$selected.'>'.
 5159:                        &Apache::lonnet::plaintext($role,'Course').
 5160:                        '</option>';
 5161:         }
 5162:         $output .= '</select></td>';
 5163:     }
 5164:     $output .= '</tr></table></fieldset>'.
 5165:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Roles which may create user accounts').'</legend>';
 5166:     foreach my $ltirole (@ltiroles) {
 5167:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_makeuser_'.$num.'" value="'.$ltirole.'"'.
 5168:                    $checked{'makeuser'}{$ltirole}.' />'.$ltirole.'</label>&nbsp;</span> ';     
 5169:     }
 5170:     $output .= '</fieldset>'.
 5171:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('New user accounts created for LTI users').'</legend>'.
 5172:                '<table>'.
 5173:                &modifiable_userdata_row('lti','instdata_'.$num,$current,$numinrow,$itemcount).
 5174:                '</table>'.
 5175:                '<table class="LC_nested"><tr><td class="LC_left_item">LON-CAPA Authentication</td>'.
 5176:                '<td class="LC_left_item">';
 5177:     foreach my $auth ('lti',@authtypes) {
 5178:         my $authtext;
 5179:         if ($auth eq 'lti') {
 5180:             $authtext = &mt('None');
 5181:         } else {
 5182:             $authtext = $authnames{$shortauth{$auth}};
 5183:         }
 5184:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="lti_lcauth_'.$num.
 5185:                    '" value="'.$auth.'"'.$checked{'lcauth'}{$auth}.$onclicklcauth.' />'.
 5186:                    $authtext.'</label></span> &nbsp;';
 5187:     }
 5188:     $output .= '</td></tr>'.
 5189:                '<tr id="lti_lcauth_parmrow_'.$num.'" style="'.$lcauthparmstyle.'">'.
 5190:                '<td class="LC_right_item" colspan="2"><span class="LC_nobreak">'.
 5191:                '<span id="lti_lcauth_parmtext_'.$num.'">'.$lcauthparmtext.'</span>'.
 5192:                '<input type="text" name="lti_lcauthparm_'.$num.'" value="" /></span></td></tr>'.
 5193:                '</table></fieldset>'.
 5194:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping courses').'</legend>'.
 5195:                '<div class="LC_floatleft"><span class="LC_nobreak">'.
 5196:                &mt('Unique course identifier').':&nbsp;';
 5197:     foreach my $option ('course_offering_sourcedid','context_id','other') {
 5198:         $output .= '<label><input type="radio" name="lti_mapcrs_'.$num.'" value="'.$option.'"'.
 5199:                    $checked{'mapcrs'}{$option}.$onclickcrs.' />'.$option.'</label>'.
 5200:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 5201:     }
 5202:     $output .= '</span></div><div class="LC_floatleft" style="display:'.$crsfieldsty.';" id="lti_crsfield_'.$num.'">'.
 5203:                '<input type="text" name="lti_mapcrsfield_'.$num.'" value="'.$cidfield.'" />'.
 5204:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>'.
 5205:                '<span class="LC_nobreak">'.&mt('LON-CAPA course type(s)').':&nbsp;';
 5206:     foreach my $type (@coursetypes) {
 5207:         $output .= '<label><input type="checkbox" name="lti_mapcrstype_'.$num.'" value="'.$type.'"'.
 5208:                    $checked{'mapcrstype'}{$type}.' />'.$coursetypetitles{$type}.'</label>'.
 5209:                    ('&nbsp;'x2);
 5210:     }
 5211:     $output .= '</span></fieldset>'.
 5212:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Creating courses').'</legend>'.
 5213:                '<span class="LC_nobreak">'.&mt('Course created (if absent) on Instructor access').':&nbsp;'.
 5214:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="0"'.
 5215:                $checked{'makecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5216:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="1"'.
 5217:                $checked{'makecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 5218:                '</fieldset>'.
 5219:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Roles which may self-enroll').'</legend>';
 5220:     foreach my $lticrsrole (@lticourseroles) {
 5221:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_selfenroll_'.$num.'" value="'.$lticrsrole.'"'.
 5222:                    $checked{'selfenroll'}{$lticrsrole}.' />'.$lticrsrole.'</label>&nbsp;</span> ';
 5223:     }
 5224:     $output .= '</fieldset>'.
 5225:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Course options').'</legend>'.
 5226:                '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Assign users to sections').':&nbsp;'.
 5227:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="0"'.
 5228:                $checked{'crssec'}{'N'}.$onclicksec.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5229:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="1"'.
 5230:                $checked{'crssec'}{'Y'}.$onclicksec.' />'.&mt('Yes').'</label></span></div>'.
 5231:                '<div class="LC_floatleft" style="display:'.$crssecfieldsty.';" id="lti_crssecfield_'.$num.'">'.
 5232:                '<span class="LC_nobreak">'.&mt('From').':<label>'.
 5233:                '<input type="radio" name="lti_crssecsrc_'.$num.'" value="course_section_sourcedid"'.
 5234:                $checked{'crssecsrc'}{'sourcedid'}.$onclicksecsrc.' />'.
 5235:                &mt('Standard field').'</label>'.('&nbsp;'x2).
 5236:                '<label><input type="radio" name="lti_crssecsrc_'.$num.'" value="other"'.
 5237:                $checked{'crssecsrc'}{'other'}.$onclicksecsrc.' />'.&mt('Other').
 5238:                '</label></span></div><div class="LC_floatleft" style="display:'.$secsrcfieldsty.';" id="lti_secsrcfield_'.$num.'">'.
 5239:                '<input type="text" name="lti_customsection_'.$num.'" value="'.$crssecsrc.'" />'.
 5240:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 5241:     my ($pb1p1chk,$pb1p0chk,$onclickpb);
 5242:     foreach my $extra ('roster','passback') {
 5243:         my $checkedon = '';
 5244:         my $checkedoff = ' checked="checked"';
 5245:         if ($extra eq 'passback') {
 5246:             $pb1p1chk = ' checked="checked"';
 5247:             $pb1p0chk = '';
 5248:             $onclickpb = ' onclick="toggleLTI(this.form,'."'passback','$num'".');"'; 
 5249:         } else {
 5250:             $onclickpb = ''; 
 5251:         }
 5252:         if (ref($current) eq 'HASH') {
 5253:             if (($current->{$extra})) {
 5254:                 $checkedon = $checkedoff;
 5255:                 $checkedoff = '';
 5256:                 if ($extra eq 'passback') {
 5257:                     $passbacksty = 'inline-block';
 5258:                 }
 5259:                 if ($current->{'passbackformat'} eq '1.0') {
 5260:                     $pb1p0chk =  ' checked="checked"';
 5261:                     $pb1p1chk = '';
 5262:                 }
 5263:             }
 5264:         }
 5265:         $output .= $lt{$extra}.'&nbsp;'.
 5266:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="0"'.$checkedoff.$onclickpb.' />'.
 5267:                    &mt('No').'</label>'.('&nbsp;'x2).
 5268:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="1"'.$checkedon.$onclickpb.' />'.
 5269:                    &mt('Yes').'</label><br />';
 5270:     }
 5271:     $output .= '<div class="LC_floatleft" style="display:'.$passbacksty.';" id="lti_passback_'.$num.'">'.
 5272:                '<span class="LC_nobreak">'.&mt('Grade format').
 5273:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.1"'.$pb1p1chk.' />'.
 5274:                &mt('Outcomes Service (1.1)').'</label>'.('&nbsp;'x2).
 5275:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.0"'.$pb1p0chk.'/>'.
 5276:                &mt('Outcomes Extension (1.0)').'</label></span></div>'.
 5277:                '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 5278:                '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Callback on logout').':&nbsp;'.
 5279:                '<label><input type="radio" name="lti_callback_'.$num.'" value="0"'.
 5280:                $checked{'callback'}{'N'}.$onclickcallback.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5281:                '<label><input type="radio" name="lti_callback_'.$num.'" value="1"'.
 5282:                $checked{'callback'}{'Y'}.$onclickcallback.' />'.&mt('Yes').'</label></span></div>'.
 5283:                '<div class="LC_floatleft" style="display:'.$callbacksty.';" id="lti_callbackfield_'.$num.'">'.
 5284:                '<span class="LC_nobreak">'.&mt('Parameter').': '.
 5285:                '<input type="text" name="lti_callbackparam_'.$num.'" value="'.$callback.'" /></span>'.
 5286:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>'.
 5287:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Course defaults (Course Coordinator can override)').'</legend>'.
 5288:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'topmenu'}.':&nbsp;'.
 5289:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="0"'.
 5290:                $checked{'topmenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5291:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="1"'.
 5292:                $checked{'topmenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>'.
 5293:                '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 5294:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'inlinemenu'}.':&nbsp;'.
 5295:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="0"'.
 5296:                $checked{'inlinemenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 5297:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="1"'.
 5298:                $checked{'inlinemenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>';
 5299:      $output .='<div style="padding:0;clear:both;margin:0;border:0"></div>'. 
 5300:                '<div class="LC_floatleft" style="display:'.$menusty.';" id="lti_menufield_'.$num.'">'.
 5301:                '<span class="LC_nobreak">'.&mt('Menu items').':&nbsp;';
 5302:     foreach my $type ('fullname','coursetitle','role','logout','grades') {
 5303:         $output .= '<label><input type="checkbox" name="lti_menuitem_'.$num.'" value="'.$type.'"'.
 5304:                    $checked{'menuitem'}{$type}.' />'.$menutitles{$type}.'</label>'.
 5305:                    ('&nbsp;'x2);
 5306:     }
 5307:     $output .= '</span></div></fieldset>';
 5308: #        '<fieldset><legend>'.&mt('Assigning author roles').'</legend>';
 5309: #
 5310: #    $output .= '</fieldset>'.
 5311: #        '<fieldset><legend>'.&mt('Assigning domain roles').'</legend>';
 5312:     return $output;
 5313: }
 5314: 
 5315: sub ltimenu_titles {
 5316:     return &Apache::lonlocal::texthash(
 5317:                                         fullname    => 'Full name',
 5318:                                         coursetitle => 'Course title',
 5319:                                         role        => 'Role',
 5320:                                         logout      => 'Logout',
 5321:                                         grades      => 'Grades',
 5322:     );
 5323: }
 5324: 
 5325: sub print_coursedefaults {
 5326:     my ($position,$dom,$settings,$rowtotal) = @_;
 5327:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 5328:     my $itemcount = 1;
 5329:     my %choices =  &Apache::lonlocal::texthash (
 5330:         canuse_pdfforms      => 'Course/Community users can create/upload PDF forms',
 5331:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 5332:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 5333:         coursecredits        => 'Credits can be specified for courses',
 5334:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 5335:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 5336:         texengine            => 'Default method to display mathematics',
 5337:         postsubmit           => 'Disable submit button/keypress following student submission',
 5338:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 5339:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 5340:     );
 5341:     my %staticdefaults = (
 5342:                            anonsurvey_threshold => 10,
 5343:                            uploadquota          => 500,
 5344:                            postsubmit           => 60,
 5345:                            mysqltables          => 172800,
 5346:                          );
 5347:     if ($position eq 'top') {
 5348:         %defaultchecked = (
 5349:                             'canuse_pdfforms' => 'off',
 5350:                             'uselcmath'       => 'on',
 5351:                             'usejsme'         => 'on',
 5352:                             'canclone'        => 'none',
 5353:                           );
 5354:         @toggles = ('canuse_pdfforms','uselcmath','usejsme');
 5355:         my $deftex = $Apache::lonnet::deftex;
 5356:         if (ref($settings) eq 'HASH') {
 5357:             if ($settings->{'texengine'}) {
 5358:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 5359:                     $deftex = $settings->{'texengine'};
 5360:                 }
 5361:             }
 5362:         }
 5363:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5364:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 5365:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 5366:                        '</span></td><td class="LC_right_item">'.
 5367:                        '<select name="texengine">'."\n";
 5368:         my %texoptions = (
 5369:                             MathJax  => 'MathJax',
 5370:                             mimetex  => &mt('Convert to Images'),
 5371:                             tth      => &mt('TeX to HTML'),
 5372:                          );
 5373:         foreach my $renderer ('MathJax','mimetex','tth') {
 5374:             my $selected = '';
 5375:             if ($renderer eq $deftex) {
 5376:                 $selected = ' selected="selected"';
 5377:             }
 5378:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 5379:         }
 5380:         $mathdisp .= '</select></td></tr>'."\n";
 5381:         $itemcount ++;
 5382:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 5383:                                                      \%choices,$itemcount);
 5384:         $datatable = $mathdisp.$datatable;
 5385:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5386:         $datatable .=
 5387:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 5388:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 5389:             '</span></td><td class="LC_left_item">';
 5390:         my $currcanclone = 'none';
 5391:         my $onclick;
 5392:         my @cloneoptions = ('none','domain');
 5393:         my %clonetitles = (
 5394:                              none     => 'No additional course requesters',
 5395:                              domain   => "Any course requester in course's domain",
 5396:                              instcode => 'Course requests for official courses ...',
 5397:                           );
 5398:         my (%codedefaults,@code_order,@posscodes);
 5399:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 5400:                                                     \@code_order) eq 'ok') {
 5401:             if (@code_order > 0) {
 5402:                 push(@cloneoptions,'instcode');
 5403:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 5404:             }
 5405:         }
 5406:         if (ref($settings) eq 'HASH') {
 5407:             if ($settings->{'canclone'}) {
 5408:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 5409:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 5410:                         if (@code_order > 0) {
 5411:                             $currcanclone = 'instcode';
 5412:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 5413:                         }
 5414:                     }
 5415:                 } elsif ($settings->{'canclone'} eq 'domain') {
 5416:                     $currcanclone = $settings->{'canclone'};
 5417:                 }
 5418:             }
 5419:         }
 5420:         foreach my $option (@cloneoptions) {
 5421:             my ($checked,$additional);
 5422:             if ($currcanclone eq $option) {
 5423:                 $checked = ' checked="checked"';
 5424:             }
 5425:             if ($option eq 'instcode') {
 5426:                 if (@code_order) {
 5427:                     my $show = 'none';
 5428:                     if ($checked) {
 5429:                         $show = 'block';
 5430:                     }
 5431:                     $additional = '<div id="cloneinstcode" style="display:'.$show.';" />'.
 5432:                                   &mt('Institutional codes for new and cloned course have identical:').
 5433:                                   '<br />';
 5434:                     foreach my $item (@code_order) {
 5435:                         my $codechk;
 5436:                         if ($checked) {
 5437:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 5438:                                 $codechk = ' checked="checked"';
 5439:                             }
 5440:                         }
 5441:                         $additional .= '<label>'.
 5442:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 5443:                                        $item.'</label>';
 5444:                     }
 5445:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 5446:                 }
 5447:             }
 5448:             $datatable .=
 5449:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 5450:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 5451:                 '</label>&nbsp;'.$additional.'</span><br />';
 5452:         }
 5453:         $datatable .= '</td>'.
 5454:                       '</tr>';
 5455:         $itemcount ++;
 5456:     } else {
 5457:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5458:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 5459:         my $currusecredits = 0;
 5460:         my $postsubmitclient = 1;
 5461:         my @types = ('official','unofficial','community','textbook','placement');
 5462:         if (ref($settings) eq 'HASH') {
 5463:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 5464:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 5465:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 5466:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 5467:                 }
 5468:             }
 5469:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 5470:                 foreach my $type (@types) {
 5471:                     next if ($type eq 'community');
 5472:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 5473:                     if ($defcredits{$type} ne '') {
 5474:                         $currusecredits = 1;
 5475:                     }
 5476:                 }
 5477:             }
 5478:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 5479:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 5480:                     $postsubmitclient = 0;
 5481:                     foreach my $type (@types) {
 5482:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5483:                     }
 5484:                 } else {
 5485:                     foreach my $type (@types) {
 5486:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 5487:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 5488:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 5489:                             } else {
 5490:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5491:                             }
 5492:                         } else {
 5493:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5494:                         }
 5495:                     }
 5496:                 }
 5497:             } else {
 5498:                 foreach my $type (@types) {
 5499:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5500:                 }
 5501:             }
 5502:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 5503:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 5504:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 5505:                 }
 5506:             } else {
 5507:                 foreach my $type (@types) {
 5508:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 5509:                 }
 5510:             }
 5511:         } else {
 5512:             foreach my $type (@types) {
 5513:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 5514:             }
 5515:         }
 5516:         if (!$currdefresponder) {
 5517:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 5518:         } elsif ($currdefresponder < 1) {
 5519:             $currdefresponder = 1;
 5520:         }
 5521:         foreach my $type (@types) {
 5522:             if ($curruploadquota{$type} eq '') {
 5523:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 5524:             }
 5525:         }
 5526:         $datatable .=
 5527:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5528:                 $choices{'anonsurvey_threshold'}.
 5529:                 '</span></td>'.
 5530:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 5531:                 '<input type="text" name="anonsurvey_threshold"'.
 5532:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 5533:                 '</td></tr>'."\n";
 5534:         $itemcount ++;
 5535:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5536:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5537:                       $choices{'uploadquota'}.
 5538:                       '</span></td>'.
 5539:                       '<td style="text-align: right" class="LC_right_item">'.
 5540:                       '<table><tr>';
 5541:         foreach my $type (@types) {
 5542:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 5543:                            '<input type="text" name="uploadquota_'.$type.'"'.
 5544:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 5545:         }
 5546:         $datatable .= '</tr></table></td></tr>'."\n";
 5547:         $itemcount ++;
 5548:         my $onclick = "toggleDisplay(this.form,'credits');";
 5549:         my $display = 'none';
 5550:         if ($currusecredits) {
 5551:             $display = 'block';
 5552:         }
 5553:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 5554:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 5555:         foreach my $type (@types) {
 5556:             next if ($type eq 'community');
 5557:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 5558:                            '<input type="text" name="'.$type.'_credits"'.
 5559:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 5560:         }
 5561:         $additional .= '</tr></table></div>'."\n";
 5562:         %defaultchecked = ('coursecredits' => 'off');
 5563:         @toggles = ('coursecredits');
 5564:         my $current = {
 5565:                         'coursecredits' => $currusecredits,
 5566:                       };
 5567:         (my $table,$itemcount) =
 5568:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 5569:                                \%choices,$itemcount,$onclick,$additional,'left');
 5570:         $datatable .= $table;
 5571:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 5572:         my $display = 'none';
 5573:         if ($postsubmitclient) {
 5574:             $display = 'block';
 5575:         }
 5576:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 5577:                       &mt('Number of seconds submit is disabled').'<br />'.
 5578:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 5579:                       '<table><tr>';
 5580:         foreach my $type (@types) {
 5581:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 5582:                            '<input type="text" name="'.$type.'_timeout" value="'.
 5583:                            $deftimeout{$type}.'" size="5" /></td>';
 5584:         }
 5585:         $additional .= '</tr></table></div>'."\n";
 5586:         %defaultchecked = ('postsubmit' => 'on');
 5587:         @toggles = ('postsubmit');
 5588:         $current = {
 5589:                        'postsubmit' => $postsubmitclient,
 5590:                    };
 5591:         ($table,$itemcount) =
 5592:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 5593:                                \%choices,$itemcount,$onclick,$additional,'left');
 5594:         $datatable .= $table;
 5595:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5596:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5597:                       $choices{'mysqltables'}.
 5598:                       '</span></td>'.
 5599:                       '<td style="text-align: right" class="LC_right_item">'.
 5600:                       '<table><tr>';
 5601:         foreach my $type (@types) {
 5602:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 5603:                            '<input type="text" name="mysqltables_'.$type.'"'.
 5604:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 5605:         }
 5606:         $datatable .= '</tr></table></td></tr>'."\n";
 5607:         $itemcount ++;
 5608: 
 5609:     }
 5610:     $$rowtotal += $itemcount;
 5611:     return $datatable;
 5612: }
 5613: 
 5614: sub print_selfenrollment {
 5615:     my ($position,$dom,$settings,$rowtotal) = @_;
 5616:     my ($css_class,$datatable);
 5617:     my $itemcount = 1;
 5618:     my @types = ('official','unofficial','community','textbook','placement');
 5619:     if (($position eq 'top') || ($position eq 'middle')) {
 5620:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 5621:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 5622:         my @rows;
 5623:         my $key;
 5624:         if ($position eq 'top') {
 5625:             $key = 'admin'; 
 5626:             if (ref($rowsref) eq 'ARRAY') {
 5627:                 @rows = @{$rowsref};
 5628:             }
 5629:         } elsif ($position eq 'middle') {
 5630:             $key = 'default';
 5631:             @rows = ('types','registered','approval','limit');
 5632:         }
 5633:         foreach my $row (@rows) {
 5634:             if (defined($titlesref->{$row})) {
 5635:                 $itemcount ++;
 5636:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5637:                 $datatable .= '<tr'.$css_class.'>'.
 5638:                               '<td>'.$titlesref->{$row}.'</td>'.
 5639:                               '<td class="LC_left_item">'.
 5640:                               '<table><tr>';
 5641:                 my (%current,%currentcap);
 5642:                 if (ref($settings) eq 'HASH') {
 5643:                     if (ref($settings->{$key}) eq 'HASH') {
 5644:                         foreach my $type (@types) {
 5645:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 5646:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 5647:                             }
 5648:                             if (($row eq 'limit') && ($key eq 'default')) {
 5649:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 5650:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 5651:                                 }
 5652:                             }
 5653:                         }
 5654:                     }
 5655:                 }
 5656:                 my %roles = (
 5657:                              '0' => &Apache::lonnet::plaintext('dc'),
 5658:                             ); 
 5659:             
 5660:                 foreach my $type (@types) {
 5661:                     unless (($row eq 'registered') && ($key eq 'default')) {
 5662:                         $datatable .= '<th>'.&mt($type).'</th>';
 5663:                     }
 5664:                 }
 5665:                 unless (($row eq 'registered') && ($key eq 'default')) {
 5666:                     $datatable .= '</tr><tr>';
 5667:                 }
 5668:                 foreach my $type (@types) {
 5669:                     if ($type eq 'community') {
 5670:                         $roles{'1'} = &mt('Community personnel');
 5671:                     } else {
 5672:                         $roles{'1'} = &mt('Course personnel');
 5673:                     }
 5674:                     $datatable .= '<td style="vertical-align: top">';
 5675:                     if ($position eq 'top') {
 5676:                         my %checked;
 5677:                         if ($current{$type} eq '0') {
 5678:                             $checked{'0'} = ' checked="checked"';
 5679:                         } else {
 5680:                             $checked{'1'} = ' checked="checked"';
 5681:                         }
 5682:                         foreach my $role ('1','0') {
 5683:                             $datatable .= '<span class="LC_nobreak"><label>'.
 5684:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 5685:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 5686:                                           $roles{$role}.'</label></span> ';
 5687:                         }
 5688:                     } else {
 5689:                         if ($row eq 'types') {
 5690:                             my %checked;
 5691:                             if ($current{$type} =~ /^(all|dom)$/) {
 5692:                                 $checked{$1} = ' checked="checked"';
 5693:                             } else {
 5694:                                 $checked{''} = ' checked="checked"';
 5695:                             }
 5696:                             foreach my $val ('','dom','all') {
 5697:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5698:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5699:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5700:                             }
 5701:                         } elsif ($row eq 'registered') {
 5702:                             my %checked;
 5703:                             if ($current{$type} eq '1') {
 5704:                                 $checked{'1'} = ' checked="checked"';
 5705:                             } else {
 5706:                                 $checked{'0'} = ' checked="checked"';
 5707:                             }
 5708:                             foreach my $val ('0','1') {
 5709:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5710:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5711:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5712:                             }
 5713:                         } elsif ($row eq 'approval') {
 5714:                             my %checked;
 5715:                             if ($current{$type} =~ /^([12])$/) {
 5716:                                 $checked{$1} = ' checked="checked"';
 5717:                             } else {
 5718:                                 $checked{'0'} = ' checked="checked"';
 5719:                             }
 5720:                             for my $val (0..2) {
 5721:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5722:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5723:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5724:                             }
 5725:                         } elsif ($row eq 'limit') {
 5726:                             my %checked;
 5727:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 5728:                                 $checked{$1} = ' checked="checked"';
 5729:                             } else {
 5730:                                 $checked{'none'} = ' checked="checked"';
 5731:                             }
 5732:                             my $cap;
 5733:                             if ($currentcap{$type} =~ /^\d+$/) {
 5734:                                 $cap = $currentcap{$type};
 5735:                             }
 5736:                             foreach my $val ('none','allstudents','selfenrolled') {
 5737:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 5738:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 5739:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 5740:                             }
 5741:                             $datatable .= '<br />'.
 5742:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 5743:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 5744:                                           '</span>'; 
 5745:                         }
 5746:                     }
 5747:                     $datatable .= '</td>';
 5748:                 }
 5749:                 $datatable .= '</tr>';
 5750:             }
 5751:             $datatable .= '</table></td></tr>';
 5752:         }
 5753:     } elsif ($position eq 'bottom') {
 5754:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 5755:     }
 5756:     $$rowtotal += $itemcount;
 5757:     return $datatable;
 5758: }
 5759: 
 5760: sub print_validation_rows {
 5761:     my ($caller,$dom,$settings,$rowtotal) = @_;
 5762:     my ($itemsref,$namesref,$fieldsref);
 5763:     if ($caller eq 'selfenroll') { 
 5764:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 5765:     } elsif ($caller eq 'requestcourses') {
 5766:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 5767:     }
 5768:     my %currvalidation;
 5769:     if (ref($settings) eq 'HASH') {
 5770:         if (ref($settings->{'validation'}) eq 'HASH') {
 5771:             %currvalidation = %{$settings->{'validation'}};
 5772:         }
 5773:     }
 5774:     my $datatable;
 5775:     my $itemcount = 0;
 5776:     foreach my $item (@{$itemsref}) {
 5777:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5778:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 5779:                       $namesref->{$item}.
 5780:                       '</span></td>'.
 5781:                       '<td class="LC_left_item">';
 5782:         if (($item eq 'url') || ($item eq 'button')) {
 5783:             $datatable .= '<span class="LC_nobreak">'.
 5784:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 5785:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 5786:         } elsif ($item eq 'fields') {
 5787:             my @currfields;
 5788:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 5789:                 @currfields = @{$currvalidation{$item}};
 5790:             }
 5791:             foreach my $field (@{$fieldsref}) {
 5792:                 my $check = '';
 5793:                 if (grep(/^\Q$field\E$/,@currfields)) {
 5794:                     $check = ' checked="checked"';
 5795:                 }
 5796:                 $datatable .= '<span class="LC_nobreak"><label>'.
 5797:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 5798:                               ' value="'.$field.'"'.$check.' />'.$field.
 5799:                               '</label></span> ';
 5800:             }
 5801:         } elsif ($item eq 'markup') {
 5802:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 5803:                            $currvalidation{$item}.
 5804:                               '</textarea>';
 5805:         }
 5806:         $datatable .= '</td></tr>'."\n";
 5807:         if (ref($rowtotal)) {
 5808:             $itemcount ++;
 5809:         }
 5810:     }
 5811:     if ($caller eq 'requestcourses') {
 5812:         my %currhash;
 5813:         if (ref($settings) eq 'HASH') {
 5814:             if (ref($settings->{'validation'}) eq 'HASH') {
 5815:                 if ($settings->{'validation'}{'dc'} ne '') {
 5816:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 5817:                 }
 5818:             }
 5819:         }
 5820:         my $numinrow = 2;
 5821:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 5822:                                                        'validationdc',%currhash);
 5823:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 5824:         $datatable .= '<tr'.$css_class.'><td>';
 5825:         if ($numdc > 1) {
 5826:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 5827:         } else {
 5828:             $datatable .=  &mt('Course creation processed as: ');
 5829:         }
 5830:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 5831:         $itemcount ++;
 5832:     }
 5833:     if (ref($rowtotal)) {
 5834:         $$rowtotal += $itemcount;
 5835:     }
 5836:     return $datatable;
 5837: }
 5838: 
 5839: sub print_privacy {
 5840:     my ($position,$dom,$settings,$rowtotal) = @_;
 5841:     my ($datatable,$css_class,$numinrow,@items,%names,$othertitle,$usertypes,$types);
 5842:     my $itemcount = 0;
 5843:     unless ($position eq 'top') {
 5844:         @items = ('domain','author','course','community');
 5845:         %names = &Apache::lonlocal::texthash (
 5846:                      domain => 'Assigned domain role(s)',
 5847:                      author => 'Assigned co-author role(s)',
 5848:                      course => 'Assigned course role(s)',
 5849:                      community => 'Assigned community role',
 5850:                  );
 5851:         $numinrow = 4;
 5852:         ($othertitle,$usertypes,$types) =
 5853:             &Apache::loncommon::sorted_inst_types($dom);
 5854:     }
 5855:     if (($position eq 'top') || ($position eq 'middle')) {
 5856:         my (%by_ip,%by_location,@intdoms,@instdoms);
 5857:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 5858:         if ($position eq 'top') {
 5859:             my %curr;
 5860:             my @options = ('none','user','domain','auto');
 5861:             my %titles = &Apache::lonlocal::texthash (
 5862:                 none   => 'Not allowed',
 5863:                 user   => 'User authorizes',
 5864:                 domain => 'DC authorizes',
 5865:                 auto   => 'Unrestricted',
 5866:                 instdom => 'Other domain shares institution/provider',
 5867:                 extdom => 'Other domain has different institution/provider',
 5868:             );
 5869:             my %names = &Apache::lonlocal::texthash (
 5870:                 domain => 'Domain role',
 5871:                 author => 'Co-author role',
 5872:                 course => 'Course role',
 5873:                 community => 'Community role',
 5874:             );
 5875:             my $primary_id = &Apache::lonnet::domain($dom,'primary');
 5876:             my $intdom = &Apache::lonnet::internet_dom($primary_id);
 5877:             foreach my $domtype ('instdom','extdom') {
 5878:                 my (%checked,$skip);
 5879:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5880:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$domtype}.'</td>'.
 5881:                               '<td class="LC_left_item">';
 5882:                 if ($domtype eq 'instdom') {
 5883:                     unless (@instdoms > 1) {
 5884:                         $datatable .= &mt('Nothing to set, as no domains besides [_1] are hosted by [_2]',$dom,$intdom);
 5885:                         $skip = 1;
 5886:                     }
 5887:                 } elsif ($domtype eq 'extdom') {
 5888:                     if (keys(%by_location) == 0) {
 5889:                         $datatable .= &mt('Nothing to set, as no other hosts besides [_1]',$intdom);
 5890:                         $skip = 1;
 5891:                     }
 5892:                 }
 5893:                 unless ($skip) {
 5894:                     foreach my $roletype ('domain','author','course','community') {
 5895:                         $checked{'auto'} = ' checked="checked"';
 5896:                         if (ref($settings) eq 'HASH') {
 5897:                             if (ref($settings->{approval}) eq 'HASH') {
 5898:                                 if (ref($settings->{approval}->{$domtype}) eq 'HASH') {
 5899:                                     if ($settings->{approval}->{$domtype}->{$roletype}=~ /^(none|user|domain)$/) {
 5900:                                         $checked{$1} = ' checked="checked"';
 5901:                                         $checked{'auto'} = '';
 5902:                                     }
 5903:                                 }
 5904:                             }
 5905:                         }
 5906:                         $datatable .= '<fieldset><legend>'.$names{$roletype}.'</legend>';
 5907:                         foreach my $option (@options) {
 5908:                             $datatable .= '<span class="LC_nobreak"><label>'.
 5909:                                           '<input type="radio" name="privacy_approval_'.$domtype.'_'.$roletype.'" '.
 5910:                                           'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 5911:                                           '</label></span>&nbsp; ';
 5912:                         }
 5913:                         $datatable .= '</fieldset>';
 5914:                     }
 5915:                 }
 5916:                 $datatable .= '</td></tr>';
 5917:                 $itemcount ++;
 5918:             }
 5919:         } elsif ($position eq 'middle') {
 5920:             if ((@instdoms > 1) || (keys(%by_location) > 0)) {
 5921:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5922:                     foreach my $item (@{$types}) {
 5923:                         $datatable .= &modifiable_userdata_row('privacy','othdom_'.$item,$settings,
 5924:                                                                $numinrow,$itemcount,'','','','','',
 5925:                                                                '',$usertypes->{$item});
 5926:                         $itemcount ++;
 5927:                     }
 5928:                 }
 5929:                 $datatable .= &modifiable_userdata_row('privacy','othdom_default',$settings,
 5930:                                                        $numinrow,$itemcount,'','','','','',
 5931:                                                        '',$othertitle);
 5932:                 $itemcount ++;
 5933:             } else {
 5934:                 my (@insttypes,%insttitles);
 5935:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 5936:                     @insttypes = @{$types};
 5937:                     %insttitles = %{$usertypes};
 5938:                 }
 5939:                 foreach my $item (@insttypes,'default') {
 5940:                     my $title;
 5941:                     if ($item eq 'default') {
 5942:                         $title = $othertitle;
 5943:                     } else {
 5944:                         $title = $insttitles{$item};
 5945:                     }
 5946:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5947:                     $datatable .= '<tr'.$css_class.'>'.
 5948:                                   '<td class="LC_left_item">'.$title.'</td>'.
 5949:                                   '<td class="LC_left_item">'.
 5950:                                   &mt('Nothing to set here, as there are no other domains').
 5951:                                   '</td></tr>';
 5952:                     $itemcount ++;
 5953:                 }
 5954:             }
 5955:         }
 5956:     } else {
 5957:         my $prefix;
 5958:         if ($position eq 'lower') {
 5959:             $prefix = 'priv';
 5960:         } else {
 5961:             $prefix = 'unpriv';
 5962:         }
 5963:         foreach my $item (@items) {
 5964:             $datatable .= &modifiable_userdata_row('privacy',$prefix.'_'.$item,$settings,
 5965:                                                    $numinrow,$itemcount,'','','','','',
 5966:                                                    '',$names{$item});
 5967:             $itemcount ++;
 5968:         }
 5969:     }
 5970:     if (ref($rowtotal)) {
 5971:         $$rowtotal += $itemcount;
 5972:     }
 5973:     return $datatable;
 5974: }
 5975: 
 5976: sub print_passwords {
 5977:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 5978:     my ($datatable,$css_class);
 5979:     my $itemcount = 0;
 5980:     my %titles = &Apache::lonlocal::texthash (
 5981:         captcha        => '"Forgot Password" CAPTCHA validation',
 5982:         link           => 'Reset link expiration (hours)',
 5983:         case           => 'Case-sensitive usernames/e-mail',
 5984:         prelink        => 'Information required (form 1)',
 5985:         postlink       => 'Information required (form 2)',
 5986:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 5987:         customtext     => 'Domain specific text (HTML)',
 5988:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 5989:         intauth_check  => 'Check bcrypt cost if authenticated',
 5990:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 5991:         permanent      => 'Permanent e-mail address',
 5992:         critical       => 'Critical notification address',
 5993:         notify         => 'Notification address',
 5994:         min            => 'Minimum password length',
 5995:         max            => 'Maximum password length',
 5996:         chars          => 'Required characters',
 5997:         expire         => 'Password expiration (days)',
 5998:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 5999:     );
 6000:     if ($position eq 'top') {
 6001:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6002:         my $shownlinklife = 2;
 6003:         my $prelink = 'both';
 6004:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 6005:         if (ref($settings) eq 'HASH') {
 6006:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 6007:                 $shownlinklife = $settings->{resetlink};
 6008:             }
 6009:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 6010:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 6011:             }
 6012:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 6013:                 $prelink = $settings->{resetprelink};
 6014:             }
 6015:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 6016:                 %postlink = %{$settings->{resetpostlink}};
 6017:             }
 6018:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 6019:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 6020:             }
 6021:             if ($settings->{resetremove}) {
 6022:                 $nostdtext = 1;
 6023:             }
 6024:             if ($settings->{resetcustom}) {
 6025:                 $customurl = $settings->{resetcustom};
 6026:             }
 6027:         } else {
 6028:             if (ref($types) eq 'ARRAY') {
 6029:                 foreach my $item (@{$types}) {
 6030:                     $casesens{$item} = 1;
 6031:                     $postlink{$item} = ['username','email'];
 6032:                 }
 6033:             }
 6034:             $casesens{'default'} = 1;
 6035:             $postlink{'default'} = ['username','email'];
 6036:             $prelink = 'both';
 6037:             %emailsrc = (
 6038:                           permanent => 1,
 6039:                           critical  => 1,
 6040:                           notify    => 1,
 6041:             );
 6042:         }
 6043:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 6044:         $itemcount ++;
 6045:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6046:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 6047:                       '<td class="LC_left_item">'.
 6048:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 6049:                       'name="passwords_link" size="3" /></td></tr>';
 6050:         $itemcount ++;
 6051:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6052:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 6053:                       '<td class="LC_left_item">';
 6054:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6055:             foreach my $item (@{$types}) {
 6056:                 my $checkedcase;
 6057:                 if ($casesens{$item}) {
 6058:                     $checkedcase = ' checked="checked"';
 6059:                 }
 6060:                 $datatable .= '<span class="LC_nobreak"><label>'.
 6061:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 6062:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 6063:                               '</span>&nbsp;&nbsp; ';
 6064:             }
 6065:         }
 6066:         my $checkedcase;
 6067:         if ($casesens{'default'}) {
 6068:             $checkedcase = ' checked="checked"';
 6069:         }
 6070:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 6071:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 6072:                       $othertitle.'</label></span></td>';
 6073:         $itemcount ++;
 6074:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6075:         my %checkedpre = (
 6076:                              both => ' checked="checked"',
 6077:                              either => '',
 6078:                          );
 6079:         if ($prelink eq 'either') {
 6080:             $checkedpre{either} = ' checked="checked"';
 6081:             $checkedpre{both} = '';
 6082:         }
 6083:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 6084:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6085:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 6086:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 6087:                       '<span class="LC_nobreak"><label>'.
 6088:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 6089:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 6090:         $itemcount ++;
 6091:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6092:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 6093:                       '<td class="LC_left_item">';
 6094:         my %postlinked;
 6095:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6096:             foreach my $item (@{$types}) {
 6097:                 undef(%postlinked);
 6098:                 $datatable .= '<fieldset style="display: inline-block;">'.
 6099:                               '<legend>'.$usertypes->{$item}.'</legend>';
 6100:                 if (ref($postlink{$item}) eq 'ARRAY') {
 6101:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 6102:                 }
 6103:                 foreach my $field ('email','username') {
 6104:                     my $checked;
 6105:                     if ($postlinked{$field}) {
 6106:                         $checked = ' checked="checked"';
 6107:                     }
 6108:                     $datatable .= '<span class="LC_nobreak"><label>'.
 6109:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 6110:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 6111:                                   '<span>&nbsp;&nbsp; ';
 6112:                 }
 6113:                 $datatable .= '</fieldset>';
 6114:             }
 6115:         }
 6116:         if (ref($postlink{'default'}) eq 'ARRAY') {
 6117:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 6118:         }
 6119:         $datatable .= '<fieldset style="display: inline-block;">'.
 6120:                       '<legend>'.$othertitle.'</legend>';
 6121:         foreach my $field ('email','username') {
 6122:             my $checked;
 6123:             if ($postlinked{$field}) {
 6124:                 $checked = ' checked="checked"';
 6125:             }
 6126:             $datatable .= '<span class="LC_nobreak"><label>'.
 6127:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 6128:                           $field.'"'.$checked.' />'.$field.'</label>'.
 6129:                           '<span>&nbsp;&nbsp; ';
 6130:         }
 6131:         $datatable .= '</fieldset></td></tr>';
 6132:         $itemcount ++;
 6133:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6134:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 6135:                       '<td class="LC_left_item">';
 6136:         foreach my $type ('permanent','critical','notify') {
 6137:             my $checkedemail;
 6138:             if ($emailsrc{$type}) {
 6139:                 $checkedemail = ' checked="checked"';
 6140:             }
 6141:             $datatable .= '<span class="LC_nobreak"><label>'.
 6142:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 6143:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 6144:                           '<span>&nbsp;&nbsp; ';
 6145:         }
 6146:         $datatable .= '</td></tr>';
 6147:         $itemcount ++;
 6148:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6149:         my $switchserver = &check_switchserver($dom,$confname);
 6150:         my ($showstd,$noshowstd);
 6151:         if ($nostdtext) {
 6152:             $noshowstd = ' checked="checked"';
 6153:         } else {
 6154:             $showstd = ' checked="checked"';
 6155:         }
 6156:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 6157:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6158:                       &mt('Retain standard text:').
 6159:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 6160:                       &mt('Yes').'</label>'.'&nbsp;'.
 6161:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 6162:                       &mt('No').'</label></span><br />'.
 6163:                       '<span class="LC_fontsize_small">'.
 6164:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 6165:                       &mt('Include custom text:');
 6166:         if ($customurl) {
 6167:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('custom text'),600,500,
 6168:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 6169:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 6170:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 6171:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 6172:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 6173:         }
 6174:         if ($switchserver) {
 6175:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 6176:         } else {
 6177:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 6178:                          '<input type="file" name="passwords_customfile" /></span>';
 6179:         }
 6180:         $datatable .= '</td></tr>';
 6181:     } elsif ($position eq 'middle') {
 6182:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 6183:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 6184:         my %defaults;
 6185:         if (ref($domconf{'defaults'}) eq 'HASH') {
 6186:             %defaults = %{$domconf{'defaults'}};
 6187:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 6188:                 $defaults{'intauth_cost'} = 10;
 6189:             }
 6190:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 6191:                 $defaults{'intauth_check'} = 0;
 6192:             }
 6193:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 6194:                 $defaults{'intauth_switch'} = 0;
 6195:             }
 6196:         } else {
 6197:             %defaults = (
 6198:                           'intauth_cost'   => 10,
 6199:                           'intauth_check'  => 0,
 6200:                           'intauth_switch' => 0,
 6201:                         );
 6202:         }
 6203:         foreach my $item (@items) {
 6204:             if ($itemcount%2) {
 6205:                 $css_class = '';
 6206:             } else {
 6207:                 $css_class = ' class="LC_odd_row" ';
 6208:             }
 6209:             $datatable .= '<tr'.$css_class.'>'.
 6210:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 6211:                           '</span></td><td class="LC_left_item" colspan="3">';
 6212:             if ($item eq 'intauth_switch') {
 6213:                 my @options = (0,1,2);
 6214:                 my %optiondesc = &Apache::lonlocal::texthash (
 6215:                                    0 => 'No',
 6216:                                    1 => 'Yes',
 6217:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 6218:                                  );
 6219:                 $datatable .= '<table width="100%">';
 6220:                 foreach my $option (@options) {
 6221:                     my $checked = ' ';
 6222:                     if ($defaults{$item} eq $option) {
 6223:                         $checked = ' checked="checked"';
 6224:                     }
 6225:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 6226:                                   '<label><input type="radio" name="'.$item.
 6227:                                   '" value="'.$option.'"'.$checked.' />'.
 6228:                                   $optiondesc{$option}.'</label></span></td></tr>';
 6229:                 }
 6230:                 $datatable .= '</table>';
 6231:             } elsif ($item eq 'intauth_check') {
 6232:                 my @options = (0,1,2);
 6233:                 my %optiondesc = &Apache::lonlocal::texthash (
 6234:                                    0 => 'No',
 6235:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 6236:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 6237:                                  );
 6238:                 $datatable .= '<table width="100%">';
 6239:                 foreach my $option (@options) {
 6240:                     my $checked = ' ';
 6241:                     my $onclick;
 6242:                     if ($defaults{$item} eq $option) {
 6243:                         $checked = ' checked="checked"';
 6244:                     }
 6245:                     if ($option == 2) {
 6246:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 6247:                     }
 6248:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 6249:                                   '<label><input type="radio" name="'.$item.
 6250:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 6251:                                   $optiondesc{$option}.'</label></span></td></tr>';
 6252:                 }
 6253:                 $datatable .= '</table>';
 6254:             } else {
 6255:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 6256:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 6257:             }
 6258:             $datatable .= '</td></tr>';
 6259:             $itemcount ++;
 6260:         }
 6261:     } elsif ($position eq 'lower') {
 6262:         my ($min,$max,%chars,$expire,$numsaved);
 6263:         $min = $Apache::lonnet::passwdmin;
 6264:         if (ref($settings) eq 'HASH') {
 6265:             if ($settings->{min}) {
 6266:                 $min = $settings->{min};
 6267:             }
 6268:             if ($settings->{max}) {
 6269:                 $max = $settings->{max};
 6270:             }
 6271:             if (ref($settings->{chars}) eq 'ARRAY') {
 6272:                 map { $chars{$_} = 1; } (@{$settings->{chars}});
 6273:             }
 6274:             if ($settings->{expire}) {
 6275:                 $expire = $settings->{expire};
 6276:             }
 6277:             if ($settings->{numsaved}) {
 6278:                 $numsaved = $settings->{numsaved};
 6279:             }
 6280:         }
 6281:         my %rulenames = &Apache::lonlocal::texthash(
 6282:                                                      uc => 'At least one upper case letter',
 6283:                                                      lc => 'At least one lower case letter',
 6284:                                                      num => 'At least one number',
 6285:                                                      spec => 'At least one non-alphanumeric',
 6286:                                                    );
 6287:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6288:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 6289:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6290:                       '<input type="text" name="passwords_min" value="'.$min.'" size="3" '.
 6291:                       'onblur="javascript:warnIntPass(this);" />'.
 6292:                       '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
 6293:                       '</span></td></tr>';
 6294:         $itemcount ++;
 6295:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6296:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 6297:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6298:                       '<input type="text" name="passwords_max" value="'.$max.'" size="3" '.
 6299:                       'onblur="javascript:warnIntPass(this);" />'.
 6300:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 6301:                       '</span></td></tr>';
 6302:         $itemcount ++;
 6303:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6304:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 6305:                       '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 6306:                       '</span></td>';
 6307:         my $numinrow = 2;
 6308:         my @possrules = ('uc','lc','num','spec');
 6309:         $datatable .= '<td class="LC_left_item"><table>';
 6310:         for (my $i=0; $i<@possrules; $i++) {
 6311:             my ($rem,$checked);
 6312:             if ($chars{$possrules[$i]}) {
 6313:                 $checked = ' checked="checked"';
 6314:             }
 6315:             $rem = $i%($numinrow);
 6316:             if ($rem == 0) {
 6317:                 if ($i > 0) {
 6318:                     $datatable .= '</tr>';
 6319:                 }
 6320:                 $datatable .= '<tr>';
 6321:             }
 6322:             $datatable .= '<td><span class="LC_nobreak"><label>'.
 6323:                           '<input type="checkbox" name="passwords_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 6324:                           $rulenames{$possrules[$i]}.'</label></span></td>';
 6325:         }
 6326:         my $rem = @possrules%($numinrow);
 6327:         my $colsleft = $numinrow - $rem;
 6328:         if ($colsleft > 1 ) {
 6329:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6330:                           '&nbsp;</td>';
 6331:         } elsif ($colsleft == 1) {
 6332:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 6333:         }
 6334:         $datatable .='</table></td></tr>';
 6335:         $itemcount ++;
 6336:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6337:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'expire'}.'</td>'.
 6338:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6339:                       '<input type="text" name="passwords_expire" value="'.$expire.'" size="4" '.
 6340:                       'onblur="javascript:warnIntPass(this);" />'.
 6341:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no expiration)').'</span>'.
 6342:                       '</span></td></tr>';
 6343:         $itemcount ++;
 6344:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6345:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 6346:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6347:                       '<input type="text" name="passwords_numsaved" value="'.$numsaved.'" size="3" '.
 6348:                       'onblur="javascript:warnIntPass(this);" />'. 
 6349:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 6350:                       '</span></td></tr>';
 6351:     } else {
 6352:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6353:         my %ownerchg = (
 6354:                           by  => {},
 6355:                           for => {},
 6356:                        );
 6357:         my %ownertitles = &Apache::lonlocal::texthash (
 6358:                             by  => 'Course owner status(es) allowed',
 6359:                             for => 'Student status(es) allowed',
 6360:                           );
 6361:         if (ref($settings) eq 'HASH') {
 6362:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 6363:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 6364:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 6365:                 }
 6366:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 6367:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 6368:                 }
 6369:             }
 6370:         }
 6371:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6372:         $datatable .= '<tr '.$css_class.'>'.
 6373:                       '<td>'.
 6374:                       &mt('Requirements').'<ul>'.
 6375:                       '<li>'.&mt("Course 'type' is not a Community or Placement Test").'</li>'.
 6376:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 6377:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 6378:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 6379:                       '</ul>'.
 6380:                       '</td>'.
 6381:                       '<td class="LC_left_item">';
 6382:         foreach my $item ('by','for') {
 6383:             $datatable .= '<fieldset style="display: inline-block;">'.
 6384:                           '<legend>'.$ownertitles{$item}.'</legend>';
 6385:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6386:                 foreach my $type (@{$types}) {
 6387:                     my $checked;
 6388:                     if ($ownerchg{$item}{$type}) {
 6389:                         $checked = ' checked="checked"';
 6390:                     }
 6391:                     $datatable .= '<span class="LC_nobreak"><label>'.
 6392:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 6393:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 6394:                                   '</span>&nbsp;&nbsp; ';
 6395:                 }
 6396:             }
 6397:             my $checked;
 6398:             if ($ownerchg{$item}{'default'}) {
 6399:                 $checked = ' checked="checked"';
 6400:             }
 6401:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 6402:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 6403:                           $othertitle.'</label></span></fieldset>';
 6404:         }
 6405:         $datatable .= '</td></tr>';
 6406:     }
 6407:     return $datatable;
 6408: }
 6409: 
 6410: sub print_usersessions {
 6411:     my ($position,$dom,$settings,$rowtotal) = @_;
 6412:     my ($css_class,$datatable,$itemcount,%checked,%choices);
 6413:     my (%by_ip,%by_location,@intdoms,@instdoms);
 6414:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 6415: 
 6416:     my @alldoms = &Apache::lonnet::all_domains();
 6417:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 6418:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 6419:     my %altids = &id_for_thisdom(%servers);
 6420:     if ($position eq 'top') {
 6421:         if (keys(%serverhomes) > 1) {
 6422:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 6423:             my ($curroffloadnow,$curroffloadoth);
 6424:             if (ref($settings) eq 'HASH') {
 6425:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 6426:                     $curroffloadnow = $settings->{'offloadnow'};
 6427:                 }
 6428:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 6429:                     $curroffloadoth = $settings->{'offloadoth'};
 6430:                 }
 6431:             }
 6432:             my $other_insts = scalar(keys(%by_location));
 6433:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 6434:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 6435:         } else {
 6436:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 6437:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.').
 6438:                           '</td></tr>';
 6439:         }
 6440:     } else {
 6441:         my %titles = &usersession_titles();
 6442:         my ($prefix,@types);
 6443:         if ($position eq 'bottom') {
 6444:             $prefix = 'remote';
 6445:             @types = ('version','excludedomain','includedomain');
 6446:         } else {
 6447:             $prefix = 'hosted';
 6448:             @types = ('excludedomain','includedomain');
 6449:         }
 6450:         ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 6451:     }
 6452:     $$rowtotal += $itemcount;
 6453:     return $datatable;
 6454: }
 6455: 
 6456: sub rules_by_location {
 6457:     my ($settings,$prefix,$by_location,$by_ip,$types,$titles) = @_; 
 6458:     my ($datatable,$itemcount,$css_class);
 6459:     if (keys(%{$by_location}) == 0) {
 6460:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6461:         $datatable = '<tr'.$css_class.'><td colspan="2">'.
 6462:                      &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.').
 6463:                      '</td></tr>';
 6464:         $itemcount = 1;
 6465:     } else {
 6466:         $itemcount = 0;
 6467:         my $numinrow = 5;
 6468:         my (%current,%checkedon,%checkedoff);
 6469:         my @locations = sort(keys(%{$by_location}));
 6470:         foreach my $type (@{$types}) {
 6471:             $checkedon{$type} = '';
 6472:             $checkedoff{$type} = ' checked="checked"';
 6473:         }
 6474:         if (ref($settings) eq 'HASH') {
 6475:             if (ref($settings->{$prefix}) eq 'HASH') {
 6476:                 foreach my $key (keys(%{$settings->{$prefix}})) {
 6477:                     $current{$key} = $settings->{$prefix}{$key};
 6478:                     if ($key eq 'version') {
 6479:                         if ($current{$key} ne '') {
 6480:                             $checkedon{$key} = ' checked="checked"';
 6481:                             $checkedoff{$key} = '';
 6482:                         }
 6483:                     } elsif (ref($current{$key}) eq 'ARRAY') {
 6484:                         $checkedon{$key} = ' checked="checked"';
 6485:                         $checkedoff{$key} = '';
 6486:                     }
 6487:                 }
 6488:             }
 6489:         }
 6490:         foreach my $type (@{$types}) {
 6491:             next if ($type ne 'version' && !@locations);
 6492:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6493:             $datatable .= '<tr'.$css_class.'>
 6494:                            <td><span class="LC_nobreak">'.$titles->{$type}.'</span><br />
 6495:                            <span class="LC_nobreak">&nbsp;
 6496:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 6497:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 6498:             if ($type eq 'version') {
 6499:                 my @lcversions = &Apache::lonnet::all_loncaparevs();
 6500:                 my $selector = '<select name="'.$prefix.'_version">';
 6501:                 foreach my $version (@lcversions) {
 6502:                     my $selected = '';
 6503:                     if ($current{'version'} eq $version) {
 6504:                         $selected = ' selected="selected"';
 6505:                     }
 6506:                     $selector .= ' <option value="'.$version.'"'.
 6507:                                  $selected.'>'.$version.'</option>';
 6508:                 }
 6509:                 $selector .= '</select> ';
 6510:                 $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 6511:             } else {
 6512:                 $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 6513:                              'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 6514:                              ' />'.('&nbsp;'x2).
 6515:                              '<input type="button" value="'.&mt('uncheck all').'" '.
 6516:                              'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 6517:                              "\n".
 6518:                              '</div><div><table>';
 6519:                 my $rem;
 6520:                 for (my $i=0; $i<@locations; $i++) {
 6521:                     my ($showloc,$value,$checkedtype);
 6522:                     if (ref($by_location->{$locations[$i]}) eq 'ARRAY') {
 6523:                         my $ip = $by_location->{$locations[$i]}->[0];
 6524:                         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 6525:                             $value = join(':',@{$by_ip->{$ip}});
 6526:                             $showloc = join(', ',@{$by_ip->{$ip}});
 6527:                             if (ref($current{$type}) eq 'ARRAY') {
 6528:                                 foreach my $loc (@{$by_ip->{$ip}}) {
 6529:                                     if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 6530:                                         $checkedtype = ' checked="checked"';
 6531:                                         last;
 6532:                                     }
 6533:                                 }
 6534:                             }
 6535:                         }
 6536:                     }
 6537:                     $rem = $i%($numinrow);
 6538:                     if ($rem == 0) {
 6539:                         if ($i > 0) {
 6540:                             $datatable .= '</tr>';
 6541:                         }
 6542:                         $datatable .= '<tr>';
 6543:                     }
 6544:                     $datatable .= '<td class="LC_left_item">'.
 6545:                                   '<span class="LC_nobreak"><label>'.
 6546:                                   '<input type="checkbox" name="'.$prefix.'_'.$type.
 6547:                                   '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 6548:                                   '</label></span></td>';
 6549:                 }
 6550:                 $rem = @locations%($numinrow);
 6551:                 my $colsleft = $numinrow - $rem;
 6552:                 if ($colsleft > 1 ) {
 6553:                     $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 6554:                                   '&nbsp;</td>';
 6555:                 } elsif ($colsleft == 1) {
 6556:                     $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 6557:                 }
 6558:                 $datatable .= '</tr></table>';
 6559:             }
 6560:             $datatable .= '</td></tr>';
 6561:             $itemcount ++;
 6562:         }
 6563:     }
 6564:     return ($datatable,$itemcount);
 6565: }
 6566: 
 6567: sub print_ssl {
 6568:     my ($position,$dom,$settings,$rowtotal) = @_;
 6569:     my ($css_class,$datatable);
 6570:     my $itemcount = 1;
 6571:     if ($position eq 'top') {
 6572:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 6573:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 6574:         my $same_institution;
 6575:         if ($intdom ne '') {
 6576:             my $internet_names = &Apache::lonnet::get_internet_names($Apache::lonnet::perlvar{'lonHostID'});
 6577:             if (ref($internet_names) eq 'ARRAY') {
 6578:                 if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 6579:                     $same_institution = 1;
 6580:                 }
 6581:             }
 6582:         }
 6583:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6584:         $datatable = '<tr'.$css_class.'><td colspan="2">';
 6585:         if ($same_institution) {
 6586:             my %domservers = &Apache::lonnet::get_servers($dom);
 6587:             $datatable .= &LONCAPA::SSL::print_certstatus(\%domservers,'web','domprefs');
 6588:         } else {
 6589:             $datatable .= &mt("You need to be logged into one of your own domain's servers to display information about the status of LON-CAPA SSL certificates.");
 6590:         }
 6591:         $datatable .= '</td></tr>';
 6592:         $itemcount ++;
 6593:     } else {
 6594:         my %titles = &ssl_titles();
 6595:         my (%by_ip,%by_location,@intdoms,@instdoms);
 6596:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 6597:         my @alldoms = &Apache::lonnet::all_domains();
 6598:         my %serverhomes = %Apache::lonnet::serverhomeIDs;
 6599:         my @domservers = &Apache::lonnet::get_servers($dom);
 6600:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 6601:         my %altids = &id_for_thisdom(%servers);
 6602:         if (($position eq 'connto') || ($position eq 'connfrom')) {
 6603:             my $legacy;
 6604:             unless (ref($settings) eq 'HASH') {
 6605:                 my $name;
 6606:                 if ($position eq 'connto') {
 6607:                     $name = 'loncAllowInsecure';
 6608:                 } else {
 6609:                     $name = 'londAllowInsecure';
 6610:                 }
 6611:                 my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
 6612:                 my @ids=&Apache::lonnet::current_machine_ids();
 6613:                 if (($primarylibserv ne '') && (!grep(/^\Q$primarylibserv\E$/,@ids))) {
 6614:                     my %what = (
 6615:                                    $name => 1,
 6616:                                );
 6617:                     my ($result,$returnhash) =
 6618:                         &Apache::lonnet::get_remote_globals($primarylibserv,\%what);
 6619:                     if ($result eq 'ok') {
 6620:                         if (ref($returnhash) eq 'HASH') {
 6621:                             $legacy = $returnhash->{$name};
 6622:                         }
 6623:                     }
 6624:                 } else {
 6625:                     $legacy = $Apache::lonnet::perlvar{$name};
 6626:                 }
 6627:             }
 6628:             foreach my $type ('dom','intdom','other') {
 6629:                 my %checked;
 6630:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6631:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$type}.'</td>'.
 6632:                               '<td class="LC_right_item">';
 6633:                 my $skip; 
 6634:                 if ($type eq 'dom') {
 6635:                     unless (keys(%servers) > 1) {
 6636:                         $datatable .= &mt('Nothing to set here, as there are no other servers/VMs');    
 6637:                         $skip = 1;
 6638:                     }
 6639:                 }
 6640:                 if ($type eq 'intdom') {
 6641:                     unless (@instdoms > 1) {
 6642:                         $datatable .= &mt('Nothing to set here, as there are no other domains for this institution');
 6643:                         $skip = 1;
 6644:                     } 
 6645:                 } elsif ($type eq 'other') {
 6646:                     if (keys(%by_location) == 0) {
 6647:                         $datatable .= &mt('Nothing to set here, as there are no other institutions');
 6648:                         $skip = 1;
 6649:                     }
 6650:                 }
 6651:                 unless ($skip) {
 6652:                     $checked{'yes'} = ' checked="checked"'; 
 6653:                     if (ref($settings) eq 'HASH') {
 6654:                         if (ref($settings->{$position}) eq 'HASH') {
 6655:                             if ($settings->{$position}->{$type} =~ /^(no|req)$/) {
 6656:                                 $checked{$1} = $checked{'yes'};
 6657:                                 delete($checked{'yes'}); 
 6658:                             }
 6659:                         }
 6660:                     } else {
 6661:                         if ($legacy == 0) {
 6662:                             $checked{'req'} = $checked{'yes'};
 6663:                             delete($checked{'yes'});    
 6664:                         }
 6665:                     }
 6666:                     foreach my $option ('no','yes','req') {
 6667:                         $datatable .= '<span class="LC_nobreak"><label>'.
 6668:                                       '<input type="radio" name="'.$position.'_'.$type.'" '.
 6669:                                       'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 6670:                                       '</label></span>'.('&nbsp;'x2);
 6671:                     }
 6672:                 }
 6673:                 $datatable .= '</td></tr>';
 6674:                 $itemcount ++; 
 6675:             }
 6676:         } else {
 6677:             my $prefix = 'replication';
 6678:             my @types = ('certreq','nocertreq');
 6679:             if (keys(%by_location) == 0) {
 6680:                 $datatable .= '<tr'.$css_class.'><td>'.
 6681:                               &mt('Nothing to set here, as there are no other institutions').
 6682:                               '</td></tr>';
 6683:                 $itemcount ++;
 6684:             } else {
 6685:                 ($datatable,$itemcount) = 
 6686:                     &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 6687:             }
 6688:         }
 6689:     }
 6690:     $$rowtotal += $itemcount;
 6691:     return $datatable;
 6692: }
 6693: 
 6694: sub ssl_titles {
 6695:     return &Apache::lonlocal::texthash (
 6696:                dom           => 'LON-CAPA servers/VMs from same domain',
 6697:                intdom        => 'LON-CAPA servers/VMs from same "internet" domain',
 6698:                other         => 'External LON-CAPA servers/VMs',
 6699:                connto        => 'Connections to other servers',
 6700:                connfrom      => 'Connections from other servers',
 6701:                replication   => 'Replicating content to other institutions',
 6702:                certreq       => 'Client certificate required, but specific domains exempt',
 6703:                nocertreq     => 'No client certificate required, except for specific domains',
 6704:                no            => 'SSL not used',
 6705:                yes           => 'SSL Optional (used if available)',
 6706:                req           => 'SSL Required',
 6707:     );
 6708: }
 6709: 
 6710: sub print_trust {
 6711:     my ($prefix,$dom,$settings,$rowtotal) = @_;
 6712:     my ($css_class,$datatable,%checked,%choices);
 6713:     my (%by_ip,%by_location,@intdoms,@instdoms);
 6714:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 6715:     my $itemcount = 1;
 6716:     my %titles = &trust_titles();
 6717:     my @types = ('exc','inc');
 6718:     if ($prefix eq 'top') {
 6719:         $prefix = 'content';
 6720:     } elsif ($prefix eq 'bottom') {
 6721:         $prefix = 'msg';
 6722:     }
 6723:     ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 6724:     $$rowtotal += $itemcount;
 6725:     return $datatable;
 6726: }
 6727: 
 6728: sub trust_titles {
 6729:     return &Apache::lonlocal::texthash(
 6730:                content  => "Access to this domain's content by others",
 6731:                shared   => "Access to other domain's content by this domain",
 6732:                enroll   => "Enrollment in this domain's courses by others", 
 6733:                othcoau  => "Co-author roles in this domain for others",
 6734:                coaurem  => "Co-author roles for this domain's users elsewhere", 
 6735:                domroles => "Domain roles in this domain assignable to others",
 6736:                catalog  => "Course Catalog for this domain displayed elsewhere",
 6737:                reqcrs   => "Requests for creation of courses in this domain by others",
 6738:                msg      => "Users in other domains can send messages to this domain",
 6739:                exc      => "Allow all, but exclude specific domains",
 6740:                inc      => "Deny all, but include specific domains",
 6741:            );
 6742: } 
 6743: 
 6744: sub build_location_hashes {
 6745:     my ($intdoms,$by_ip,$by_location,$instdoms) = @_;
 6746:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 6747:                   (ref($by_location) eq 'HASH') && (ref($instdoms) eq 'ARRAY'));
 6748:     my %iphost = &Apache::lonnet::get_iphost();
 6749:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 6750:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 6751:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 6752:         foreach my $id (@{$iphost{$primary_ip}}) {
 6753:             my $intdom = &Apache::lonnet::internet_dom($id);
 6754:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 6755:                 push(@{$intdoms},$intdom);
 6756:             }
 6757:         }
 6758:     }
 6759:     foreach my $ip (keys(%iphost)) {
 6760:         if (ref($iphost{$ip}) eq 'ARRAY') {
 6761:             foreach my $id (@{$iphost{$ip}}) {
 6762:                 my $location = &Apache::lonnet::internet_dom($id);
 6763:                 if ($location) {
 6764:                     if (grep(/^\Q$location\E$/,@{$intdoms})) {
 6765:                         my $dom = &Apache::lonnet::host_domain($id);
 6766:                         unless (grep(/^\Q$dom\E/,@{$instdoms})) {
 6767:                             push(@{$instdoms},$dom);
 6768:                         }
 6769:                         next;
 6770:                     }
 6771:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 6772:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 6773:                             push(@{$by_ip->{$ip}},$location);
 6774:                         }
 6775:                     } else {
 6776:                         $by_ip->{$ip} = [$location];
 6777:                     }
 6778:                 }
 6779:             }
 6780:         }
 6781:     }
 6782:     foreach my $ip (sort(keys(%{$by_ip}))) {
 6783:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 6784:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 6785:             my $first = $by_ip->{$ip}->[0];
 6786:             if (ref($by_location->{$first}) eq 'ARRAY') {
 6787:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 6788:                     push(@{$by_location->{$first}},$ip);
 6789:                 }
 6790:             } else {
 6791:                 $by_location->{$first} = [$ip];
 6792:             }
 6793:         }
 6794:     }
 6795:     return;
 6796: }
 6797: 
 6798: sub current_offloads_to {
 6799:     my ($dom,$settings,$servers) = @_;
 6800:     my (%spareid,%otherdomconfigs);
 6801:     if (ref($servers) eq 'HASH') {
 6802:         foreach my $lonhost (sort(keys(%{$servers}))) {
 6803:             my $gotspares;
 6804:             if (ref($settings) eq 'HASH') {
 6805:                 if (ref($settings->{'spares'}) eq 'HASH') {
 6806:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 6807:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 6808:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 6809:                         $gotspares = 1;
 6810:                     }
 6811:                 }
 6812:             }
 6813:             unless ($gotspares) {
 6814:                 my $gotspares;
 6815:                 my $serverhomeID =
 6816:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 6817:                 my $serverhomedom =
 6818:                     &Apache::lonnet::host_domain($serverhomeID);
 6819:                 if ($serverhomedom ne $dom) {
 6820:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 6821:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 6822:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 6823:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 6824:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 6825:                                 $gotspares = 1;
 6826:                             }
 6827:                         }
 6828:                     } else {
 6829:                         $otherdomconfigs{$serverhomedom} =
 6830:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 6831:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 6832:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 6833:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 6834:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 6835:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 6836:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 6837:                                         $gotspares = 1;
 6838:                                     }
 6839:                                 }
 6840:                             }
 6841:                         }
 6842:                     }
 6843:                 }
 6844:             }
 6845:             unless ($gotspares) {
 6846:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 6847:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 6848:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 6849:                } else {
 6850:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 6851:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 6852:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 6853:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 6854:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 6855:                     } else {
 6856:                         my %what = (
 6857:                              spareid => 1,
 6858:                         );
 6859:                         my ($result,$returnhash) = 
 6860:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 6861:                         if ($result eq 'ok') { 
 6862:                             if (ref($returnhash) eq 'HASH') {
 6863:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 6864:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 6865:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 6866:                                 }
 6867:                             }
 6868:                         }
 6869:                     }
 6870:                 }
 6871:             }
 6872:         }
 6873:     }
 6874:     return %spareid;
 6875: }
 6876: 
 6877: sub spares_row {
 6878:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 6879:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 6880:     my $css_class;
 6881:     my $numinrow = 4;
 6882:     my $itemcount = 1;
 6883:     my $datatable;
 6884:     my %typetitles = &sparestype_titles();
 6885:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 6886:         foreach my $server (sort(keys(%{$servers}))) {
 6887:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 6888:             my ($othercontrol,$serverdom);
 6889:             if ($serverhome ne $server) {
 6890:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 6891:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 6892:             } else {
 6893:                 $serverdom = &Apache::lonnet::host_domain($server);
 6894:                 if ($serverdom ne $dom) {
 6895:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 6896:                 }
 6897:             }
 6898:             next unless (ref($spareid->{$server}) eq 'HASH');
 6899:             my ($checkednow,$checkedoth);
 6900:             if (ref($curroffloadnow) eq 'HASH') {
 6901:                 if ($curroffloadnow->{$server}) {
 6902:                     $checkednow = ' checked="checked"';
 6903:                 }
 6904:             }
 6905:             if (ref($curroffloadoth) eq 'HASH') {
 6906:                 if ($curroffloadoth->{$server}) {
 6907:                     $checkedoth = ' checked="checked"';
 6908:                 }
 6909:             }
 6910:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6911:             $datatable .= '<tr'.$css_class.'>
 6912:                            <td rowspan="2">
 6913:                             <span class="LC_nobreak">'.
 6914:                           &mt('[_1] when busy, offloads to:'
 6915:                               ,'<b>'.$server.'</b>').'</span><br />'.
 6916:                           '<span class="LC_nobreak">'."\n".
 6917:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 6918:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 6919:                           "\n";
 6920:             if ($other_insts) {
 6921:                 $datatable .= '<br />'.
 6922:                               '<span class="LC_nobreak">'."\n".
 6923:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 6924:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 6925:                           "\n";
 6926:             }
 6927:             my (%current,%canselect);
 6928:             my @choices = 
 6929:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 6930:             foreach my $type ('primary','default') {
 6931:                 if (ref($spareid->{$server}) eq 'HASH') {
 6932:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 6933:                         my @spares = @{$spareid->{$server}{$type}};
 6934:                         if (@spares > 0) {
 6935:                             if ($othercontrol) {
 6936:                                 $current{$type} = join(', ',@spares);
 6937:                             } else {
 6938:                                 $current{$type} .= '<table>';
 6939:                                 my $numspares = scalar(@spares);
 6940:                                 for (my $i=0;  $i<@spares; $i++) {
 6941:                                     my $rem = $i%($numinrow);
 6942:                                     if ($rem == 0) {
 6943:                                         if ($i > 0) {
 6944:                                             $current{$type} .= '</tr>';
 6945:                                         }
 6946:                                         $current{$type} .= '<tr>';
 6947:                                     }
 6948:                                     $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;'.
 6949:                                                        $spareid->{$server}{$type}[$i].
 6950:                                                        '</label></td>'."\n";
 6951:                                 }
 6952:                                 my $rem = @spares%($numinrow);
 6953:                                 my $colsleft = $numinrow - $rem;
 6954:                                 if ($colsleft > 1 ) {
 6955:                                     $current{$type} .= '<td colspan="'.$colsleft.
 6956:                                                        '" class="LC_left_item">'.
 6957:                                                        '&nbsp;</td>';
 6958:                                 } elsif ($colsleft == 1) {
 6959:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 6960:                                 }
 6961:                                 $current{$type} .= '</tr></table>';
 6962:                             }
 6963:                         }
 6964:                     }
 6965:                     if ($current{$type} eq '') {
 6966:                         $current{$type} = &mt('None specified');
 6967:                     }
 6968:                     if ($othercontrol) {
 6969:                         if ($type eq 'primary') {
 6970:                             $canselect{$type} = $othercontrol;
 6971:                         }
 6972:                     } else {
 6973:                         $canselect{$type} = 
 6974:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 6975:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 6976:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 6977:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 6978:                         if (@choices > 0) {
 6979:                             foreach my $lonhost (@choices) {
 6980:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 6981:                             }
 6982:                         }
 6983:                         $canselect{$type} .= '</select>'."\n";
 6984:                     }
 6985:                 } else {
 6986:                     $current{$type} = &mt('Could not be determined');
 6987:                     if ($type eq 'primary') {
 6988:                         $canselect{$type} =  $othercontrol;
 6989:                     }
 6990:                 }
 6991:                 if ($type eq 'default') {
 6992:                     $datatable .= '<tr'.$css_class.'>';
 6993:                 }
 6994:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 6995:                               '<td>'.$current{$type}.'</td>'."\n".
 6996:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 6997:             }
 6998:             $itemcount ++;
 6999:         }
 7000:     }
 7001:     $$rowtotal += $itemcount;
 7002:     return $datatable;
 7003: }
 7004: 
 7005: sub possible_newspares {
 7006:     my ($server,$currspares,$serverhomes,$altids) = @_;
 7007:     my $serverhostname = &Apache::lonnet::hostname($server);
 7008:     my %excluded;
 7009:     if ($serverhostname ne '') {
 7010:         %excluded = (
 7011:                        $serverhostname => 1,
 7012:                     );
 7013:     }
 7014:     if (ref($currspares) eq 'HASH') {
 7015:         foreach my $type (keys(%{$currspares})) {
 7016:             if (ref($currspares->{$type}) eq 'ARRAY') {
 7017:                 if (@{$currspares->{$type}} > 0) {
 7018:                     foreach my $curr (@{$currspares->{$type}}) {
 7019:                         my $hostname = &Apache::lonnet::hostname($curr);
 7020:                         $excluded{$hostname} = 1;
 7021:                     }
 7022:                 }
 7023:             }
 7024:         }
 7025:     }
 7026:     my @choices;
 7027:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 7028:         if (keys(%{$serverhomes}) > 1) {
 7029:             foreach my $name (sort(keys(%{$serverhomes}))) {
 7030:                 unless ($excluded{$name}) {
 7031:                     if (exists($altids->{$serverhomes->{$name}})) {
 7032:                         push(@choices,$altids->{$serverhomes->{$name}});
 7033:                     } else {
 7034:                         push(@choices,$serverhomes->{$name});
 7035:                     }
 7036:                 }
 7037:             }
 7038:         }
 7039:     }
 7040:     return sort(@choices);
 7041: }
 7042: 
 7043: sub print_loadbalancing {
 7044:     my ($dom,$settings,$rowtotal) = @_;
 7045:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7046:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7047:     my $numinrow = 1;
 7048:     my $datatable;
 7049:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7050:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 7051:     if (ref($settings) eq 'HASH') {
 7052:         %existing = %{$settings};
 7053:     }
 7054:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 7055:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 7056:                                   \%currtargets,\%currrules,\%currcookies);
 7057:     } else {
 7058:         return;
 7059:     }
 7060:     my ($othertitle,$usertypes,$types) =
 7061:         &Apache::loncommon::sorted_inst_types($dom);
 7062:     my $rownum = 8;
 7063:     if (ref($types) eq 'ARRAY') {
 7064:         $rownum += scalar(@{$types});
 7065:     }
 7066:     my @css_class = ('LC_odd_row','LC_even_row');
 7067:     my $balnum = 0;
 7068:     my $islast;
 7069:     my (@toshow,$disabledtext);
 7070:     if (keys(%currbalancer) > 0) {
 7071:         @toshow = sort(keys(%currbalancer));
 7072:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 7073:             push(@toshow,'');
 7074:         }
 7075:     } else {
 7076:         @toshow = ('');
 7077:         $disabledtext = &mt('No existing load balancer');
 7078:     }
 7079:     foreach my $lonhost (@toshow) {
 7080:         if ($balnum == scalar(@toshow)-1) {
 7081:             $islast = 1;
 7082:         } else {
 7083:             $islast = 0;
 7084:         }
 7085:         my $cssidx = $balnum%2;
 7086:         my $targets_div_style = 'display: none';
 7087:         my $disabled_div_style = 'display: block';
 7088:         my $homedom_div_style = 'display: none';
 7089:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 7090:                       '<td rowspan="'.$rownum.'" style="vertical-align: top">'.
 7091:                       '<p>';
 7092:         if ($lonhost eq '') {
 7093:             $datatable .= '<span class="LC_nobreak">';
 7094:             if (keys(%currbalancer) > 0) {
 7095:                 $datatable .= &mt('Add balancer:');
 7096:             } else {
 7097:                 $datatable .= &mt('Enable balancer:');
 7098:             }
 7099:             $datatable .= '&nbsp;'.
 7100:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 7101:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 7102:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 7103:                           '<option value="" selected="selected">'.&mt('None').
 7104:                           '</option>'."\n";
 7105:             foreach my $server (sort(keys(%servers))) {
 7106:                 next if ($currbalancer{$server});
 7107:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 7108:             }
 7109:             $datatable .=
 7110:                 '</select>'."\n".
 7111:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 7112:         } else {
 7113:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 7114:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 7115:                            &mt('Stop balancing').'</label>'.
 7116:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 7117:             $targets_div_style = 'display: block';
 7118:             $disabled_div_style = 'display: none';
 7119:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 7120:                 $homedom_div_style = 'display: block';
 7121:             }
 7122:         }
 7123:         $datatable .= '</p></td><td rowspan="'.$rownum.'" style="vertical-align: top">'.
 7124:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 7125:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 7126:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 7127:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 7128:         my @sparestypes = ('primary','default');
 7129:         my %typetitles = &sparestype_titles();
 7130:         my %hostherechecked = (
 7131:                                   no => ' checked="checked"',
 7132:                               );
 7133:         my %balcookiechecked = (
 7134:                                   no => ' checked="checked"', 
 7135:                                );
 7136:         foreach my $sparetype (@sparestypes) {
 7137:             my $targettable;
 7138:             for (my $i=0; $i<$numspares; $i++) {
 7139:                 my $checked;
 7140:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 7141:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 7142:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 7143:                             $checked = ' checked="checked"';
 7144:                         }
 7145:                     }
 7146:                 }
 7147:                 my ($chkboxval,$disabled);
 7148:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 7149:                     $chkboxval = $spares[$i];
 7150:                 }
 7151:                 if (exists($currbalancer{$spares[$i]})) {
 7152:                     $disabled = ' disabled="disabled"';
 7153:                 }
 7154:                 $targettable .=
 7155:                     '<td><span class="LC_nobreak"><label>'.
 7156:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 7157:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 7158:                     '</span></label></span></td>';
 7159:                 my $rem = $i%($numinrow);
 7160:                 if ($rem == 0) {
 7161:                     if (($i > 0) && ($i < $numspares-1)) {
 7162:                         $targettable .= '</tr>';
 7163:                     }
 7164:                     if ($i < $numspares-1) {
 7165:                         $targettable .= '<tr>';
 7166:                     }
 7167:                 }
 7168:             }
 7169:             if ($targettable ne '') {
 7170:                 my $rem = $numspares%($numinrow);
 7171:                 my $colsleft = $numinrow - $rem;
 7172:                 if ($colsleft > 1 ) {
 7173:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7174:                                     '&nbsp;</td>';
 7175:                 } elsif ($colsleft == 1) {
 7176:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 7177:                 }
 7178:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 7179:                                '<table><tr>'.$targettable.'</tr></table><br />';
 7180:             }
 7181:             $hostherechecked{$sparetype} = '';
 7182:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 7183:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 7184:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 7185:                         $hostherechecked{$sparetype} = ' checked="checked"';
 7186:                         $hostherechecked{'no'} = '';
 7187:                     }
 7188:                 }
 7189:             }
 7190:         }
 7191:         if ($currcookies{$lonhost}) {
 7192:             %balcookiechecked = (
 7193:                                     yes => ' checked="checked"',
 7194:                                 );
 7195:         }
 7196:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 7197:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 7198:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 7199:         foreach my $sparetype (@sparestypes) {
 7200:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 7201:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 7202:                           '</i></label><br />';
 7203:         }
 7204:         $datatable .= &mt('Use balancer cookie').'<br />'.
 7205:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 7206:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 7207:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 7208:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 7209:                       '</div></td></tr>'.
 7210:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 7211:                                            $othertitle,$usertypes,$types,\%servers,
 7212:                                            \%currbalancer,$lonhost,
 7213:                                            $targets_div_style,$homedom_div_style,
 7214:                                            $css_class[$cssidx],$balnum,$islast);
 7215:         $$rowtotal += $rownum;
 7216:         $balnum ++;
 7217:     }
 7218:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 7219:     return $datatable;
 7220: }
 7221: 
 7222: sub get_loadbalancers_config {
 7223:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 7224:     return unless ((ref($servers) eq 'HASH') &&
 7225:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 7226:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 7227:                    (ref($currcookies) eq 'HASH'));
 7228:     if (keys(%{$existing}) > 0) {
 7229:         my $oldlonhost;
 7230:         foreach my $key (sort(keys(%{$existing}))) {
 7231:             if ($key eq 'lonhost') {
 7232:                 $oldlonhost = $existing->{'lonhost'};
 7233:                 $currbalancer->{$oldlonhost} = 1;
 7234:             } elsif ($key eq 'targets') {
 7235:                 if ($oldlonhost) {
 7236:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 7237:                 }
 7238:             } elsif ($key eq 'rules') {
 7239:                 if ($oldlonhost) {
 7240:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 7241:                 }
 7242:             } elsif (ref($existing->{$key}) eq 'HASH') {
 7243:                 $currbalancer->{$key} = 1;
 7244:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 7245:                 $currrules->{$key} = $existing->{$key}{'rules'};
 7246:                 if ($existing->{$key}{'cookie'}) {
 7247:                     $currcookies->{$key} = 1;
 7248:                 }
 7249:             }
 7250:         }
 7251:     } else {
 7252:         my ($balancerref,$targetsref) =
 7253:                 &Apache::lonnet::get_lonbalancer_config($servers);
 7254:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 7255:             foreach my $server (sort(keys(%{$balancerref}))) {
 7256:                 $currbalancer->{$server} = 1;
 7257:                 $currtargets->{$server} = $targetsref->{$server};
 7258:             }
 7259:         }
 7260:     }
 7261:     return;
 7262: }
 7263: 
 7264: sub loadbalancing_rules {
 7265:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 7266:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 7267:         $css_class,$balnum,$islast) = @_;
 7268:     my $output;
 7269:     my $num = 0;
 7270:     my ($alltypes,$othertypes,$titles) =
 7271:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 7272:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 7273:         foreach my $type (@{$alltypes}) {
 7274:             $num ++;
 7275:             my $current;
 7276:             if (ref($currrules) eq 'HASH') {
 7277:                 $current = $currrules->{$type};
 7278:             }
 7279:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 7280:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 7281:                     $current = '';
 7282:                 }
 7283:             }
 7284:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 7285:                                              $servers,$currbalancer,$lonhost,$dom,
 7286:                                              $targets_div_style,$homedom_div_style,
 7287:                                              $css_class,$balnum,$num,$islast);
 7288:         }
 7289:     }
 7290:     return $output;
 7291: }
 7292: 
 7293: sub loadbalancing_titles {
 7294:     my ($dom,$intdom,$usertypes,$types) = @_;
 7295:     my %othertypes = (
 7296:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 7297:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 7298:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 7299:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 7300:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 7301:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 7302:                      );
 7303:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 7304:     my @available;
 7305:     if (ref($types) eq 'ARRAY') {
 7306:         @available = @{$types};
 7307:     }
 7308:     unless (grep(/^default$/,@available)) {
 7309:         push(@available,'default');
 7310:     }
 7311:     unshift(@alltypes,@available);
 7312:     my %titles;
 7313:     foreach my $type (@alltypes) {
 7314:         if ($type =~ /^_LC_/) {
 7315:             $titles{$type} = $othertypes{$type};
 7316:         } elsif ($type eq 'default') {
 7317:             $titles{$type} = &mt('All users from [_1]',$dom);
 7318:             if (ref($types) eq 'ARRAY') {
 7319:                 if (@{$types} > 0) {
 7320:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 7321:                 }
 7322:             }
 7323:         } elsif (ref($usertypes) eq 'HASH') {
 7324:             $titles{$type} = $usertypes->{$type};
 7325:         }
 7326:     }
 7327:     return (\@alltypes,\%othertypes,\%titles);
 7328: }
 7329: 
 7330: sub loadbalance_rule_row {
 7331:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 7332:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 7333:     my @rulenames;
 7334:     my %ruletitles = &offloadtype_text();
 7335:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 7336:         @rulenames = ('balancer','offloadedto','specific');
 7337:     } else {
 7338:         @rulenames = ('default','homeserver');
 7339:         if ($type eq '_LC_external') {
 7340:             push(@rulenames,'externalbalancer');
 7341:         } else {
 7342:             push(@rulenames,'specific');
 7343:         }
 7344:         push(@rulenames,'none');
 7345:     }
 7346:     my $style = $targets_div_style;
 7347:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 7348:         $style = $homedom_div_style;
 7349:     }
 7350:     my $space;
 7351:     if ($islast && $num == 1) {
 7352:         $space = '<div style="display:inline-block;">&nbsp;</div>';
 7353:     }
 7354:     my $output =
 7355:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td style="vertical-align: top">'.$space.
 7356:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 7357:         '<td valaign="top">'.$space.
 7358:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 7359:     for (my $i=0; $i<@rulenames; $i++) {
 7360:         my $rule = $rulenames[$i];
 7361:         my ($checked,$extra);
 7362:         if ($rulenames[$i] eq 'default') {
 7363:             $rule = '';
 7364:         }
 7365:         if ($rulenames[$i] eq 'specific') {
 7366:             if (ref($servers) eq 'HASH') {
 7367:                 my $default;
 7368:                 if (($current ne '') && (exists($servers->{$current}))) {
 7369:                     $checked = ' checked="checked"';
 7370:                 }
 7371:                 unless ($checked) {
 7372:                     $default = ' selected="selected"';
 7373:                 }
 7374:                 $extra =
 7375:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 7376:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 7377:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 7378:                     '<option value=""'.$default.'></option>'."\n";
 7379:                 foreach my $server (sort(keys(%{$servers}))) {
 7380:                     if (ref($currbalancer) eq 'HASH') {
 7381:                         next if (exists($currbalancer->{$server}));
 7382:                     }
 7383:                     my $selected;
 7384:                     if ($server eq $current) {
 7385:                         $selected = ' selected="selected"';
 7386:                     }
 7387:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 7388:                 }
 7389:                 $extra .= '</select>';
 7390:             }
 7391:         } elsif ($rule eq $current) {
 7392:             $checked = ' checked="checked"';
 7393:         }
 7394:         $output .= '<span class="LC_nobreak"><label>'.
 7395:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 7396:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 7397:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 7398:                    ')"'.$checked.' />&nbsp;';
 7399:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 7400:             $output .= $ruletitles{'particular'};
 7401:         } else {
 7402:             $output .= $ruletitles{$rulenames[$i]};
 7403:         }
 7404:         $output .= '</label>'.$extra.'</span><br />'."\n";
 7405:     }
 7406:     $output .= '</div></td></tr>'."\n";
 7407:     return $output;
 7408: }
 7409: 
 7410: sub offloadtype_text {
 7411:     my %ruletitles = &Apache::lonlocal::texthash (
 7412:            'default'          => 'Offloads to default destinations',
 7413:            'homeserver'       => "Offloads to user's home server",
 7414:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 7415:            'specific'         => 'Offloads to specific server',
 7416:            'none'             => 'No offload',
 7417:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 7418:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 7419:            'particular'       => 'Session hosted (after re-auth) on server:',
 7420:     );
 7421:     return %ruletitles;
 7422: }
 7423: 
 7424: sub sparestype_titles {
 7425:     my %typestitles = &Apache::lonlocal::texthash (
 7426:                           'primary' => 'primary',
 7427:                           'default' => 'default',
 7428:                       );
 7429:     return %typestitles;
 7430: }
 7431: 
 7432: sub contact_titles {
 7433:     my %titles = &Apache::lonlocal::texthash (
 7434:                    'supportemail'    => 'Support E-mail address',
 7435:                    'adminemail'      => 'Default Server Admin E-mail address',
 7436:                    'errormail'       => 'Error reports to be e-mailed to',
 7437:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 7438:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 7439:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 7440:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 7441:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 7442:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 7443:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 7444:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 7445:                    'errorthreshold'  => 'Error/warning threshold for status e-mail',
 7446:                    'errorsysmail'    => 'Error threshold for e-mail to core group',
 7447:                    'errorweights'    => 'Weights used to compute error count',
 7448:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 7449:                  );
 7450:     my %short_titles = &Apache::lonlocal::texthash (
 7451:                            adminemail   => 'Admin E-mail address',
 7452:                            supportemail => 'Support E-mail',
 7453:                        );   
 7454:     return (\%titles,\%short_titles);
 7455: }
 7456: 
 7457: sub helpform_fields {
 7458:     my %titles =  &Apache::lonlocal::texthash (
 7459:                        'username'   => 'Name',
 7460:                        'user'       => 'Username/domain',
 7461:                        'phone'      => 'Phone',
 7462:                        'cc'         => 'Cc e-mail',
 7463:                        'course'     => 'Course Details',
 7464:                        'section'    => 'Sections',
 7465:                        'screenshot' => 'File upload',
 7466:     );
 7467:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 7468:     my %possoptions = (
 7469:                         username     => ['yes','no','req'],
 7470:                         phone        => ['yes','no','req'],
 7471:                         user         => ['yes','no'],
 7472:                         cc           => ['yes','no'],
 7473:                         course       => ['yes','no'],
 7474:                         section      => ['yes','no'],
 7475:                         screenshot   => ['yes','no'],
 7476:                       );
 7477:     my %fieldoptions = &Apache::lonlocal::texthash (
 7478:                          'yes'  => 'Optional',
 7479:                          'req'  => 'Required',
 7480:                          'no'   => "Not shown",
 7481:     );
 7482:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 7483: }
 7484: 
 7485: sub tool_titles {
 7486:     my %titles = &Apache::lonlocal::texthash (
 7487:                      aboutme    => 'Personal web page',
 7488:                      blog       => 'Blog',
 7489:                      webdav     => 'WebDAV',
 7490:                      portfolio  => 'Portfolio',
 7491:                      official   => 'Official courses (with institutional codes)',
 7492:                      unofficial => 'Unofficial courses',
 7493:                      community  => 'Communities',
 7494:                      textbook   => 'Textbook courses',
 7495:                      placement  => 'Placement tests',
 7496:                  );
 7497:     return %titles;
 7498: }
 7499: 
 7500: sub courserequest_titles {
 7501:     my %titles = &Apache::lonlocal::texthash (
 7502:                                    official   => 'Official',
 7503:                                    unofficial => 'Unofficial',
 7504:                                    community  => 'Communities',
 7505:                                    textbook   => 'Textbook',
 7506:                                    placement  => 'Placement tests',
 7507:                                    lti        => 'LTI Provider',
 7508:                                    norequest  => 'Not allowed',
 7509:                                    approval   => 'Approval by DC',
 7510:                                    validate   => 'With validation',
 7511:                                    autolimit  => 'Numerical limit',
 7512:                                    unlimited  => '(blank for unlimited)',
 7513:                  );
 7514:     return %titles;
 7515: }
 7516: 
 7517: sub authorrequest_titles {
 7518:     my %titles = &Apache::lonlocal::texthash (
 7519:                                    norequest  => 'Not allowed',
 7520:                                    approval   => 'Approval by Dom. Coord.',
 7521:                                    automatic  => 'Automatic approval',
 7522:                  );
 7523:     return %titles;
 7524: }
 7525: 
 7526: sub courserequest_conditions {
 7527:     my %conditions = &Apache::lonlocal::texthash (
 7528:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 7529:        validate   => '(Processing of request subject to institutional validation).',
 7530:                  );
 7531:     return %conditions;
 7532: }
 7533: 
 7534: 
 7535: sub print_usercreation {
 7536:     my ($position,$dom,$settings,$rowtotal) = @_;
 7537:     my $numinrow = 4;
 7538:     my $datatable;
 7539:     if ($position eq 'top') {
 7540:         $$rowtotal ++;
 7541:         my $rowcount = 0;
 7542:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 7543:         if (ref($rules) eq 'HASH') {
 7544:             if (keys(%{$rules}) > 0) {
 7545:                 $datatable .= &user_formats_row('username',$settings,$rules,
 7546:                                                 $ruleorder,$numinrow,$rowcount);
 7547:                 $$rowtotal ++;
 7548:                 $rowcount ++;
 7549:             }
 7550:         }
 7551:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 7552:         if (ref($idrules) eq 'HASH') {
 7553:             if (keys(%{$idrules}) > 0) {
 7554:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 7555:                                                 $idruleorder,$numinrow,$rowcount);
 7556:                 $$rowtotal ++;
 7557:                 $rowcount ++;
 7558:             }
 7559:         }
 7560:         if ($rowcount == 0) {
 7561:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 7562:             $$rowtotal ++;
 7563:             $rowcount ++;
 7564:         }
 7565:     } elsif ($position eq 'middle') {
 7566:         my @creators = ('author','course','requestcrs');
 7567:         my ($rules,$ruleorder) =
 7568:             &Apache::lonnet::inst_userrules($dom,'username');
 7569:         my %lt = &usercreation_types();
 7570:         my %checked;
 7571:         if (ref($settings) eq 'HASH') {
 7572:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 7573:                 foreach my $item (@creators) {
 7574:                     $checked{$item} = $settings->{'cancreate'}{$item};
 7575:                 }
 7576:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 7577:                 foreach my $item (@creators) {
 7578:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 7579:                         $checked{$item} = 'none';
 7580:                     }
 7581:                 }
 7582:             }
 7583:         }
 7584:         my $rownum = 0;
 7585:         foreach my $item (@creators) {
 7586:             $rownum ++;
 7587:             if ($checked{$item} eq '') {
 7588:                 $checked{$item} = 'any';
 7589:             }
 7590:             my $css_class;
 7591:             if ($rownum%2) {
 7592:                 $css_class = '';
 7593:             } else {
 7594:                 $css_class = ' class="LC_odd_row" ';
 7595:             }
 7596:             $datatable .= '<tr'.$css_class.'>'.
 7597:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 7598:                          '</span></td><td style="text-align: right">';
 7599:             my @options = ('any');
 7600:             if (ref($rules) eq 'HASH') {
 7601:                 if (keys(%{$rules}) > 0) {
 7602:                     push(@options,('official','unofficial'));
 7603:                 }
 7604:             }
 7605:             push(@options,'none');
 7606:             foreach my $option (@options) {
 7607:                 my $type = 'radio';
 7608:                 my $check = ' ';
 7609:                 if ($checked{$item} eq $option) {
 7610:                     $check = ' checked="checked" ';
 7611:                 } 
 7612:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7613:                               '<input type="'.$type.'" name="can_createuser_'.
 7614:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 7615:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 7616:             }
 7617:             $datatable .= '</td></tr>';
 7618:         }
 7619:     } else {
 7620:         my @contexts = ('author','course','domain');
 7621:         my @authtypes = ('int','krb4','krb5','loc','lti');
 7622:         my %checked;
 7623:         if (ref($settings) eq 'HASH') {
 7624:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 7625:                 foreach my $item (@contexts) {
 7626:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 7627:                         foreach my $auth (@authtypes) {
 7628:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 7629:                                 $checked{$item}{$auth} = ' checked="checked" ';
 7630:                             }
 7631:                         }
 7632:                     }
 7633:                 }
 7634:             }
 7635:         } else {
 7636:             foreach my $item (@contexts) {
 7637:                 foreach my $auth (@authtypes) {
 7638:                     $checked{$item}{$auth} = ' checked="checked" ';
 7639:                 }
 7640:             }
 7641:         }
 7642:         my %title = &context_names();
 7643:         my %authname = &authtype_names();
 7644:         my $rownum = 0;
 7645:         my $css_class; 
 7646:         foreach my $item (@contexts) {
 7647:             if ($rownum%2) {
 7648:                 $css_class = '';
 7649:             } else {
 7650:                 $css_class = ' class="LC_odd_row" ';
 7651:             }
 7652:             $datatable .=   '<tr'.$css_class.'>'.
 7653:                             '<td>'.$title{$item}.
 7654:                             '</td><td class="LC_left_item">'.
 7655:                             '<span class="LC_nobreak">';
 7656:             foreach my $auth (@authtypes) {
 7657:                 $datatable .= '<label>'. 
 7658:                               '<input type="checkbox" name="'.$item.'_auth" '.
 7659:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 7660:                               $authname{$auth}.'</label>&nbsp;';
 7661:             }
 7662:             $datatable .= '</span></td></tr>';
 7663:             $rownum ++;
 7664:         }
 7665:         $$rowtotal += $rownum;
 7666:     }
 7667:     return $datatable;
 7668: }
 7669: 
 7670: sub print_selfcreation {
 7671:     my ($position,$dom,$settings,$rowtotal) = @_;
 7672:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 7673:         $emaildomain,$datatable);
 7674:     if (ref($settings) eq 'HASH') {
 7675:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 7676:             $createsettings = $settings->{'cancreate'};
 7677:             if (ref($createsettings) eq 'HASH') {
 7678:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 7679:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 7680:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 7681:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 7682:                         @selfcreate = ('email','login','sso');
 7683:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 7684:                         @selfcreate = ($createsettings->{'selfcreate'});
 7685:                     }
 7686:                 }
 7687:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 7688:                     $processing = $createsettings->{'selfcreateprocessing'};
 7689:                 }
 7690:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 7691:                     $emailoptions = $createsettings->{'emailoptions'};
 7692:                 }
 7693:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 7694:                     $emailverified = $createsettings->{'emailverified'};
 7695:                 }
 7696:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 7697:                     $emaildomain = $createsettings->{'emaildomain'};
 7698:                 }
 7699:             }
 7700:         }
 7701:     }
 7702:     my %radiohash;
 7703:     my $numinrow = 4;
 7704:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 7705:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7706:     if ($position eq 'top') {
 7707:         my %choices = &Apache::lonlocal::texthash (
 7708:                                                       cancreate_login      => 'Institutional Login',
 7709:                                                       cancreate_sso        => 'Institutional Single Sign On',
 7710:                                                   );
 7711:         my @toggles = sort(keys(%choices));
 7712:         my %defaultchecked = (
 7713:                                'cancreate_login' => 'off',
 7714:                                'cancreate_sso'   => 'off',
 7715:                              );
 7716:         my ($onclick,$itemcount);
 7717:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 7718:                                                      \%choices,$itemcount,$onclick);
 7719:         $$rowtotal += $itemcount;
 7720:         
 7721:         if (ref($usertypes) eq 'HASH') {
 7722:             if (keys(%{$usertypes}) > 0) {
 7723:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 7724:                                              $dom,$numinrow,$othertitle,
 7725:                                              'statustocreate',$rowtotal);
 7726:                 $$rowtotal ++;
 7727:             }
 7728:         }
 7729:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 7730:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 7731:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 7732:         my $rem;
 7733:         my $numperrow = 2;
 7734:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 7735:         $datatable .= '<tr'.$css_class.'>'.
 7736:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 7737:                      '<td class="LC_left_item">'."\n".
 7738:                      '<table>'."\n";
 7739:         for (my $i=0; $i<@fields; $i++) {
 7740:             $rem = $i%($numperrow);
 7741:             if ($rem == 0) {
 7742:                 if ($i > 0) {
 7743:                     $datatable .= '</tr>';
 7744:                 }
 7745:                 $datatable .= '<tr>';
 7746:             }
 7747:             my $currval;
 7748:             if (ref($createsettings) eq 'HASH') {
 7749:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 7750:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 7751:                 }
 7752:             }
 7753:             $datatable .= '<td class="LC_left_item">'.
 7754:                           '<span class="LC_nobreak">'.
 7755:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 7756:                           'value="'.$currval.'" size="10" />&nbsp;'.
 7757:                           $fieldtitles{$fields[$i]}.'</span></td>';
 7758:         }
 7759:         my $colsleft = $numperrow - $rem;
 7760:         if ($colsleft > 1 ) {
 7761:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7762:                          '&nbsp;</td>';
 7763:         } elsif ($colsleft == 1) {
 7764:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 7765:         }
 7766:         $datatable .= '</tr></table></td></tr>';
 7767:         $$rowtotal ++;
 7768:     } elsif ($position eq 'middle') {
 7769:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 7770:         my @posstypes;
 7771:         if (ref($types) eq 'ARRAY') {
 7772:             @posstypes = @{$types};
 7773:         }
 7774:         unless (grep(/^default$/,@posstypes)) {
 7775:             push(@posstypes,'default');
 7776:         }
 7777:         my %usertypeshash;
 7778:         if (ref($usertypes) eq 'HASH') {
 7779:             %usertypeshash = %{$usertypes};
 7780:         }
 7781:         $usertypeshash{'default'} = $othertitle;
 7782:         foreach my $status (@posstypes) {
 7783:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 7784:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 7785:             $$rowtotal ++;
 7786:         }
 7787:     } else {
 7788:         my %choices = &Apache::lonlocal::texthash (
 7789:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 7790:                                                   );
 7791:         my @toggles = sort(keys(%choices));
 7792:         my %defaultchecked = (
 7793:                                'cancreate_email' => 'off',
 7794:                              );
 7795:         my $customclass = 'LC_selfcreate_email';
 7796:         my $classprefix = 'LC_canmodify_emailusername_';
 7797:         my $optionsprefix = 'LC_options_emailusername_';
 7798:         my $display = 'none';
 7799:         my $rowstyle = 'display:none';
 7800:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 7801:             $display = 'block';
 7802:             $rowstyle = 'display:table-row';
 7803:         }
 7804:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
 7805:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 7806:                                                      \%choices,$$rowtotal,$onclick);
 7807:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
 7808:                                          $rowstyle);
 7809:         $$rowtotal ++;
 7810:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
 7811:                                       $rowstyle);
 7812:         $$rowtotal ++;
 7813:         my (@ordered,@posstypes,%usertypeshash);
 7814:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 7815:         my ($emailrules,$emailruleorder) =
 7816:             &Apache::lonnet::inst_userrules($dom,'email');
 7817:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7818:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7819:         if (ref($types) eq 'ARRAY') {
 7820:             @posstypes = @{$types};
 7821:         }
 7822:         if (@posstypes) {
 7823:             unless (grep(/^default$/,@posstypes)) {
 7824:                 push(@posstypes,'default');
 7825:             }
 7826:             if (ref($usertypes) eq 'HASH') {
 7827:                 %usertypeshash = %{$usertypes};
 7828:             }
 7829:             my $currassign;
 7830:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
 7831:                 $currassign = {
 7832:                                   selfassign => $domdefaults{'inststatusguest'},
 7833:                               };
 7834:                 @ordered = @{$domdefaults{'inststatusguest'}};
 7835:             } else {
 7836:                 $currassign = { selfassign => [] };
 7837:             }
 7838:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
 7839:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
 7840:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
 7841:                                          $numinrow,$othertitle,'selfassign',
 7842:                                          $rowtotal,$onclicktypes,$customclass,
 7843:                                          $rowstyle);
 7844:             $$rowtotal ++;
 7845:             $usertypeshash{'default'} = $othertitle;
 7846:             foreach my $status (@posstypes) {
 7847:                 my $css_class;
 7848:                 if ($$rowtotal%2) {
 7849:                     $css_class = 'LC_odd_row ';
 7850:                 }
 7851:                 $css_class .= $customclass;
 7852:                 my $rowid = $optionsprefix.$status;
 7853:                 my $hidden = 1;
 7854:                 my $currstyle = 'display:none';
 7855:                 if (grep(/^\Q$status\E$/,@ordered)) {
 7856:                     $currstyle = $rowstyle;
 7857:                     $hidden = 0; 
 7858:                 }
 7859:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 7860:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
 7861:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
 7862:                 unless ($hidden) {
 7863:                     $$rowtotal ++;
 7864:                 }
 7865:             }
 7866:         } else {
 7867:             my $css_class;
 7868:             if ($$rowtotal%2) {
 7869:                 $css_class = 'LC_odd_row ';
 7870:             }
 7871:             $css_class .= $customclass;
 7872:             $usertypeshash{'default'} = $othertitle;
 7873:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 7874:                                          $emailrules,$emailruleorder,$settings,'default','',
 7875:                                          $othertitle,$css_class,$rowstyle,$intdom);
 7876:             $$rowtotal ++;
 7877:         }
 7878:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 7879:         $numinrow = 1;
 7880:         if (@posstypes) {
 7881:             foreach my $status (@posstypes) {
 7882:                 my $rowid = $classprefix.$status;
 7883:                 my $datarowstyle = 'display:none';
 7884:                 if (grep(/^\Q$status\E$/,@ordered)) { 
 7885:                     $datarowstyle = $rowstyle; 
 7886:                 }
 7887:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 7888:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 7889:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
 7890:                 unless ($datarowstyle eq 'display:none') {
 7891:                     $$rowtotal ++;
 7892:                 }
 7893:             }
 7894:         } else {
 7895:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
 7896:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 7897:                                                    $infotitles,'',$customclass,$rowstyle);
 7898:         }
 7899:     }
 7900:     return $datatable;
 7901: }
 7902: 
 7903: sub selfcreate_javascript {
 7904:     return <<"ENDSCRIPT";
 7905: 
 7906: <script type="text/javascript">
 7907: // <![CDATA[
 7908: 
 7909: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
 7910:     var x = document.getElementsByClassName(target);
 7911:     var insttypes = 0;
 7912:     var insttypeRegExp = new RegExp(prefix);
 7913:     if ((x.length != undefined) && (x.length > 0)) {
 7914:         if (form.elements[radio].length != undefined) {
 7915:             for (var i=0; i<form.elements[radio].length; i++) {
 7916:                 if (form.elements[radio][i].checked) {
 7917:                     if (form.elements[radio][i].value == 1) {
 7918:                         for (var j=0; j<x.length; j++) {
 7919:                             if (x[j].id == 'undefined') {
 7920:                                 x[j].style.display = 'table-row';
 7921:                             } else if (insttypeRegExp.test(x[j].id)) {
 7922:                                 insttypes ++;
 7923:                             } else {
 7924:                                 x[j].style.display = 'table-row';
 7925:                             }
 7926:                         }
 7927:                     } else {
 7928:                         for (var j=0; j<x.length; j++) {
 7929:                             x[j].style.display = 'none';
 7930:                         }
 7931:                     }
 7932:                     break;
 7933:                 }
 7934:             }
 7935:             if (insttypes > 0) {
 7936:                 toggleDataRow(form,checkbox,target,altprefix);
 7937:                 toggleDataRow(form,checkbox,target,prefix,1);
 7938:             }
 7939:         }
 7940:     }
 7941:     return;
 7942: }
 7943: 
 7944: function toggleDataRow(form,checkbox,target,prefix,docount) {
 7945:     if (form.elements[checkbox].length != undefined) {
 7946:         var count = 0;
 7947:         if (docount) {
 7948:             for (var i=0; i<form.elements[checkbox].length; i++) {
 7949:                 if (form.elements[checkbox][i].checked) {
 7950:                     count ++;
 7951:                 }
 7952:             }
 7953:         }
 7954:         for (var i=0; i<form.elements[checkbox].length; i++) {
 7955:             var type = form.elements[checkbox][i].value;
 7956:             if (document.getElementById(prefix+type)) {
 7957:                 if (form.elements[checkbox][i].checked) {
 7958:                     document.getElementById(prefix+type).style.display = 'table-row';
 7959:                     if (count % 2 == 1) {
 7960:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 7961:                     } else {
 7962:                         document.getElementById(prefix+type).className = target;
 7963:                     }
 7964:                     count ++;
 7965:                 } else {
 7966:                     document.getElementById(prefix+type).style.display = 'none';
 7967:                 }
 7968:             }
 7969:         }
 7970:     }
 7971:     return;
 7972: }
 7973: 
 7974: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
 7975:     var caller = radio+'_'+status;
 7976:     if (form.elements[caller].length != undefined) {
 7977:         for (var i=0; i<form.elements[caller].length; i++) {
 7978:             if (form.elements[caller][i].checked) {
 7979:                 if (document.getElementById(altprefix+'_inst_'+status)) {
 7980:                     var curr = form.elements[caller][i].value;
 7981:                     if (prefix) {
 7982:                         document.getElementById(prefix+'_'+status).style.display = 'none';
 7983:                     }
 7984:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
 7985:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
 7986:                     if (curr == 'custom') {
 7987:                         if (prefix) { 
 7988:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
 7989:                         }
 7990:                     } else if (curr == 'inst') {
 7991:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
 7992:                     } else if (curr == 'noninst') {
 7993:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
 7994:                     }
 7995:                     break;
 7996:                 }
 7997:             }
 7998:         }
 7999:     }
 8000: }
 8001: 
 8002: // ]]>
 8003: </script>
 8004: 
 8005: ENDSCRIPT
 8006: }
 8007: 
 8008: sub noninst_users {
 8009:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
 8010:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_; 
 8011:     my $class = 'LC_left_item';
 8012:     if ($css_class) {
 8013:         $css_class = ' class="'.$css_class.'"'; 
 8014:     }
 8015:     if ($rowid) {
 8016:         $rowid = ' id="'.$rowid.'"';
 8017:     }
 8018:     if ($rowstyle) {
 8019:         $rowstyle = ' style="'.$rowstyle.'"';
 8020:     }
 8021:     my ($output,$description);
 8022:     if ($type eq 'default') {
 8023:         $description = &mt('Requests for: [_1]',$typetitle);
 8024:     } else {
 8025:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
 8026:     }
 8027:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 8028:               "<td>$description</td>\n".           
 8029:               '<td class="'.$class.'" colspan="2">'.
 8030:               '<table><tr>';
 8031:     my %headers = &Apache::lonlocal::texthash( 
 8032:               approve  => 'Processing',
 8033:               email    => 'E-mail',
 8034:               username => 'Username',
 8035:     );
 8036:     foreach my $item ('approve','email','username') {
 8037:         $output .= '<th>'.$headers{$item}.'</th>';
 8038:     }
 8039:     $output .= '</tr><tr>';
 8040:     foreach my $item ('approve','email','username') {
 8041:         $output .= '<td style="vertical-align: top">';
 8042:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
 8043:         if ($item eq 'approve') {
 8044:             %choices = &Apache::lonlocal::texthash (
 8045:                                                      automatic => 'Automatically approved',
 8046:                                                      approval  => 'Queued for approval',
 8047:                                                    );
 8048:             @options = ('automatic','approval');
 8049:             $hashref = $processing;
 8050:             $defoption = 'automatic';
 8051:             $name = 'cancreate_emailprocess_'.$type;
 8052:         } elsif ($item eq 'email') {
 8053:             %choices = &Apache::lonlocal::texthash (
 8054:                                                      any     => 'Any e-mail',
 8055:                                                      inst    => 'Institutional only',
 8056:                                                      noninst => 'Non-institutional only',
 8057:                                                      custom  => 'Custom restrictions',
 8058:                                                    );
 8059:             @options = ('any','inst','noninst');
 8060:             my $showcustom;
 8061:             if (ref($emailrules) eq 'HASH') {
 8062:                 if (keys(%{$emailrules}) > 0) {
 8063:                     push(@options,'custom');
 8064:                     $showcustom = 'cancreate_emailrule';
 8065:                     if (ref($settings) eq 'HASH') {
 8066:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 8067:                             foreach my $rule (@{$settings->{'email_rule'}}) {
 8068:                                 if (exists($emailrules->{$rule})) {
 8069:                                     $hascustom ++;
 8070:                                 }
 8071:                             }
 8072:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
 8073:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
 8074:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
 8075:                                     if (exists($emailrules->{$rule})) {
 8076:                                         $hascustom ++;
 8077:                                     }
 8078:                                 }
 8079:                             }
 8080:                         }
 8081:                     }
 8082:                 }
 8083:             }
 8084:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
 8085:                                                      "'cancreate_emaildomain','$type'".');"';
 8086:             $hashref = $emailoptions;
 8087:             $defoption = 'any';
 8088:             $name = 'cancreate_emailoptions_'.$type;
 8089:         } elsif ($item eq 'username') {
 8090:             %choices = &Apache::lonlocal::texthash (
 8091:                                                      all    => 'Same as e-mail',
 8092:                                                      first  => 'Omit @domain',
 8093:                                                      free   => 'Free to choose',
 8094:                                                    );
 8095:             @options = ('all','first','free');
 8096:             $hashref = $emailverified;
 8097:             $defoption = 'all';
 8098:             $name = 'cancreate_usernameoptions_'.$type;
 8099:         }
 8100:         foreach my $option (@options) {
 8101:             my $checked;
 8102:             if (ref($hashref) eq 'HASH') {
 8103:                 if ($type eq '') {
 8104:                     if (!exists($hashref->{'default'})) {
 8105:                         if ($option eq $defoption) {
 8106:                             $checked = ' checked="checked"';
 8107:                         }
 8108:                     } else {
 8109:                         if ($hashref->{'default'} eq $option) {
 8110:                             $checked = ' checked="checked"';
 8111:                         }
 8112:                     }
 8113:                 } else {
 8114:                     if (!exists($hashref->{$type})) {
 8115:                         if ($option eq $defoption) {
 8116:                             $checked = ' checked="checked"';
 8117:                         }
 8118:                     } else {
 8119:                         if ($hashref->{$type} eq $option) {
 8120:                             $checked = ' checked="checked"';
 8121:                         }
 8122:                     }
 8123:                 }
 8124:             } elsif (($item eq 'email') && ($hascustom)) {
 8125:                 if ($option eq 'custom') {
 8126:                     $checked = ' checked="checked"';
 8127:                 }
 8128:             } elsif ($option eq $defoption) {
 8129:                 $checked = ' checked="checked"';
 8130:             }
 8131:             $output .= '<span class="LC_nobreak"><label>'.
 8132:                        '<input type="radio" name="'.$name.'"'.
 8133:                        $checked.' value="'.$option.'"'.$onclick.' />'.
 8134:                        $choices{$option}.'</label></span><br />';
 8135:             if ($item eq 'email') {
 8136:                 if ($option eq 'custom') {
 8137:                     my $id = 'cancreate_emailrule_'.$type;
 8138:                     my $display = 'none';
 8139:                     if ($checked) {
 8140:                         $display = 'inline';
 8141:                     }
 8142:                     my $numinrow = 2;
 8143:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
 8144:                                '<legend>'.&mt('Disallow').'</legend><table>'.
 8145:                                &user_formats_row('email',$settings,$emailrules,
 8146:                                                  $emailruleorder,$numinrow,'',$type);
 8147:                               '</table></fieldset>';
 8148:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
 8149:                     my %text = &Apache::lonlocal::texthash (
 8150:                                                              inst    => 'must end:',
 8151:                                                              noninst => 'cannot end:',
 8152:                                                            );
 8153:                     my $value;
 8154:                     if (ref($emaildomain) eq 'HASH') {
 8155:                         if (ref($emaildomain->{$type}) eq 'HASH') {
 8156:                             $value = $emaildomain->{$type}->{$option}; 
 8157:                         }
 8158:                     }
 8159:                     if ($value eq '') {
 8160:                         $value = '@'.$intdom;
 8161:                     }
 8162:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
 8163:                     my $display = 'none';
 8164:                     if ($checked) {
 8165:                         $display = 'inline';
 8166:                     }
 8167:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
 8168:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
 8169:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
 8170:                                '</div>';
 8171:                 }
 8172:             }
 8173:         }
 8174:         $output .= '</td>'."\n";
 8175:     }
 8176:     $output .= "</tr></table></td></tr>\n";
 8177:     return $output;
 8178: }
 8179: 
 8180: sub captcha_choice {
 8181:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
 8182:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
 8183:         $vertext,$currver);
 8184:     my %lt = &captcha_phrases();
 8185:     $keyentry = 'hidden';
 8186:     my $colspan=2;
 8187:     if ($context eq 'cancreate') {
 8188:         $rowname = &mt('CAPTCHA validation');
 8189:     } elsif ($context eq 'login') {
 8190:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
 8191:     } elsif ($context eq 'passwords') {
 8192:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
 8193:         $colspan=1;
 8194:     }
 8195:     if (ref($settings) eq 'HASH') {
 8196:         if ($settings->{'captcha'}) {
 8197:             $checked{$settings->{'captcha'}} = ' checked="checked"';
 8198:         } else {
 8199:             $checked{'original'} = ' checked="checked"';
 8200:         }
 8201:         if ($settings->{'captcha'} eq 'recaptcha') {
 8202:             $pubtext = $lt{'pub'};
 8203:             $privtext = $lt{'priv'};
 8204:             $keyentry = 'text';
 8205:             $vertext = $lt{'ver'};
 8206:             $currver = $settings->{'recaptchaversion'};
 8207:             if ($currver ne '2') {
 8208:                 $currver = 1;
 8209:             }
 8210:         }
 8211:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
 8212:             $currpub = $settings->{'recaptchakeys'}{'public'};
 8213:             $currpriv = $settings->{'recaptchakeys'}{'private'};
 8214:         }
 8215:     } else {
 8216:         $checked{'original'} = ' checked="checked"';
 8217:     }
 8218:     my $css_class;
 8219:     if ($itemcount%2) {
 8220:         $css_class = 'LC_odd_row';
 8221:     }
 8222:     if ($customcss) {
 8223:         $css_class .= " $customcss";
 8224:     }
 8225:     $css_class =~ s/^\s+//;
 8226:     if ($css_class) {
 8227:         $css_class = ' class="'.$css_class.'"';
 8228:     }
 8229:     if ($rowstyle) {
 8230:         $css_class .= ' style="'.$rowstyle.'"';
 8231:     }
 8232:     my $output = '<tr'.$css_class.'>'.
 8233:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
 8234:                  '<table><tr><td>'."\n";
 8235:     foreach my $option ('original','recaptcha','notused') {
 8236:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
 8237:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
 8238:                    $lt{$option}.'</label></span>';
 8239:         unless ($option eq 'notused') {
 8240:             $output .= ('&nbsp;'x2)."\n";
 8241:         }
 8242:     }
 8243: #
 8244: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
 8245: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
 8246: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
 8247: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
 8248: #
 8249:     $output .= '</td></tr>'."\n".
 8250:                '<tr><td class="LC_zero_height">'."\n".
 8251:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
 8252:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
 8253:                $currpub.'" size="40" /></span><br />'."\n".
 8254:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
 8255:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
 8256:                $currpriv.'" size="40" /></span><br />'.
 8257:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
 8258:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
 8259:                $currver.'" size="3" /></span><br />'.
 8260:                '</td></tr></table>'."\n".
 8261:                '</td></tr>';
 8262:     return $output;
 8263: }
 8264: 
 8265: sub user_formats_row {
 8266:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
 8267:     my $output;
 8268:     my %text = (
 8269:                    'username' => 'new usernames',
 8270:                    'id'       => 'IDs',
 8271:                );
 8272:     unless ($type eq 'email') {
 8273:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 8274:         $output = '<tr '.$css_class.'>'.
 8275:                   '<td><span class="LC_nobreak">'.
 8276:                   &mt("Format rules to check for $text{$type}: ").
 8277:                   '</td><td class="LC_left_item" colspan="2"><table>';
 8278:     }
 8279:     my $rem;
 8280:     if (ref($ruleorder) eq 'ARRAY') {
 8281:         for (my $i=0; $i<@{$ruleorder}; $i++) {
 8282:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
 8283:                 my $rem = $i%($numinrow);
 8284:                 if ($rem == 0) {
 8285:                     if ($i > 0) {
 8286:                         $output .= '</tr>';
 8287:                     }
 8288:                     $output .= '<tr>';
 8289:                 }
 8290:                 my $check = ' ';
 8291:                 if (ref($settings) eq 'HASH') {
 8292:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
 8293:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
 8294:                             $check = ' checked="checked" ';
 8295:                         }
 8296:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
 8297:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
 8298:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
 8299:                                 $check = ' checked="checked" ';
 8300:                             }
 8301:                         }
 8302:                     }
 8303:                 }
 8304:                 my $name = $type.'_rule';
 8305:                 if ($type eq 'email') {
 8306:                     $name .= '_'.$status;
 8307:                 }
 8308:                 $output .= '<td class="LC_left_item">'.
 8309:                            '<span class="LC_nobreak"><label>'.
 8310:                            '<input type="checkbox" name="'.$name.'" '.
 8311:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
 8312:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
 8313:             }
 8314:         }
 8315:         $rem = @{$ruleorder}%($numinrow);
 8316:     }
 8317:     my $colsleft;
 8318:     if ($rem) {
 8319:         $colsleft = $numinrow - $rem;
 8320:     }
 8321:     if ($colsleft > 1 ) {
 8322:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8323:                    '&nbsp;</td>';
 8324:     } elsif ($colsleft == 1) {
 8325:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 8326:     }
 8327:     $output .= '</tr></table>';
 8328:     unless ($type eq 'email') {
 8329:         $output .= '</td></tr>';
 8330:     }
 8331:     return $output;
 8332: }
 8333: 
 8334: sub usercreation_types {
 8335:     my %lt = &Apache::lonlocal::texthash (
 8336:                     author     => 'When adding a co-author',
 8337:                     course     => 'When adding a user to a course',
 8338:                     requestcrs => 'When requesting a course',
 8339:                     any        => 'Any',
 8340:                     official   => 'Institutional only ',
 8341:                     unofficial => 'Non-institutional only',
 8342:                     none       => 'None',
 8343:     );
 8344:     return %lt;
 8345: }
 8346: 
 8347: sub selfcreation_types {
 8348:     my %lt = &Apache::lonlocal::texthash (
 8349:                     selfcreate => 'User creates own account',
 8350:                     any        => 'Any',
 8351:                     official   => 'Institutional only ',
 8352:                     unofficial => 'Non-institutional only',
 8353:                     email      => 'E-mail address',
 8354:                     login      => 'Institutional Login',
 8355:                     sso        => 'SSO',
 8356:              );
 8357: }
 8358: 
 8359: sub authtype_names {
 8360:     my %lt = &Apache::lonlocal::texthash(
 8361:                       int    => 'Internal',
 8362:                       krb4   => 'Kerberos 4',
 8363:                       krb5   => 'Kerberos 5',
 8364:                       loc    => 'Local',
 8365:                       lti    => 'LTI',
 8366:                   );
 8367:     return %lt;
 8368: }
 8369: 
 8370: sub context_names {
 8371:     my %context_title = &Apache::lonlocal::texthash(
 8372:        author => 'Creating users when an Author',
 8373:        course => 'Creating users when in a course',
 8374:        domain => 'Creating users when a Domain Coordinator',
 8375:     );
 8376:     return %context_title;
 8377: }
 8378: 
 8379: sub print_usermodification {
 8380:     my ($position,$dom,$settings,$rowtotal) = @_;
 8381:     my $numinrow = 4;
 8382:     my ($context,$datatable,$rowcount);
 8383:     if ($position eq 'top') {
 8384:         $rowcount = 0;
 8385:         $context = 'author'; 
 8386:         foreach my $role ('ca','aa') {
 8387:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 8388:                                                    $numinrow,$rowcount);
 8389:             $$rowtotal ++;
 8390:             $rowcount ++;
 8391:         }
 8392:     } elsif ($position eq 'bottom') {
 8393:         $context = 'course';
 8394:         $rowcount = 0;
 8395:         foreach my $role ('st','ep','ta','in','cr') {
 8396:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 8397:                                                    $numinrow,$rowcount);
 8398:             $$rowtotal ++;
 8399:             $rowcount ++;
 8400:         }
 8401:     }
 8402:     return $datatable;
 8403: }
 8404: 
 8405: sub print_defaults {
 8406:     my ($position,$dom,$settings,$rowtotal) = @_;
 8407:     my $rownum = 0;
 8408:     my ($datatable,$css_class,$titles);
 8409:     unless ($position eq 'bottom') {
 8410:         $titles = &defaults_titles($dom);
 8411:     }
 8412:     if ($position eq 'top') {
 8413:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
 8414:                      'datelocale_def','portal_def');
 8415:         my %defaults;
 8416:         if (ref($settings) eq 'HASH') {
 8417:             %defaults = %{$settings};
 8418:         } else {
 8419:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 8420:             foreach my $item (@items) {
 8421:                 $defaults{$item} = $domdefaults{$item};
 8422:             }
 8423:         }
 8424:         foreach my $item (@items) {
 8425:             if ($rownum%2) {
 8426:                 $css_class = '';
 8427:             } else {
 8428:                 $css_class = ' class="LC_odd_row" ';
 8429:             }
 8430:             $datatable .= '<tr'.$css_class.'>'.
 8431:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 8432:                           '</span></td><td class="LC_right_item" colspan="3">';
 8433:             if ($item eq 'auth_def') {
 8434:                 my @authtypes = ('internal','krb4','krb5','localauth','lti');
 8435:                 my %shortauth = (
 8436:                                  internal => 'int',
 8437:                                  krb4 => 'krb4',
 8438:                                  krb5 => 'krb5',
 8439:                                  localauth  => 'loc',
 8440:                                  lti => 'lti',
 8441:                                 );
 8442:                 my %authnames = &authtype_names();
 8443:                 foreach my $auth (@authtypes) {
 8444:                     my $checked = ' ';
 8445:                     if ($defaults{$item} eq $auth) {
 8446:                         $checked = ' checked="checked" ';
 8447:                     }
 8448:                     $datatable .= '<label><input type="radio" name="'.$item.
 8449:                                   '" value="'.$auth.'"'.$checked.'/>'.
 8450:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
 8451:                 }
 8452:             } elsif ($item eq 'timezone_def') {
 8453:                 my $includeempty = 1;
 8454:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
 8455:             } elsif ($item eq 'datelocale_def') {
 8456:                 my $includeempty = 1;
 8457:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
 8458:             } elsif ($item eq 'lang_def') {
 8459:                 my $includeempty = 1;
 8460:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
 8461:             } else {
 8462:                 my $size;
 8463:                 if ($item eq 'portal_def') {
 8464:                     $size = ' size="25"';
 8465:                 }
 8466:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 8467:                               $defaults{$item}.'"'.$size.' />';
 8468:             }
 8469:             $datatable .= '</td></tr>';
 8470:             $rownum ++;
 8471:         }
 8472:     } else {
 8473:         my %defaults;
 8474:         if (ref($settings) eq 'HASH') {
 8475:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 8476:                 my $maxnum = @{$settings->{'inststatusorder'}};
 8477:                 for (my $i=0; $i<$maxnum; $i++) {
 8478:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
 8479:                     my $item = $settings->{'inststatusorder'}->[$i];
 8480:                     my $title = $settings->{'inststatustypes'}->{$item};
 8481:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
 8482:                     $datatable .= '<tr'.$css_class.'>'.
 8483:                                   '<td><span class="LC_nobreak">'.
 8484:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
 8485:                     for (my $k=0; $k<=$maxnum; $k++) {
 8486:                         my $vpos = $k+1;
 8487:                         my $selstr;
 8488:                         if ($k == $i) {
 8489:                             $selstr = ' selected="selected" ';
 8490:                         }
 8491:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8492:                     }
 8493:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
 8494:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
 8495:                                   &mt('delete').'</span></td>'.
 8496:                                   '<td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.&mt('Name displayed:').
 8497:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
 8498:                                   '</span></td></tr>';
 8499:                 }
 8500:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
 8501:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
 8502:                 $datatable .= '<tr '.$css_class.'>'.
 8503:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
 8504:                 for (my $k=0; $k<=$maxnum; $k++) {
 8505:                     my $vpos = $k+1;
 8506:                     my $selstr;
 8507:                     if ($k == $maxnum) {
 8508:                         $selstr = ' selected="selected" ';
 8509:                     }
 8510:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 8511:                 }
 8512:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
 8513:                               '<input type="text" size="10" name="addinststatus" value="" />'.
 8514:                               '&nbsp;'.&mt('(new)').
 8515:                               '</span></td><td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.
 8516:                               &mt('Name displayed:').
 8517:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
 8518:                               '</tr>'."\n";
 8519:                 $rownum ++;
 8520:             }
 8521:         }
 8522:     }
 8523:     $$rowtotal += $rownum;
 8524:     return $datatable;
 8525: }
 8526: 
 8527: sub get_languages_hash {
 8528:     my %langchoices;
 8529:     foreach my $id (&Apache::loncommon::languageids()) {
 8530:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 8531:         if ($code ne '') {
 8532:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 8533:         }
 8534:     }
 8535:     return %langchoices;
 8536: }
 8537: 
 8538: sub defaults_titles {
 8539:     my ($dom) = @_;
 8540:     my %titles = &Apache::lonlocal::texthash (
 8541:                    'auth_def'      => 'Default authentication type',
 8542:                    'auth_arg_def'  => 'Default authentication argument',
 8543:                    'lang_def'      => 'Default language',
 8544:                    'timezone_def'  => 'Default timezone',
 8545:                    'datelocale_def' => 'Default locale for dates',
 8546:                    'portal_def'     => 'Portal/Default URL',
 8547:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
 8548:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
 8549:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
 8550:                  );
 8551:     if ($dom) {
 8552:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
 8553:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 8554:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
 8555:         $protocol = 'http' if ($protocol ne 'https');
 8556:         if ($uint_dom) {
 8557:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
 8558:                                          $uint_dom);
 8559:         }
 8560:     }
 8561:     return (\%titles);
 8562: }
 8563: 
 8564: sub print_scantron {
 8565:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
 8566:     if ($position eq 'top') {
 8567:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
 8568:     } else {
 8569:         return &print_scantronconfig($dom,$settings,\$rowtotal);
 8570:     }
 8571: }
 8572: 
 8573: sub scantron_javascript {
 8574:     return <<"ENDSCRIPT";
 8575: 
 8576: <script type="text/javascript">
 8577: // <![CDATA[
 8578: 
 8579: function toggleScantron(form) {
 8580:     var csvfieldset = new Array();
 8581:     if (document.getElementById('scantroncsv_cols')) {
 8582:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
 8583:     }
 8584:     if (document.getElementById('scantroncsv_options')) {
 8585:         csvfieldset.push(document.getElementById('scantroncsv_options'));
 8586:     }
 8587:     if (csvfieldset.length) {
 8588:         if (document.getElementById('scantronconfcsv')) {
 8589:             var scantroncsv = document.getElementById('scantronconfcsv');
 8590:             if (scantroncsv.checked) {
 8591:                 for (var i=0; i<csvfieldset.length; i++) {
 8592:                     csvfieldset[i].style.display = 'block';
 8593:                 }
 8594:             } else {
 8595:                 for (var i=0; i<csvfieldset.length; i++) {
 8596:                     csvfieldset[i].style.display = 'none';
 8597:                 }
 8598:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
 8599:                 if (csvselects.length) {
 8600:                     for (var j=0; j<csvselects.length; j++) {
 8601:                         csvselects[j].selectedIndex = 0;
 8602:                     }
 8603:                 }
 8604:             }
 8605:         }
 8606:     }
 8607:     return;
 8608: }
 8609: // ]]>
 8610: </script>
 8611: 
 8612: ENDSCRIPT
 8613: 
 8614: }
 8615: 
 8616: sub print_scantronformat {
 8617:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
 8618:     my $itemcount = 1;
 8619:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
 8620:         %confhash);
 8621:     my $switchserver = &check_switchserver($dom,$confname);
 8622:     my %lt = &Apache::lonlocal::texthash (
 8623:                 default => 'Default bubblesheet format file error',
 8624:                 custom  => 'Custom bubblesheet format file error',
 8625:              );
 8626:     my %scantronfiles = (
 8627:         default => 'default.tab',
 8628:         custom => 'custom.tab',
 8629:     );
 8630:     foreach my $key (keys(%scantronfiles)) {
 8631:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
 8632:                               .$scantronfiles{$key};
 8633:     }
 8634:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
 8635:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
 8636:         if (!$switchserver) {
 8637:             my $servadm = $r->dir_config('lonAdmEMail');
 8638:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
 8639:             if ($configuserok eq 'ok') {
 8640:                 if ($author_ok eq 'ok') {
 8641:                     my %legacyfile = (
 8642:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
 8643:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
 8644:                     );
 8645:                     my %md5chk;
 8646:                     foreach my $type (keys(%legacyfile)) {
 8647:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
 8648:                         chomp($md5chk{$type});
 8649:                     }
 8650:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
 8651:                         foreach my $type (keys(%legacyfile)) {
 8652:                             ($scantronurls{$type},my $error) =
 8653:                                 &legacy_scantronformat($r,$dom,$confname,
 8654:                                                  $type,$legacyfile{$type},
 8655:                                                  $scantronurls{$type},
 8656:                                                  $scantronfiles{$type});
 8657:                             if ($error ne '') {
 8658:                                 $error{$type} = $error;
 8659:                             }
 8660:                         }
 8661:                         if (keys(%error) == 0) {
 8662:                             $is_custom = 1;
 8663:                             $confhash{'scantron'}{'scantronformat'} =
 8664:                                 $scantronurls{'custom'};
 8665:                             my $putresult =
 8666:                                 &Apache::lonnet::put_dom('configuration',
 8667:                                                          \%confhash,$dom);
 8668:                             if ($putresult ne 'ok') {
 8669:                                 $error{'custom'} =
 8670:                                     '<span class="LC_error">'.
 8671:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 8672:                             }
 8673:                         }
 8674:                     } else {
 8675:                         ($scantronurls{'default'},my $error) =
 8676:                             &legacy_scantronformat($r,$dom,$confname,
 8677:                                           'default',$legacyfile{'default'},
 8678:                                           $scantronurls{'default'},
 8679:                                           $scantronfiles{'default'});
 8680:                         if ($error eq '') {
 8681:                             $confhash{'scantron'}{'scantronformat'} = ''; 
 8682:                             my $putresult =
 8683:                                 &Apache::lonnet::put_dom('configuration',
 8684:                                                          \%confhash,$dom);
 8685:                             if ($putresult ne 'ok') {
 8686:                                 $error{'default'} =
 8687:                                     '<span class="LC_error">'.
 8688:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 8689:                             }
 8690:                         } else {
 8691:                             $error{'default'} = $error;
 8692:                         }
 8693:                     }
 8694:                 }
 8695:             }
 8696:         } else {
 8697:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
 8698:         }
 8699:     }
 8700:     if (ref($settings) eq 'HASH') {
 8701:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
 8702:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
 8703:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
 8704:                 $scantronurl = '';
 8705:             } else {
 8706:                 $scantronurl = $settings->{'scantronformat'};
 8707:             }
 8708:             $is_custom = 1;
 8709:         } else {
 8710:             $scantronurl = $scantronurls{'default'};
 8711:         }
 8712:     } else {
 8713:         if ($is_custom) {
 8714:             $scantronurl = $scantronurls{'custom'};
 8715:         } else {
 8716:             $scantronurl = $scantronurls{'default'};
 8717:         }
 8718:     }
 8719:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8720:     $datatable .= '<tr'.$css_class.'>';
 8721:     if (!$is_custom) {
 8722:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
 8723:                       '<span class="LC_nobreak">';
 8724:         if ($scantronurl) {
 8725:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
 8726:                                                          undef,undef,undef,undef,'background-color:#ffffff');
 8727:         } else {
 8728:             $datatable = &mt('File unavailable for display');
 8729:         }
 8730:         $datatable .= '</span></td>';
 8731:         if (keys(%error) == 0) { 
 8732:             $datatable .= '<td style="vertical-align: bottom">';
 8733:             if (!$switchserver) {
 8734:                 $datatable .= &mt('Upload:').'<br />';
 8735:             }
 8736:         } else {
 8737:             my $errorstr;
 8738:             foreach my $key (sort(keys(%error))) {
 8739:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 8740:             }
 8741:             $datatable .= '<td>'.$errorstr;
 8742:         }
 8743:     } else {
 8744:         if (keys(%error) > 0) {
 8745:             my $errorstr;
 8746:             foreach my $key (sort(keys(%error))) {
 8747:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 8748:             } 
 8749:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
 8750:         } elsif ($scantronurl) {
 8751:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
 8752:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 8753:             $datatable .= '<td><span class="LC_nobreak">'.
 8754:                           $link.
 8755:                           '<label><input type="checkbox" name="scantronformat_del"'.
 8756:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
 8757:                           '<td><span class="LC_nobreak">&nbsp;'.
 8758:                           &mt('Replace:').'</span><br />';
 8759:         }
 8760:     }
 8761:     if (keys(%error) == 0) {
 8762:         if ($switchserver) {
 8763:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 8764:         } else {
 8765:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 8766:                          '<input type="file" name="scantronformat" /></span>';
 8767:         }
 8768:     }
 8769:     $datatable .= '</td></tr>';
 8770:     $$rowtotal ++;
 8771:     return $datatable;
 8772: }
 8773: 
 8774: sub legacy_scantronformat {
 8775:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
 8776:     my ($url,$error);
 8777:     my @statinfo = &Apache::lonnet::stat_file($newurl);
 8778:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
 8779:         (my $result,$url) =
 8780:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
 8781:                          '','',$newfile);
 8782:         if ($result ne 'ok') {
 8783:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
 8784:         }
 8785:     }
 8786:     return ($url,$error);
 8787: }
 8788: 
 8789: sub print_scantronconfig {
 8790:     my ($dom,$settings,$rowtotal) = @_;
 8791:     my $itemcount = 2;
 8792:     my $is_checked = ' checked="checked"';
 8793:     my %optionson = (
 8794:                      hdr => ' checked="checked"',
 8795:                      pad => ' checked="checked"',
 8796:                      rem => ' checked="checked"',
 8797:                     );
 8798:     my %optionsoff = (
 8799:                       hdr => '',
 8800:                       pad => '',
 8801:                       rem => '',
 8802:                      );
 8803:     my $currcsvsty = 'none';
 8804:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
 8805:     my @fields = &scantroncsv_fields();
 8806:     my %titles = &scantronconfig_titles();
 8807:     if (ref($settings) eq 'HASH') {
 8808:         if (ref($settings->{config}) eq 'HASH') {
 8809:             if ($settings->{config}->{dat}) {
 8810:                 $checked{'dat'} = $is_checked;
 8811:             }
 8812:             if (ref($settings->{config}->{csv}) eq 'HASH') {
 8813:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
 8814:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
 8815:                     if (keys(%csvfields) > 0) {
 8816:                         $checked{'csv'} = $is_checked;
 8817:                         $currcsvsty = 'block';
 8818:                     }
 8819:                 }
 8820:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
 8821:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
 8822:                     foreach my $option (keys(%optionson)) {
 8823:                         unless ($csvoptions{$option}) {
 8824:                             $optionsoff{$option} = $optionson{$option};
 8825:                             $optionson{$option} = '';
 8826:                         }
 8827:                     }
 8828:                 }
 8829:             }
 8830:         } else {
 8831:             $checked{'dat'} = $is_checked;
 8832:         }
 8833:     } else {
 8834:         $checked{'dat'} = $is_checked;
 8835:     }
 8836:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
 8837:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 8838:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
 8839:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
 8840:     foreach my $item ('dat','csv') {
 8841:         my $id;
 8842:         if ($item eq 'csv') {
 8843:             $id = 'id="scantronconfcsv" ';
 8844:         }
 8845:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
 8846:                       $titles{$item}.'</label>'.('&nbsp;'x3);
 8847:         if ($item eq 'csv') {
 8848:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
 8849:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
 8850:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
 8851:             foreach my $col (@fields) {
 8852:                 my $selnone;
 8853:                 if ($csvfields{$col} eq '') {
 8854:                     $selnone = ' selected="selected"';
 8855:                 }
 8856:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
 8857:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
 8858:                               '<option value=""'.$selnone.'></option>';
 8859:                 for (my $i=0; $i<20; $i++) {
 8860:                     my $shown = $i+1;
 8861:                     my $sel;
 8862:                     unless ($selnone) {
 8863:                         if (exists($csvfields{$col})) {
 8864:                             if ($csvfields{$col} == $i) {
 8865:                                 $sel = ' selected="selected"';
 8866:                             }
 8867:                         }
 8868:                     }
 8869:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
 8870:                 }
 8871:                 $datatable .= '</select></td></tr>';
 8872:            }
 8873:            $datatable .= '</table></fieldset>'.
 8874:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
 8875:                          '<legend>'.&mt('CSV Options').'</legend>';
 8876:            foreach my $option ('hdr','pad','rem') {
 8877:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
 8878:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
 8879:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
 8880:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
 8881:            }
 8882:            $datatable .= '</fieldset>';
 8883:            $itemcount ++;
 8884:         }
 8885:     }
 8886:     $datatable .= '</td></tr>';
 8887:     $$rowtotal ++;
 8888:     return $datatable;
 8889: }
 8890: 
 8891: sub scantronconfig_titles {
 8892:     return &Apache::lonlocal::texthash(
 8893:                                           dat => 'Standard format (.dat)',
 8894:                                           csv => 'Comma separated values (.csv)',
 8895:                                           hdr => 'Remove first line in file (contains column titles)',
 8896:                                           pad => 'Prepend 0s to PaperID',
 8897:                                           rem => 'Remove leading spaces (except Question Response columns)',
 8898:                                           CODE => 'CODE',
 8899:                                           ID   => 'Student ID',
 8900:                                           PaperID => 'Paper ID',
 8901:                                           FirstName => 'First Name',
 8902:                                           LastName => 'Last Name',
 8903:                                           FirstQuestion => 'First Question Response',
 8904:                                           Section => 'Section',
 8905:     );
 8906: }
 8907: 
 8908: sub scantroncsv_fields {
 8909:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
 8910: }
 8911: 
 8912: sub print_coursecategories {
 8913:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
 8914:     my $datatable;
 8915:     if ($position eq 'top') {
 8916:         my (%checked);
 8917:         my @catitems = ('unauth','auth');
 8918:         my @cattypes = ('std','domonly','codesrch','none');
 8919:         $checked{'unauth'} = 'std';
 8920:         $checked{'auth'} = 'std';
 8921:         if (ref($settings) eq 'HASH') {
 8922:             foreach my $type (@cattypes) {
 8923:                 if ($type eq $settings->{'unauth'}) {
 8924:                     $checked{'unauth'} = $type;
 8925:                 }
 8926:                 if ($type eq $settings->{'auth'}) {
 8927:                     $checked{'auth'} = $type;
 8928:                 }
 8929:             }
 8930:         }
 8931:         my %lt = &Apache::lonlocal::texthash (
 8932:                                                unauth   => 'Catalog type for unauthenticated users',
 8933:                                                auth     => 'Catalog type for authenticated users',
 8934:                                                none     => 'No catalog',
 8935:                                                std      => 'Standard catalog',
 8936:                                                domonly  => 'Domain-only catalog',
 8937:                                                codesrch => "Code search form",
 8938:                                              );
 8939:        my $itemcount = 0;
 8940:        foreach my $item (@catitems) {
 8941:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 8942:            $datatable .= '<tr '.$css_class.'>'.
 8943:                          '<td>'.$lt{$item}.'</td>'.
 8944:                          '<td class="LC_right_item"><span class="LC_nobreak">';
 8945:            foreach my $type (@cattypes) {
 8946:                my $ischecked;
 8947:                if ($checked{$item} eq $type) {
 8948:                    $ischecked=' checked="checked"';
 8949:                }
 8950:                $datatable .= '<label>'.
 8951:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
 8952:                              ' />'.$lt{$type}.'</label>&nbsp;';
 8953:            }
 8954:            $datatable .= '</span></td></tr>';
 8955:            $itemcount ++;
 8956:         }
 8957:         $$rowtotal += $itemcount;
 8958:     } elsif ($position eq 'middle') {
 8959:         my $toggle_cats_crs = ' ';
 8960:         my $toggle_cats_dom = ' checked="checked" ';
 8961:         my $can_cat_crs = ' ';
 8962:         my $can_cat_dom = ' checked="checked" ';
 8963:         my $toggle_catscomm_comm = ' ';
 8964:         my $toggle_catscomm_dom = ' checked="checked" ';
 8965:         my $can_catcomm_comm = ' ';
 8966:         my $can_catcomm_dom = ' checked="checked" ';
 8967:         my $toggle_catsplace_place = ' ';
 8968:         my $toggle_catsplace_dom = ' checked="checked" ';
 8969:         my $can_catplace_place = ' ';
 8970:         my $can_catplace_dom = ' checked="checked" ';
 8971: 
 8972:         if (ref($settings) eq 'HASH') {
 8973:             if ($settings->{'togglecats'} eq 'crs') {
 8974:                 $toggle_cats_crs = $toggle_cats_dom;
 8975:                 $toggle_cats_dom = ' ';
 8976:             }
 8977:             if ($settings->{'categorize'} eq 'crs') {
 8978:                 $can_cat_crs = $can_cat_dom;
 8979:                 $can_cat_dom = ' ';
 8980:             }
 8981:             if ($settings->{'togglecatscomm'} eq 'comm') {
 8982:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
 8983:                 $toggle_catscomm_dom = ' ';
 8984:             }
 8985:             if ($settings->{'categorizecomm'} eq 'comm') {
 8986:                 $can_catcomm_comm = $can_catcomm_dom;
 8987:                 $can_catcomm_dom = ' ';
 8988:             }
 8989:             if ($settings->{'togglecatsplace'} eq 'place') {
 8990:                 $toggle_catsplace_place = $toggle_catsplace_dom;
 8991:                 $toggle_catsplace_dom = ' ';
 8992:             }
 8993:             if ($settings->{'categorizeplace'} eq 'place') {
 8994:                 $can_catplace_place = $can_catplace_dom;
 8995:                 $can_catplace_dom = ' ';
 8996:             }
 8997:         }
 8998:         my %title = &Apache::lonlocal::texthash (
 8999:                      togglecats      => 'Show/Hide a course in catalog',
 9000:                      togglecatscomm  => 'Show/Hide a community in catalog',
 9001:                      togglecatsplace => 'Show/Hide a placement test in catalog',
 9002:                      categorize      => 'Assign a category to a course',
 9003:                      categorizecomm  => 'Assign a category to a community',
 9004:                      categorizeplace => 'Assign a category to a placement test',
 9005:                     );
 9006:         my %level = &Apache::lonlocal::texthash (
 9007:                      dom   => 'Set in Domain',
 9008:                      crs   => 'Set in Course',
 9009:                      comm  => 'Set in Community',
 9010:                      place => 'Set in Placement Test',
 9011:                     );
 9012:         $datatable = '<tr class="LC_odd_row">'.
 9013:                   '<td>'.$title{'togglecats'}.'</td>'.
 9014:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 9015:                   '<input type="radio" name="togglecats"'.
 9016:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9017:                   '<label><input type="radio" name="togglecats"'.
 9018:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
 9019:                   '</tr><tr>'.
 9020:                   '<td>'.$title{'categorize'}.'</td>'.
 9021:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 9022:                   '<label><input type="radio" name="categorize"'.
 9023:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9024:                   '<label><input type="radio" name="categorize"'.
 9025:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
 9026:                   '</tr><tr class="LC_odd_row">'.
 9027:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
 9028:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 9029:                   '<input type="radio" name="togglecatscomm"'.
 9030:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9031:                   '<label><input type="radio" name="togglecatscomm"'.
 9032:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
 9033:                   '</tr><tr>'.
 9034:                   '<td>'.$title{'categorizecomm'}.'</td>'.
 9035:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 9036:                   '<label><input type="radio" name="categorizecomm"'.
 9037:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9038:                   '<label><input type="radio" name="categorizecomm"'.
 9039:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
 9040:                   '</tr><tr class="LC_odd_row">'.
 9041:                   '<td>'.$title{'togglecatsplace'}.'</td>'.
 9042:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 9043:                   '<input type="radio" name="togglecatsplace"'.
 9044:                   $toggle_catsplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9045:                   '<label><input type="radio" name="togglecatscomm"'.
 9046:                   $toggle_catsplace_place.' value="comm" />'.$level{'place'}.'</label></span></td>'.
 9047:                   '</tr><tr>'.
 9048:                   '<td>'.$title{'categorizeplace'}.'</td>'.
 9049:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 9050:                   '<label><input type="radio" name="categorizeplace"'.
 9051:                   $can_catplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
 9052:                   '<label><input type="radio" name="categorizeplace"'.
 9053:                   $can_catplace_place.'value="place" />'.$level{'place'}.'</label></span></td>'.
 9054:                   '</tr>';
 9055:         $$rowtotal += 6;
 9056:     } else {
 9057:         my $css_class;
 9058:         my $itemcount = 1;
 9059:         my $cathash; 
 9060:         if (ref($settings) eq 'HASH') {
 9061:             $cathash = $settings->{'cats'};
 9062:         }
 9063:         if (ref($cathash) eq 'HASH') {
 9064:             my (@cats,@trails,%allitems,%idx,@jsarray);
 9065:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
 9066:                                                    \%allitems,\%idx,\@jsarray);
 9067:             my $maxdepth = scalar(@cats);
 9068:             my $colattrib = '';
 9069:             if ($maxdepth > 2) {
 9070:                 $colattrib = ' colspan="2" ';
 9071:             }
 9072:             my @path;
 9073:             if (@cats > 0) {
 9074:                 if (ref($cats[0]) eq 'ARRAY') {
 9075:                     my $numtop = @{$cats[0]};
 9076:                     my $maxnum = $numtop;
 9077:                     my %default_names = (
 9078:                           instcode    => &mt('Official courses'),
 9079:                           communities => &mt('Communities'),
 9080:                           placement   => &mt('Placement Tests'),
 9081:                     );
 9082: 
 9083:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
 9084:                         ($cathash->{'instcode::0'} eq '') ||
 9085:                         (!grep(/^communities$/,@{$cats[0]})) || 
 9086:                         ($cathash->{'communities::0'} eq '') ||
 9087:                         (!grep(/^placement$/,@{$cats[0]})) ||
 9088:                         ($cathash->{'placement::0'} eq '')) {
 9089:                         $maxnum ++;
 9090:                     }
 9091:                     my $lastidx;
 9092:                     for (my $i=0; $i<$numtop; $i++) {
 9093:                         my $parent = $cats[0][$i];
 9094:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9095:                         my $item = &escape($parent).'::0';
 9096:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
 9097:                         $lastidx = $idx{$item};
 9098:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 9099:                                       .'<select name="'.$item.'"'.$chgstr.'>';
 9100:                         for (my $k=0; $k<=$maxnum; $k++) {
 9101:                             my $vpos = $k+1;
 9102:                             my $selstr;
 9103:                             if ($k == $i) {
 9104:                                 $selstr = ' selected="selected" ';
 9105:                             }
 9106:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9107:                         }
 9108:                         $datatable .= '</select></span></td><td>';
 9109:                         if ($parent eq 'instcode' || $parent eq 'communities' || $parent eq 'placement') {
 9110:                             $datatable .=  '<span class="LC_nobreak">'
 9111:                                            .$default_names{$parent}.'</span>';
 9112:                             if ($parent eq 'instcode') {
 9113:                                 $datatable .= '<br /><span class="LC_nobreak">('
 9114:                                               .&mt('with institutional codes')
 9115:                                               .')</span></td><td'.$colattrib.'>';
 9116:                             } else {
 9117:                                 $datatable .= '<table><tr><td>';
 9118:                             }
 9119:                             $datatable .= '<span class="LC_nobreak">'
 9120:                                           .'<label><input type="radio" name="'
 9121:                                           .$parent.'" value="1" checked="checked" />'
 9122:                                           .&mt('Display').'</label>';
 9123:                             if ($parent eq 'instcode') {
 9124:                                 $datatable .= '&nbsp;';
 9125:                             } else {
 9126:                                 $datatable .= '</span></td></tr><tr><td>'
 9127:                                               .'<span class="LC_nobreak">';
 9128:                             }
 9129:                             $datatable .= '<label><input type="radio" name="'
 9130:                                           .$parent.'" value="0" />'
 9131:                                           .&mt('Do not display').'</label></span>';
 9132:                             if (($parent eq 'communities') || ($parent eq 'placement')) {
 9133:                                 $datatable .= '</td></tr></table>';
 9134:                             }
 9135:                             $datatable .= '</td>';
 9136:                         } else {
 9137:                             $datatable .= $parent
 9138:                                           .'&nbsp;<span class="LC_nobreak"><label>'
 9139:                                           .'<input type="checkbox" name="deletecategory" '
 9140:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
 9141:                         }
 9142:                         my $depth = 1;
 9143:                         push(@path,$parent);
 9144:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
 9145:                         pop(@path);
 9146:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
 9147:                         $itemcount ++;
 9148:                     }
 9149:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9150:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
 9151:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
 9152:                     for (my $k=0; $k<=$maxnum; $k++) {
 9153:                         my $vpos = $k+1;
 9154:                         my $selstr;
 9155:                         if ($k == $numtop) {
 9156:                             $selstr = ' selected="selected" ';
 9157:                         }
 9158:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9159:                     }
 9160:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
 9161:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
 9162:                                   .'</tr>'."\n";
 9163:                     $itemcount ++;
 9164:                     foreach my $default ('instcode','communities','placement') {
 9165:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
 9166:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9167:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
 9168:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
 9169:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
 9170:                             for (my $k=0; $k<=$maxnum; $k++) {
 9171:                                 my $vpos = $k+1;
 9172:                                 my $selstr;
 9173:                                 if ($k == $maxnum) {
 9174:                                     $selstr = ' selected="selected" ';
 9175:                                 }
 9176:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9177:                             }
 9178:                             $datatable .= '</select></span></td>'.
 9179:                                           '<td><span class="LC_nobreak">'.
 9180:                                           $default_names{$default}.'</span>';
 9181:                             if ($default eq 'instcode') {
 9182:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
 9183:                                               .&mt('with institutional codes').')</span>';
 9184:                             }
 9185:                             $datatable .= '</td>'
 9186:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
 9187:                                           .&mt('Display').'</label>&nbsp;'
 9188:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
 9189:                                           .&mt('Do not display').'</label></span></td></tr>';
 9190:                         }
 9191:                     }
 9192:                 }
 9193:             } else {
 9194:                 $datatable .= &initialize_categories($itemcount);
 9195:             }
 9196:         } else {
 9197:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
 9198:                           .&initialize_categories($itemcount);
 9199:         }
 9200:         $$rowtotal += $itemcount;
 9201:     }
 9202:     return $datatable;
 9203: }
 9204: 
 9205: sub print_serverstatuses {
 9206:     my ($dom,$settings,$rowtotal) = @_;
 9207:     my $datatable;
 9208:     my @pages = &serverstatus_pages();
 9209:     my (%namedaccess,%machineaccess);
 9210:     foreach my $type (@pages) {
 9211:         $namedaccess{$type} = '';
 9212:         $machineaccess{$type}= '';
 9213:     }
 9214:     if (ref($settings) eq 'HASH') {
 9215:         foreach my $type (@pages) {
 9216:             if (exists($settings->{$type})) {
 9217:                 if (ref($settings->{$type}) eq 'HASH') {
 9218:                     foreach my $key (keys(%{$settings->{$type}})) {
 9219:                         if ($key eq 'namedusers') {
 9220:                             $namedaccess{$type} = $settings->{$type}->{$key};
 9221:                         } elsif ($key eq 'machines') {
 9222:                             $machineaccess{$type} = $settings->{$type}->{$key};
 9223:                         }
 9224:                     }
 9225:                 }
 9226:             }
 9227:         }
 9228:     }
 9229:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
 9230:     my $rownum = 0;
 9231:     my $css_class;
 9232:     foreach my $type (@pages) {
 9233:         $rownum ++;
 9234:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 9235:         $datatable .= '<tr'.$css_class.'>'.
 9236:                       '<td><span class="LC_nobreak">'.
 9237:                       $titles->{$type}.'</span></td>'.
 9238:                       '<td class="LC_left_item">'.
 9239:                       '<input type="text" name="'.$type.'_namedusers" '.
 9240:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
 9241:                       '<td class="LC_right_item">'.
 9242:                       '<span class="LC_nobreak">'.
 9243:                       '<input type="text" name="'.$type.'_machines" '.
 9244:                       'value="'.$machineaccess{$type}.'" size="10" />'.
 9245:                       '</span></td></tr>'."\n";
 9246:     }
 9247:     $$rowtotal += $rownum;
 9248:     return $datatable;
 9249: }
 9250: 
 9251: sub serverstatus_pages {
 9252:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
 9253:             'checksums','clusterstatus','certstatus','metadata_keywords',
 9254:             'metadata_harvest','takeoffline','takeonline','showenv','toggledebug',
 9255:             'ping','domconf','uniquecodes','diskusage','coursecatalog');
 9256: }
 9257: 
 9258: sub defaults_javascript {
 9259:     my ($settings) = @_;
 9260:     return unless (ref($settings) eq 'HASH');
 9261:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 9262:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
 9263:         if ($maxnum eq '') {
 9264:             $maxnum = 0;
 9265:         }
 9266:         $maxnum ++;
 9267:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
 9268:         return <<"ENDSCRIPT";
 9269: <script type="text/javascript">
 9270: // <![CDATA[
 9271: function reorderTypes(form,caller) {
 9272:     var changedVal;
 9273: $jstext 
 9274:     var newpos = 'addinststatus_pos';
 9275:     var current = new Array;
 9276:     var maxh = $maxnum;
 9277:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 9278:     var oldVal;
 9279:     if (caller == newpos) {
 9280:         changedVal = newitemVal;
 9281:     } else {
 9282:         var curritem = 'inststatus_pos_'+caller;
 9283:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
 9284:         current[newitemVal] = newpos;
 9285:     }
 9286:     for (var i=0; i<inststatuses.length; i++) {
 9287:         if (inststatuses[i] != caller) {
 9288:             var elementName = 'inststatus_pos_'+inststatuses[i];
 9289:             if (form.elements[elementName]) {
 9290:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 9291:                 current[currVal] = elementName;
 9292:             }
 9293:         }
 9294:     }
 9295:     for (var j=0; j<maxh; j++) {
 9296:         if (current[j] == undefined) {
 9297:             oldVal = j;
 9298:         }
 9299:     }
 9300:     if (oldVal < changedVal) {
 9301:         for (var k=oldVal+1; k<=changedVal ; k++) {
 9302:            var elementName = current[k];
 9303:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 9304:         }
 9305:     } else {
 9306:         for (var k=changedVal; k<oldVal; k++) {
 9307:             var elementName = current[k];
 9308:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 9309:         }
 9310:     }
 9311:     return;
 9312: }
 9313: 
 9314: // ]]>
 9315: </script>
 9316: 
 9317: ENDSCRIPT
 9318:     }
 9319:     return;
 9320: }
 9321: 
 9322: sub passwords_javascript {
 9323:     my %intalert = &Apache::lonlocal::texthash (
 9324:         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.',
 9325:         authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
 9326:         passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
 9327:         passmax => 'Warning: maximum password length must be a positive integer (or blank).',
 9328:         passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
 9329:         passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
 9330:     );
 9331:     &js_escape(\%intalert);
 9332:     my $defmin = $Apache::lonnet::passwdmin;
 9333:     my $intauthjs = <<"ENDSCRIPT";
 9334: 
 9335: function warnIntAuth(field) {
 9336:     if (field.name == 'intauth_check') {
 9337:         if (field.value == '2') {
 9338:             alert('$intalert{authcheck}');
 9339:         }
 9340:     }
 9341:     if (field.name == 'intauth_cost') {
 9342:         field.value.replace(/\s/g,'');
 9343:         if (field.value != '') {
 9344:             var regexdigit=/^\\d+\$/;
 9345:             if (!regexdigit.test(field.value)) {
 9346:                 alert('$intalert{authcost}');
 9347:             }
 9348:         }
 9349:     }
 9350:     return;
 9351: }
 9352: 
 9353: function warnIntPass(field) {
 9354:     field.value.replace(/^\s+/,'');
 9355:     field.value.replace(/\s+\$/,'');
 9356:     var regexdigit=/^\\d+\$/;
 9357:     if (field.name == 'passwords_min') {
 9358:         if (field.value == '') {
 9359:             alert('$intalert{passmin}');
 9360:             field.value = '$defmin';
 9361:         } else {
 9362:             if (!regexdigit.test(field.value)) {
 9363:                 alert('$intalert{passmin}');
 9364:                 field.value = '$defmin';
 9365:             }
 9366:             var minval = parseInt(field.value,10);
 9367:             if (minval < $defmin) {
 9368:                 alert('$intalert{passmin}');
 9369:                 field.value = '$defmin';
 9370:             }
 9371:         }
 9372:     } else {
 9373:         if (field.value == '0') {
 9374:             field.value = '';
 9375:         }
 9376:         if (field.value != '') {
 9377:             if (field.name == 'passwords_expire') {
 9378:                 var regexpposnum=/^\\d+(|\\.\\d*)\$/; 
 9379:                 if (!regexpposnum.test(field.value)) {
 9380:                     alert('$intalert{passexp}');
 9381:                     field.value = '';
 9382:                 } else {
 9383:                     var expval = parseFloat(field.value);
 9384:                     if (expval == 0) {
 9385:                         alert('$intalert{passexp}');
 9386:                         field.value = '';
 9387:                     }
 9388:                 }
 9389:             } else {
 9390:                 if (!regexdigit.test(field.value)) {
 9391:                     if (field.name == 'passwords_max') {
 9392:                         alert('$intalert{passmax}');
 9393:                     } else {
 9394:                         if (field.name == 'passwords_numsaved') {
 9395:                             alert('$intalert{passnum}');
 9396:                         }
 9397:                     }
 9398:                     field.value = '';
 9399:                 }
 9400:             }
 9401:         }
 9402:     }
 9403:     return;
 9404: }
 9405: 
 9406: ENDSCRIPT
 9407:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
 9408: }
 9409: 
 9410: sub coursecategories_javascript {
 9411:     my ($settings) = @_;
 9412:     my ($output,$jstext,$cathash);
 9413:     if (ref($settings) eq 'HASH') {
 9414:         $cathash = $settings->{'cats'};
 9415:     }
 9416:     if (ref($cathash) eq 'HASH') {
 9417:         my (@cats,@jsarray,%idx);
 9418:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
 9419:         if (@jsarray > 0) {
 9420:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
 9421:             for (my $i=0; $i<@jsarray; $i++) {
 9422:                 if (ref($jsarray[$i]) eq 'ARRAY') {
 9423:                     my $catstr = join('","',@{$jsarray[$i]});
 9424:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
 9425:                 }
 9426:             }
 9427:         }
 9428:     } else {
 9429:         $jstext  = '    var categories = Array(1);'."\n".
 9430:                    '    categories[0] = Array("instcode_pos");'."\n"; 
 9431:     }
 9432:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
 9433:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
 9434:     my $placement_reserved = &mt('The name: [_1] is a reserved category.','"placement"');
 9435:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
 9436:     &js_escape(\$instcode_reserved);
 9437:     &js_escape(\$communities_reserved);
 9438:     &js_escape(\$placement_reserved);
 9439:     &js_escape(\$choose_again);
 9440:     $output = <<"ENDSCRIPT";
 9441: <script type="text/javascript">
 9442: // <![CDATA[
 9443: function reorderCats(form,parent,item,idx) {
 9444:     var changedVal;
 9445: $jstext
 9446:     var newpos = 'addcategory_pos';
 9447:     if (parent == '') {
 9448:         var has_instcode = 0;
 9449:         var maxtop = categories[idx].length;
 9450:         for (var j=0; j<maxtop; j++) {
 9451:             if (categories[idx][j] == 'instcode::0') {
 9452:                 has_instcode == 1;
 9453:             }
 9454:         }
 9455:         if (has_instcode == 0) {
 9456:             categories[idx][maxtop] = 'instcode_pos';
 9457:         }
 9458:     } else {
 9459:         newpos += '_'+parent;
 9460:     }
 9461:     var maxh = 1 + categories[idx].length;
 9462:     var current = new Array;
 9463:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 9464:     if (item == newpos) {
 9465:         changedVal = newitemVal;
 9466:     } else {
 9467:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 9468:         current[newitemVal] = newpos;
 9469:     }
 9470:     for (var i=0; i<categories[idx].length; i++) {
 9471:         var elementName = categories[idx][i];
 9472:         if (elementName != item) {
 9473:             if (form.elements[elementName]) {
 9474:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 9475:                 current[currVal] = elementName;
 9476:             }
 9477:         }
 9478:     }
 9479:     var oldVal;
 9480:     for (var j=0; j<maxh; j++) {
 9481:         if (current[j] == undefined) {
 9482:             oldVal = j;
 9483:         }
 9484:     }
 9485:     if (oldVal < changedVal) {
 9486:         for (var k=oldVal+1; k<=changedVal ; k++) {
 9487:            var elementName = current[k];
 9488:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 9489:         }
 9490:     } else {
 9491:         for (var k=changedVal; k<oldVal; k++) {
 9492:             var elementName = current[k];
 9493:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 9494:         }
 9495:     }
 9496:     return;
 9497: }
 9498: 
 9499: function categoryCheck(form) {
 9500:     if (form.elements['addcategory_name'].value == 'instcode') {
 9501:         alert('$instcode_reserved\\n$choose_again');
 9502:         return false;
 9503:     }
 9504:     if (form.elements['addcategory_name'].value == 'communities') {
 9505:         alert('$communities_reserved\\n$choose_again');
 9506:         return false;
 9507:     }
 9508:     if (form.elements['addcategory_name'].value == 'placement') {
 9509:         alert('$placement_reserved\\n$choose_again');
 9510:         return false;
 9511:     }
 9512:     return true;
 9513: }
 9514: 
 9515: // ]]>
 9516: </script>
 9517: 
 9518: ENDSCRIPT
 9519:     return $output;
 9520: }
 9521: 
 9522: sub initialize_categories {
 9523:     my ($itemcount) = @_;
 9524:     my ($datatable,$css_class,$chgstr);
 9525:     my %default_names = (
 9526:                       instcode    => 'Official courses (with institutional codes)',
 9527:                       communities => 'Communities',
 9528:                       placement   => 'Placement Tests',
 9529:                         );
 9530:     my %selnum = (
 9531:                    instcode    => '0',
 9532:                    communities => '1',
 9533:                    placement   => '2',
 9534:                  );
 9535:     my %selected;
 9536:     foreach my $default ('instcode','communities','placement') {
 9537:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9538:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
 9539:         map { $selected{$selnum{$_}} = '' } keys(%selnum);
 9540:         $selected{$selnum{$default}} = ' selected="selected"';
 9541:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 9542:                      .'<select name="'.$default.'_pos"'.$chgstr.'>'
 9543:                      .'<option value="0"'.$selected{'0'}.'>1</option>'
 9544:                      .'<option value="1"'.$selected{'1'}.'>2</option>'
 9545:                      .'<option value="2"'.$selected{'2'}.'>3</option>'
 9546:                      .'<option value="3">4</option></select>&nbsp;'
 9547:                      .$default_names{$default}
 9548:                      .'</span></td><td><span class="LC_nobreak">'
 9549:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
 9550:                      .&mt('Display').'</label>&nbsp;<label>'
 9551:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
 9552:                  .'</label></span></td></tr>';
 9553:         $itemcount ++;
 9554:     }
 9555:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9556:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
 9557:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 9558:                   .'<select name="addcategory_pos"'.$chgstr.'>'
 9559:                   .'<option value="0">1</option>'
 9560:                   .'<option value="1">2</option>'
 9561:                   .'<option value="2">3</option>'
 9562:                   .'<option value="3" selected="selected">4</option></select>&nbsp;'
 9563:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
 9564:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
 9565:                   .'</td></tr>';
 9566:     return $datatable;
 9567: }
 9568: 
 9569: sub build_category_rows {
 9570:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
 9571:     my ($text,$name,$item,$chgstr);
 9572:     if (ref($cats) eq 'ARRAY') {
 9573:         my $maxdepth = scalar(@{$cats});
 9574:         if (ref($cats->[$depth]) eq 'HASH') {
 9575:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
 9576:                 my $numchildren = @{$cats->[$depth]{$parent}};
 9577:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9578:                 $text .= '<td><table class="LC_data_table">';
 9579:                 my ($idxnum,$parent_name,$parent_item);
 9580:                 my $higher = $depth - 1;
 9581:                 if ($higher == 0) {
 9582:                     $parent_name = &escape($parent).'::'.$higher;
 9583:                 } else {
 9584:                     if (ref($path) eq 'ARRAY') {
 9585:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 9586:                     }
 9587:                 }
 9588:                 $parent_item = 'addcategory_pos_'.$parent_name;
 9589:                 for (my $j=0; $j<=$numchildren; $j++) {
 9590:                     if ($j < $numchildren) {
 9591:                         $name = $cats->[$depth]{$parent}[$j];
 9592:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
 9593:                         $idxnum = $idx->{$item};
 9594:                     } else {
 9595:                         $name = $parent_name;
 9596:                         $item = $parent_item;
 9597:                     }
 9598:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
 9599:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
 9600:                     for (my $i=0; $i<=$numchildren; $i++) {
 9601:                         my $vpos = $i+1;
 9602:                         my $selstr;
 9603:                         if ($j == $i) {
 9604:                             $selstr = ' selected="selected" ';
 9605:                         }
 9606:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
 9607:                     }
 9608:                     $text .= '</select>&nbsp;';
 9609:                     if ($j < $numchildren) {
 9610:                         my $deeper = $depth+1;
 9611:                         $text .= $name.'&nbsp;'
 9612:                                  .'<label><input type="checkbox" name="deletecategory" value="'
 9613:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
 9614:                         if(ref($path) eq 'ARRAY') {
 9615:                             push(@{$path},$name);
 9616:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
 9617:                             pop(@{$path});
 9618:                         }
 9619:                     } else {
 9620:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
 9621:                         if ($j == $numchildren) {
 9622:                             $text .= $name;
 9623:                         } else {
 9624:                             $text .= $item;
 9625:                         }
 9626:                         $text .= '" value="" />';
 9627:                     }
 9628:                     $text .= '</td></tr>';
 9629:                 }
 9630:                 $text .= '</table></td>';
 9631:             } else {
 9632:                 my $higher = $depth-1;
 9633:                 if ($higher == 0) {
 9634:                     $name = &escape($parent).'::'.$higher;
 9635:                 } else {
 9636:                     if (ref($path) eq 'ARRAY') {
 9637:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
 9638:                     }
 9639:                 }
 9640:                 my $colspan;
 9641:                 if ($parent ne 'instcode') {
 9642:                     $colspan = $maxdepth - $depth - 1;
 9643:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
 9644:                 }
 9645:             }
 9646:         }
 9647:     }
 9648:     return $text;
 9649: }
 9650: 
 9651: sub modifiable_userdata_row {
 9652:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
 9653:         $rowid,$customcss,$rowstyle,$itemdesc) = @_;
 9654:     my ($role,$rolename,$statustype);
 9655:     $role = $item;
 9656:     if ($context eq 'cancreate') {
 9657:         if ($item =~ /^(emailusername)_(.+)$/) {
 9658:             $role = $1;
 9659:             $statustype = $2;
 9660:             if (ref($usertypes) eq 'HASH') {
 9661:                 if ($usertypes->{$statustype}) {
 9662:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
 9663:                 } else {
 9664:                     $rolename = &mt('Data provided by user');
 9665:                 }
 9666:             }
 9667:         }
 9668:     } elsif ($context eq 'selfcreate') {
 9669:         if (ref($usertypes) eq 'HASH') {
 9670:             $rolename = $usertypes->{$role};
 9671:         } else {
 9672:             $rolename = $role;
 9673:         }
 9674:     } elsif ($context eq 'lti') {
 9675:         $rolename = &mt('Institutional data used (if available)');
 9676:     } elsif ($context eq 'privacy') {
 9677:         $rolename = $itemdesc;
 9678:     } else {
 9679:         if ($role eq 'cr') {
 9680:             $rolename = &mt('Custom role');
 9681:         } else {
 9682:             $rolename = &Apache::lonnet::plaintext($role);
 9683:         }
 9684:     }
 9685:     my (@fields,%fieldtitles);
 9686:     if (ref($fieldsref) eq 'ARRAY') {
 9687:         @fields = @{$fieldsref};
 9688:     } else {
 9689:         @fields = ('lastname','firstname','middlename','generation',
 9690:                    'permanentemail','id');
 9691:     }
 9692:     if ((ref($titlesref) eq 'HASH')) {
 9693:         %fieldtitles = %{$titlesref};
 9694:     } else {
 9695:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 9696:     }
 9697:     my $output;
 9698:     my $css_class;
 9699:     if ($rowcount%2) {
 9700:         $css_class = 'LC_odd_row';
 9701:     }
 9702:     if ($customcss) {
 9703:         $css_class .= " $customcss";
 9704:     }
 9705:     $css_class =~ s/^\s+//;
 9706:     if ($css_class) {
 9707:         $css_class = ' class="'.$css_class.'"';
 9708:     }
 9709:     if ($rowstyle) {
 9710:         $css_class .= ' style="'.$rowstyle.'"';
 9711:     }
 9712:     if ($rowid) {
 9713:         $rowid = ' id="'.$rowid.'"';
 9714:     }
 9715:     $output = '<tr '.$css_class.$rowid.'>'.
 9716:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
 9717:               '<td class="LC_left_item" colspan="2"><table>';
 9718:     my $rem;
 9719:     my %checks;
 9720:     my %current;
 9721:     if (ref($settings) eq 'HASH') {
 9722:         my $hashref;
 9723:         if ($context eq 'lti') {
 9724:             if (ref($settings) eq 'HASH') {
 9725:                 $hashref = $settings->{'instdata'};
 9726:             }
 9727:         } elsif ($context eq 'privacy') {
 9728:             my ($key,$inner) = split(/_/,$role);
 9729:             if (ref($settings) eq 'HASH') {
 9730:                 if (ref($settings->{$key}) eq 'HASH') {
 9731:                     $hashref = $settings->{$key}->{$inner};
 9732:                 }
 9733:             }
 9734:         } elsif (ref($settings->{$context}) eq 'HASH') {
 9735:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
 9736:                 $hashref = $settings->{'lti_instdata'};
 9737:             }
 9738:             if ($role eq 'emailusername') {
 9739:                 if ($statustype) {
 9740:                     if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
 9741:                         $hashref = $settings->{$context}->{$role}->{$statustype};
 9742:                     }
 9743:                 }
 9744:             }
 9745:         }
 9746:         if (ref($hashref) eq 'HASH') { 
 9747:             foreach my $field (@fields) {
 9748:                 if ($hashref->{$field}) {
 9749:                     if ($role eq 'emailusername') {
 9750:                         $checks{$field} = $hashref->{$field};
 9751:                     } else {
 9752:                         $checks{$field} = ' checked="checked" ';
 9753:                     }
 9754:                 }
 9755:             }
 9756:         }
 9757:     }
 9758:  
 9759:     my $total = scalar(@fields);
 9760:     for (my $i=0; $i<$total; $i++) {
 9761:         $rem = $i%($numinrow);
 9762:         if ($rem == 0) {
 9763:             if ($i > 0) {
 9764:                 $output .= '</tr>';
 9765:             }
 9766:             $output .= '<tr>';
 9767:         }
 9768:         my $check = ' ';
 9769:         unless ($role eq 'emailusername') {
 9770:             if (exists($checks{$fields[$i]})) {
 9771:                 $check = $checks{$fields[$i]};
 9772:             } elsif ($context eq 'privacy') {
 9773:                 if ($role =~ /^priv_(domain|course)$/) {
 9774:                     if (ref($settings) ne 'HASH') {
 9775:                         $check = ' checked="checked" ';
 9776:                     }
 9777:                 } elsif ($role =~ /^priv_(author|community)$/) {
 9778:                     if (ref($settings) ne 'HASH') {
 9779:                         unless ($fields[$i] eq 'id') {
 9780:                             $check = ' checked="checked" ';
 9781:                         }
 9782:                     }
 9783:                 } elsif ($role =~ /^(unpriv|othdom)_/) {
 9784:                     if (ref($settings) ne 'HASH') {
 9785:                         if (($fields[$i] eq 'lastname') || ($fields[$i] eq 'firstname')) {
 9786:                             $check = ' checked="checked" ';
 9787:                         }
 9788:                     }
 9789:                 }
 9790:             } elsif ($context ne 'lti') {
 9791:                 if ($role eq 'st') {
 9792:                     if (ref($settings) ne 'HASH') {
 9793:                         $check = ' checked="checked" '; 
 9794:                     }
 9795:                 }
 9796:             }
 9797:         }
 9798:         $output .= '<td class="LC_left_item">'.
 9799:                    '<span class="LC_nobreak">';
 9800:         my $prefix = 'canmodify';
 9801:         if ($role eq 'emailusername') {
 9802:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
 9803:                 $checks{$fields[$i]} = 'omit';
 9804:             }
 9805:             foreach my $option ('required','optional','omit') {
 9806:                 my $checked='';
 9807:                 if ($checks{$fields[$i]} eq $option) {
 9808:                     $checked='checked="checked" ';
 9809:                 }
 9810:                 $output .= '<label>'.
 9811:                            '<input type="radio" name="'.$prefix.'_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
 9812:                            &mt($option).'</label>'.('&nbsp;' x2);
 9813:             }
 9814:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
 9815:         } else {
 9816:             if ($context eq 'lti') {
 9817:                 $prefix = 'lti';
 9818:             } elsif ($context eq 'privacy') {
 9819:                 $prefix = 'privacy';
 9820:             }
 9821:             $output .= '<label>'.
 9822:                        '<input type="checkbox" name="'.$prefix.'_'.$role.'" '.
 9823:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
 9824:                        '</label>';
 9825:         }
 9826:         $output .= '</span></td>';
 9827:     }
 9828:     $rem = $total%$numinrow;
 9829:     my $colsleft;
 9830:     if ($rem) {
 9831:         $colsleft = $numinrow - $rem;
 9832:     }
 9833:     if ($colsleft > 1) {
 9834:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9835:                    '&nbsp;</td>';
 9836:     } elsif ($colsleft == 1) {
 9837:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 9838:     }
 9839:     $output .= '</tr></table></td></tr>';
 9840:     return $output;
 9841: }
 9842: 
 9843: sub insttypes_row {
 9844:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
 9845:         $customcss,$rowstyle) = @_;
 9846:     my %lt = &Apache::lonlocal::texthash (
 9847:                       cansearch => 'Users allowed to search',
 9848:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
 9849:                       lockablenames => 'User preference to lock name',
 9850:                       selfassign    => 'Self-reportable affiliations',
 9851:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
 9852:              );
 9853:     my $showdom;
 9854:     if ($context eq 'cansearch') {
 9855:         $showdom = ' ('.$dom.')';
 9856:     }
 9857:     my $class = 'LC_left_item';
 9858:     if ($context eq 'statustocreate') {
 9859:         $class = 'LC_right_item';
 9860:     }
 9861:     my $css_class;
 9862:     if ($$rowtotal%2) {
 9863:         $css_class = 'LC_odd_row';
 9864:     }
 9865:     if ($customcss) {
 9866:         $css_class .= ' '.$customcss;
 9867:     }
 9868:     $css_class =~ s/^\s+//;
 9869:     if ($css_class) {
 9870:         $css_class = ' class="'.$css_class.'"';
 9871:     }
 9872:     if ($rowstyle) {
 9873:         $css_class .= ' style="'.$rowstyle.'"';
 9874:     }
 9875:     if ($onclick) {
 9876:         $onclick = 'onclick="'.$onclick.'" ';
 9877:     }
 9878:     my $output = '<tr'.$css_class.'>'.
 9879:                  '<td>'.$lt{$context}.$showdom.
 9880:                  '</td><td class="'.$class.'" colspan="2"><table>';
 9881:     my $rem;
 9882:     if (ref($types) eq 'ARRAY') {
 9883:         for (my $i=0; $i<@{$types}; $i++) {
 9884:             if (defined($usertypes->{$types->[$i]})) {
 9885:                 my $rem = $i%($numinrow);
 9886:                 if ($rem == 0) {
 9887:                     if ($i > 0) {
 9888:                         $output .= '</tr>';
 9889:                     }
 9890:                     $output .= '<tr>';
 9891:                 }
 9892:                 my $check = ' ';
 9893:                 if (ref($settings) eq 'HASH') {
 9894:                     if (ref($settings->{$context}) eq 'ARRAY') {
 9895:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
 9896:                             $check = ' checked="checked" ';
 9897:                         }
 9898:                     } elsif (ref($settings->{$context}) eq 'HASH') {
 9899:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
 9900:                             $check = ' checked="checked" ';
 9901:                         }
 9902:                     } elsif ($context eq 'statustocreate') {
 9903:                         $check = ' checked="checked" ';
 9904:                     }
 9905:                 }
 9906:                 $output .= '<td class="LC_left_item">'.
 9907:                            '<span class="LC_nobreak"><label>'.
 9908:                            '<input type="checkbox" name="'.$context.'" '.
 9909:                            'value="'.$types->[$i].'"'.$check.$onclick.' />'.
 9910:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 9911:             }
 9912:         }
 9913:         $rem = @{$types}%($numinrow);
 9914:     }
 9915:     my $colsleft = $numinrow - $rem;
 9916:     if ($context eq 'overrides') {
 9917:         if ($colsleft > 1) {
 9918:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 9919:         } else {
 9920:             $output .= '<td class="LC_left_item">';
 9921:         }
 9922:         $output .= '&nbsp;';  
 9923:     } else {
 9924:         if ($rem == 0) {
 9925:             $output .= '<tr>';
 9926:         }
 9927:         if ($colsleft > 1) {
 9928:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 9929:         } else {
 9930:             $output .= '<td class="LC_left_item">';
 9931:         }
 9932:         my $defcheck = ' ';
 9933:         if (ref($settings) eq 'HASH') {  
 9934:             if (ref($settings->{$context}) eq 'ARRAY') {
 9935:                 if (grep(/^default$/,@{$settings->{$context}})) {
 9936:                     $defcheck = ' checked="checked" ';
 9937:                 }
 9938:             } elsif ($context eq 'statustocreate') {
 9939:                 $defcheck = ' checked="checked" ';
 9940:             }
 9941:         }
 9942:         $output .= '<span class="LC_nobreak"><label>'.
 9943:                    '<input type="checkbox" name="'.$context.'" '.
 9944:                    'value="default"'.$defcheck.$onclick.' />'.
 9945:                    $othertitle.'</label></span>';
 9946:     }
 9947:     $output .= '</td></tr></table></td></tr>';
 9948:     return $output;
 9949: }
 9950: 
 9951: sub sorted_searchtitles {
 9952:     my %searchtitles = &Apache::lonlocal::texthash(
 9953:                          'uname' => 'username',
 9954:                          'lastname' => 'last name',
 9955:                          'lastfirst' => 'last name, first name',
 9956:                      );
 9957:     my @titleorder = ('uname','lastname','lastfirst');
 9958:     return (\%searchtitles,\@titleorder);
 9959: }
 9960: 
 9961: sub sorted_searchtypes {
 9962:     my %srchtypes_desc = (
 9963:                            exact    => 'is exact match',
 9964:                            contains => 'contains ..',
 9965:                            begins   => 'begins with ..',
 9966:                          );
 9967:     my @srchtypeorder = ('exact','begins','contains');
 9968:     return (\%srchtypes_desc,\@srchtypeorder);
 9969: }
 9970: 
 9971: sub usertype_update_row {
 9972:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
 9973:     my $datatable;
 9974:     my $numinrow = 4;
 9975:     foreach my $type (@{$types}) {
 9976:         if (defined($usertypes->{$type})) {
 9977:             $$rownums ++;
 9978:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
 9979:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
 9980:                           '</td><td class="LC_left_item"><table>';
 9981:             for (my $i=0; $i<@{$fields}; $i++) {
 9982:                 my $rem = $i%($numinrow);
 9983:                 if ($rem == 0) {
 9984:                     if ($i > 0) {
 9985:                         $datatable .= '</tr>';
 9986:                     }
 9987:                     $datatable .= '<tr>';
 9988:                 }
 9989:                 my $check = ' ';
 9990:                 if (ref($settings) eq 'HASH') {
 9991:                     if (ref($settings->{'fields'}) eq 'HASH') {
 9992:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
 9993:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
 9994:                                 $check = ' checked="checked" ';
 9995:                             }
 9996:                         }
 9997:                     }
 9998:                 }
 9999: 
10000:                 if ($i == @{$fields}-1) {
10001:                     my $colsleft = $numinrow - $rem;
10002:                     if ($colsleft > 1) {
10003:                         $datatable .= '<td colspan="'.$colsleft.'">';
10004:                     } else {
10005:                         $datatable .= '<td>';
10006:                     }
10007:                 } else {
10008:                     $datatable .= '<td>';
10009:                 }
10010:                 $datatable .= '<span class="LC_nobreak"><label>'.
10011:                               '<input type="checkbox" name="updateable_'.$type.
10012:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
10013:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
10014:             }
10015:             $datatable .= '</tr></table></td></tr>';
10016:         }
10017:     }
10018:     return $datatable;
10019: }
10020: 
10021: sub modify_login {
10022:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
10023:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
10024:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon);
10025:     %title = ( coursecatalog => 'Display course catalog',
10026:                adminmail => 'Display administrator E-mail address',
10027:                helpdesk  => 'Display "Contact Helpdesk" link',
10028:                newuser => 'Link for visitors to create a user account',
10029:                loginheader => 'Log-in box header');
10030:     @offon = ('off','on');
10031:     if (ref($domconfig{login}) eq 'HASH') {
10032:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
10033:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
10034:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
10035:             }
10036:         }
10037:     }
10038:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
10039:                                            \%domconfig,\%loginhash);
10040:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
10041:     foreach my $item (@toggles) {
10042:         $loginhash{login}{$item} = $env{'form.'.$item};
10043:     }
10044:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
10045:     if (ref($colchanges{'login'}) eq 'HASH') {  
10046:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
10047:                                          \%loginhash);
10048:     }
10049: 
10050:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
10051:     my %domservers = &Apache::lonnet::get_servers($dom);
10052:     my @loginvia_attribs = ('serverpath','custompath','exempt');
10053:     if (keys(%servers) > 1) {
10054:         foreach my $lonhost (keys(%servers)) {
10055:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
10056:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
10057:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
10058:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
10059:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
10060:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
10061:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
10062:                         $changes{'loginvia'}{$lonhost} = 1;
10063:                     } else {
10064:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
10065:                         $changes{'loginvia'}{$lonhost} = 1;
10066:                     }
10067:                 } else {
10068:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
10069:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
10070:                         $changes{'loginvia'}{$lonhost} = 1;
10071:                     }
10072:                 }
10073:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
10074:                     foreach my $item (@loginvia_attribs) {
10075:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
10076:                     }
10077:                 } else {
10078:                     foreach my $item (@loginvia_attribs) {
10079:                         my $new = $env{'form.'.$lonhost.'_'.$item};
10080:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
10081:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
10082:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
10083:                                 $new = '/';
10084:                             }
10085:                         }
10086:                         if (($item eq 'custompath') && 
10087:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
10088:                             $new = '';
10089:                         }
10090:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
10091:                             $changes{'loginvia'}{$lonhost} = 1;
10092:                         }
10093:                         if ($item eq 'exempt') {
10094:                             $new = &check_exempt_addresses($new);
10095:                         }
10096:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
10097:                     }
10098:                 }
10099:             } else {
10100:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
10101:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
10102:                     $changes{'loginvia'}{$lonhost} = 1;
10103:                     foreach my $item (@loginvia_attribs) {
10104:                         my $new = $env{'form.'.$lonhost.'_'.$item};
10105:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
10106:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
10107:                                 $new = '/';
10108:                             }
10109:                         }
10110:                         if (($item eq 'custompath') && 
10111:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
10112:                             $new = '';
10113:                         }
10114:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
10115:                     }
10116:                 }
10117:             }
10118:         }
10119:     }
10120: 
10121:     my $servadm = $r->dir_config('lonAdmEMail');
10122:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
10123:     if (ref($domconfig{'login'}) eq 'HASH') {
10124:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
10125:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
10126:                 if ($lang eq 'nolang') {
10127:                     push(@currlangs,$lang);
10128:                 } elsif (defined($langchoices{$lang})) {
10129:                     push(@currlangs,$lang);
10130:                 } else {
10131:                     next;
10132:                 }
10133:             }
10134:         }
10135:     }
10136:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
10137:     if (@currlangs > 0) {
10138:         foreach my $lang (@currlangs) {
10139:             if (grep(/^\Q$lang\E$/,@delurls)) {
10140:                 $changes{'helpurl'}{$lang} = 1;
10141:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
10142:                 $changes{'helpurl'}{$lang} = 1;
10143:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
10144:                 push(@newlangs,$lang);
10145:             } else {
10146:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
10147:             }
10148:         }
10149:     }
10150:     unless (grep(/^nolang$/,@currlangs)) {
10151:         if ($env{'form.loginhelpurl_nolang.filename'}) {
10152:             $changes{'helpurl'}{'nolang'} = 1;
10153:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
10154:             push(@newlangs,'nolang');
10155:         }
10156:     }
10157:     if ($env{'form.loginhelpurl_add_lang'}) {
10158:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
10159:             ($env{'form.loginhelpurl_add_file.filename'})) {
10160:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
10161:             $addedfile = $env{'form.loginhelpurl_add_lang'};
10162:         }
10163:     }
10164:     if ((@newlangs > 0) || ($addedfile)) {
10165:         my $error;
10166:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
10167:         if ($configuserok eq 'ok') {
10168:             if ($switchserver) {
10169:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
10170:             } elsif ($author_ok eq 'ok') {
10171:                 my @allnew = @newlangs;
10172:                 if ($addedfile ne '') {
10173:                     push(@allnew,$addedfile);
10174:                 }
10175:                 foreach my $lang (@allnew) {
10176:                     my $formelem = 'loginhelpurl_'.$lang;
10177:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
10178:                         $formelem = 'loginhelpurl_add_file';
10179:                     }
10180:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
10181:                                                                "help/$lang",'','',$newfile{$lang});
10182:                     if ($result eq 'ok') {
10183:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
10184:                         $changes{'helpurl'}{$lang} = 1;
10185:                     } else {
10186:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
10187:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
10188:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
10189:                             (!grep(/^\Q$lang\E$/,@delurls))) {
10190:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
10191:                         }
10192:                     }
10193:                 }
10194:             } else {
10195:                 $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);
10196:             }
10197:         } else {
10198:             $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);
10199:         }
10200:         if ($error) {
10201:             &Apache::lonnet::logthis($error);
10202:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10203:         }
10204:     }
10205: 
10206:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
10207:     if (ref($domconfig{'login'}) eq 'HASH') {
10208:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
10209:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
10210:                 if ($domservers{$lonhost}) {
10211:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
10212:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
10213:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
10214:                     }
10215:                 }
10216:             }
10217:         }
10218:     }
10219:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
10220:     foreach my $lonhost (sort(keys(%domservers))) {
10221:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
10222:             $changes{'headtag'}{$lonhost} = 1;
10223:         } else {
10224:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
10225:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
10226:             }
10227:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
10228:                 push(@newhosts,$lonhost);
10229:             } elsif ($currheadtagurls{$lonhost}) {
10230:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
10231:                 if ($currexempt{$lonhost}) {
10232:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
10233:                         $changes{'headtag'}{$lonhost} = 1;
10234:                     }
10235:                 } elsif ($possexempt{$lonhost}) {
10236:                     $changes{'headtag'}{$lonhost} = 1;
10237:                 }
10238:                 if ($possexempt{$lonhost}) {
10239:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
10240:                 }
10241:             }
10242:         }
10243:     }
10244:     if (@newhosts) {
10245:         my $error;
10246:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
10247:         if ($configuserok eq 'ok') {
10248:             if ($switchserver) {
10249:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
10250:             } elsif ($author_ok eq 'ok') {
10251:                 foreach my $lonhost (@newhosts) {
10252:                     my $formelem = 'loginheadtag_'.$lonhost;
10253:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
10254:                                                                           "login/headtag/$lonhost",'','',
10255:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
10256:                     if ($result eq 'ok') {
10257:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
10258:                         $changes{'headtag'}{$lonhost} = 1;
10259:                         if ($possexempt{$lonhost}) {
10260:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
10261:                         }
10262:                     } else {
10263:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
10264:                                            $newheadtagurls{$lonhost},$result);
10265:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
10266:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
10267:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
10268:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
10269:                         }
10270:                     }
10271:                 }
10272:             } else {
10273:                 $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);
10274:             }
10275:         } else {
10276:             $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);
10277:         }
10278:         if ($error) {
10279:             &Apache::lonnet::logthis($error);
10280:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10281:         }
10282:     }
10283:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
10284: 
10285:     my $defaulthelpfile = '/adm/loginproblems.html';
10286:     my $defaulttext = &mt('Default in use');
10287: 
10288:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
10289:                                              $dom);
10290:     if ($putresult eq 'ok') {
10291:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
10292:         my %defaultchecked = (
10293:                     'coursecatalog' => 'on',
10294:                     'helpdesk'      => 'on',
10295:                     'adminmail'     => 'off',
10296:                     'newuser'       => 'off',
10297:         );
10298:         if (ref($domconfig{'login'}) eq 'HASH') {
10299:             foreach my $item (@toggles) {
10300:                 if ($defaultchecked{$item} eq 'on') { 
10301:                     if (($domconfig{'login'}{$item} eq '0') &&
10302:                         ($env{'form.'.$item} eq '1')) {
10303:                         $changes{$item} = 1;
10304:                     } elsif (($domconfig{'login'}{$item} eq '' ||
10305:                               $domconfig{'login'}{$item} eq '1') &&
10306:                              ($env{'form.'.$item} eq '0')) {
10307:                         $changes{$item} = 1;
10308:                     }
10309:                 } elsif ($defaultchecked{$item} eq 'off') {
10310:                     if (($domconfig{'login'}{$item} eq '1') &&
10311:                         ($env{'form.'.$item} eq '0')) {
10312:                         $changes{$item} = 1;
10313:                     } elsif (($domconfig{'login'}{$item} eq '' ||
10314:                               $domconfig{'login'}{$item} eq '0') &&
10315:                              ($env{'form.'.$item} eq '1')) {
10316:                         $changes{$item} = 1;
10317:                     }
10318:                 }
10319:             }
10320:         }
10321:         if (keys(%changes) > 0 || $colchgtext) {
10322:             &Apache::loncommon::devalidate_domconfig_cache($dom);
10323:             if (ref($lastactref) eq 'HASH') {
10324:                 $lastactref->{'domainconfig'} = 1;
10325:             }
10326:             $resulttext = &mt('Changes made:').'<ul>';
10327:             foreach my $item (sort(keys(%changes))) {
10328:                 if ($item eq 'loginvia') {
10329:                     if (ref($changes{$item}) eq 'HASH') {
10330:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
10331:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
10332:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
10333:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
10334:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
10335:                                     $protocol = 'http' if ($protocol ne 'https');
10336:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
10337: 
10338:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
10339:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
10340:                                     } else {
10341:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
10342:                                     }
10343:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
10344:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
10345:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
10346:                                     }
10347:                                     $resulttext .= '</li>';
10348:                                 } else {
10349:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
10350:                                 }
10351:                             } else {
10352:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
10353:                             }
10354:                         }
10355:                         $resulttext .= '</ul></li>';
10356:                     }
10357:                 } elsif ($item eq 'helpurl') {
10358:                     if (ref($changes{$item}) eq 'HASH') {
10359:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
10360:                             if (grep(/^\Q$lang\E$/,@delurls)) {
10361:                                 my ($chg,$link);
10362:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
10363:                                 if ($lang eq 'nolang') {
10364:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
10365:                                 } else {
10366:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
10367:                                 }
10368:                                 $resulttext .= '<li>'.$chg.'</li>';
10369:                             } else {
10370:                                 my $chg;
10371:                                 if ($lang eq 'nolang') {
10372:                                     $chg = &mt('custom log-in help file for no preferred language');
10373:                                 } else {
10374:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
10375:                                 }
10376:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
10377:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
10378:                                                       '?inhibitmenu=yes',$chg,600,500).
10379:                                                '</li>';
10380:                             }
10381:                         }
10382:                     }
10383:                 } elsif ($item eq 'headtag') {
10384:                     if (ref($changes{$item}) eq 'HASH') {
10385:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
10386:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
10387:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
10388:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
10389:                                 $resulttext .= '<li><a href="'.
10390:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
10391:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
10392:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
10393:                                 if ($possexempt{$lonhost}) {
10394:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
10395:                                 } else {
10396:                                     $resulttext .= &mt('included for any client IP');
10397:                                 }
10398:                                 $resulttext .= '</li>';
10399:                             }
10400:                         }
10401:                     }
10402:                 } elsif ($item eq 'captcha') {
10403:                     if (ref($loginhash{'login'}) eq 'HASH') {
10404:                         my $chgtxt;
10405:                         if ($loginhash{'login'}{$item} eq 'notused') {
10406:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
10407:                         } else {
10408:                             my %captchas = &captcha_phrases();
10409:                             if ($captchas{$loginhash{'login'}{$item}}) {
10410:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
10411:                             } else {
10412:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
10413:                             }
10414:                         }
10415:                         $resulttext .= '<li>'.$chgtxt.'</li>';
10416:                     }
10417:                 } elsif ($item eq 'recaptchakeys') {
10418:                     if (ref($loginhash{'login'}) eq 'HASH') {
10419:                         my ($privkey,$pubkey);
10420:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
10421:                             $pubkey = $loginhash{'login'}{$item}{'public'};
10422:                             $privkey = $loginhash{'login'}{$item}{'private'};
10423:                         }
10424:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
10425:                         if (!$pubkey) {
10426:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
10427:                         } else {
10428:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
10429:                         }
10430:                         if (!$privkey) {
10431:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
10432:                         } else {
10433:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
10434:                         }
10435:                         $chgtxt .= '</ul>';
10436:                         $resulttext .= '<li>'.$chgtxt.'</li>';
10437:                     }
10438:                 } elsif ($item eq 'recaptchaversion') {
10439:                     if (ref($loginhash{'login'}) eq 'HASH') {
10440:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
10441:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
10442:                                            '</li>';
10443:                         }
10444:                     }
10445:                 } else {
10446:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
10447:                 }
10448:             }
10449:             $resulttext .= $colchgtext.'</ul>';
10450:         } else {
10451:             $resulttext = &mt('No changes made to log-in page settings');
10452:         }
10453:     } else {
10454:         $resulttext = '<span class="LC_error">'.
10455: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
10456:     }
10457:     if ($errors) {
10458:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
10459:                        $errors.'</ul>';
10460:     }
10461:     return $resulttext;
10462: }
10463: 
10464: sub check_exempt_addresses {
10465:     my ($iplist) = @_;
10466:     $iplist =~ s/^\s+//;
10467:     $iplist =~ s/\s+$//;
10468:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
10469:     my (@okips,$new);
10470:     foreach my $ip (@poss_ips) {
10471:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
10472:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
10473:                 push(@okips,$ip);
10474:             }
10475:         }
10476:     }
10477:     if (@okips > 0) {
10478:         $new = join(',',@okips);
10479:     } else {
10480:         $new = '';
10481:     }
10482:     return $new;
10483: }
10484: 
10485: sub color_font_choices {
10486:     my %choices =
10487:         &Apache::lonlocal::texthash (
10488:             img => "Header",
10489:             bgs => "Background colors",
10490:             links => "Link colors",
10491:             images => "Images",
10492:             font => "Font color",
10493:             fontmenu => "Font menu",
10494:             pgbg => "Page",
10495:             tabbg => "Header",
10496:             sidebg => "Border",
10497:             link => "Link",
10498:             alink => "Active link",
10499:             vlink => "Visited link",
10500:         );
10501:     return %choices;
10502: }
10503: 
10504: sub modify_rolecolors {
10505:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
10506:     my ($resulttext,%rolehash);
10507:     $rolehash{'rolecolors'} = {};
10508:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
10509:         if ($domconfig{'rolecolors'} eq '') {
10510:             $domconfig{'rolecolors'} = {};
10511:         }
10512:     }
10513:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
10514:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
10515:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
10516:                                              $dom);
10517:     if ($putresult eq 'ok') {
10518:         if (keys(%changes) > 0) {
10519:             &Apache::loncommon::devalidate_domconfig_cache($dom);
10520:             if (ref($lastactref) eq 'HASH') {
10521:                 $lastactref->{'domainconfig'} = 1;
10522:             }
10523:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
10524:                                              $rolehash{'rolecolors'});
10525:         } else {
10526:             $resulttext = &mt('No changes made to default color schemes');
10527:         }
10528:     } else {
10529:         $resulttext = '<span class="LC_error">'.
10530: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
10531:     }
10532:     if ($errors) {
10533:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
10534:                        $errors.'</ul>';
10535:     }
10536:     return $resulttext;
10537: }
10538: 
10539: sub modify_colors {
10540:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
10541:     my (%changes,%choices);
10542:     my @bgs;
10543:     my @links = ('link','alink','vlink');
10544:     my @logintext;
10545:     my @images;
10546:     my $servadm = $r->dir_config('lonAdmEMail');
10547:     my $errors;
10548:     my %defaults;
10549:     foreach my $role (@{$roles}) {
10550:         if ($role eq 'login') {
10551:             %choices = &login_choices();
10552:             @logintext = ('textcol','bgcol');
10553:         } else {
10554:             %choices = &color_font_choices();
10555:         }
10556:         if ($role eq 'login') {
10557:             @images = ('img','logo','domlogo','login');
10558:             @bgs = ('pgbg','mainbg','sidebg');
10559:         } else {
10560:             @images = ('img');
10561:             @bgs = ('pgbg','tabbg','sidebg');
10562:         }
10563:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
10564:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
10565:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
10566:         }
10567:         if ($role eq 'login') {
10568:             foreach my $item (@logintext) {
10569:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10570:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10571:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10572:                 }
10573:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
10574:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10575:                 }
10576:             }
10577:         } else {
10578:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
10579:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
10580:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
10581:             }
10582:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
10583:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
10584:             }
10585:         }
10586:         foreach my $item (@bgs) {
10587:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10588:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10589:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10590:             }
10591:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
10592:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10593:             }
10594:         }
10595:         foreach my $item (@links) {
10596:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
10597:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
10598:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
10599:             }
10600:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
10601:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
10602:             }
10603:         }
10604:         my ($configuserok,$author_ok,$switchserver) = 
10605:             &config_check($dom,$confname,$servadm);
10606:         my ($width,$height) = &thumb_dimensions();
10607:         if (ref($domconfig->{$role}) ne 'HASH') {
10608:             $domconfig->{$role} = {};
10609:         }
10610:         foreach my $img (@images) {
10611:             if (($role eq 'login') && (($img eq 'img') || ($img eq 'logo'))) {  
10612:                 if (defined($env{'form.login_showlogo_'.$img})) {
10613:                     $confhash->{$role}{'showlogo'}{$img} = 1;
10614:                 } else { 
10615:                     $confhash->{$role}{'showlogo'}{$img} = 0;
10616:                 }
10617:             } 
10618: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
10619: 		 && !defined($domconfig->{$role}{$img})
10620: 		 && !$env{'form.'.$role.'_del_'.$img}
10621: 		 && $env{'form.'.$role.'_import_'.$img}) {
10622: 		# import the old configured image from the .tab setting
10623: 		# if they haven't provided a new one 
10624: 		$domconfig->{$role}{$img} = 
10625: 		    $env{'form.'.$role.'_import_'.$img};
10626: 	    }
10627:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
10628:                 my $error;
10629:                 if ($configuserok eq 'ok') {
10630:                     if ($switchserver) {
10631:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
10632:                     } else {
10633:                         if ($author_ok eq 'ok') {
10634:                             my ($result,$logourl) = 
10635:                                 &publishlogo($r,'upload',$role.'_'.$img,
10636:                                            $dom,$confname,$img,$width,$height);
10637:                             if ($result eq 'ok') {
10638:                                 $confhash->{$role}{$img} = $logourl;
10639:                                 $changes{$role}{'images'}{$img} = 1;
10640:                             } else {
10641:                                 $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);
10642:                             }
10643:                         } else {
10644:                             $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);
10645:                         }
10646:                     }
10647:                 } else {
10648:                     $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);
10649:                 }
10650:                 if ($error) {
10651:                     &Apache::lonnet::logthis($error);
10652:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
10653:                 }
10654:             } elsif ($domconfig->{$role}{$img} ne '') {
10655:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
10656:                     my $error;
10657:                     if ($configuserok eq 'ok') {
10658: # is confname an author?
10659:                         if ($switchserver eq '') {
10660:                             if ($author_ok eq 'ok') {
10661:                                 my ($result,$logourl) = 
10662:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
10663:                                             $dom,$confname,$img,$width,$height);
10664:                                 if ($result eq 'ok') {
10665:                                     $confhash->{$role}{$img} = $logourl;
10666: 				    $changes{$role}{'images'}{$img} = 1;
10667:                                 }
10668:                             }
10669:                         }
10670:                     }
10671:                 }
10672:             }
10673:         }
10674:         if (ref($domconfig) eq 'HASH') {
10675:             if (ref($domconfig->{$role}) eq 'HASH') {
10676:                 foreach my $img (@images) {
10677:                     if ($domconfig->{$role}{$img} ne '') {
10678:                         if ($env{'form.'.$role.'_del_'.$img}) {
10679:                             $confhash->{$role}{$img} = '';
10680:                             $changes{$role}{'images'}{$img} = 1;
10681:                         } else {
10682:                             if ($confhash->{$role}{$img} eq '') {
10683:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
10684:                             }
10685:                         }
10686:                     } else {
10687:                         if ($env{'form.'.$role.'_del_'.$img}) {
10688:                             $confhash->{$role}{$img} = '';
10689:                             $changes{$role}{'images'}{$img} = 1;
10690:                         } 
10691:                     }
10692:                     if (($role eq 'login') && (($img eq 'logo') || ($img eq 'img'))) {
10693:                         if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
10694:                             if ($confhash->{$role}{'showlogo'}{$img} ne 
10695:                                 $domconfig->{$role}{'showlogo'}{$img}) {
10696:                                 $changes{$role}{'showlogo'}{$img} = 1; 
10697:                             }
10698:                         } else {
10699:                             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
10700:                                 $changes{$role}{'showlogo'}{$img} = 1;
10701:                             }
10702:                         }
10703:                     }
10704:                 }
10705:                 if ($domconfig->{$role}{'font'} ne '') {
10706:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
10707:                         $changes{$role}{'font'} = 1;
10708:                     }
10709:                 } else {
10710:                     if ($confhash->{$role}{'font'}) {
10711:                         $changes{$role}{'font'} = 1;
10712:                     }
10713:                 }
10714:                 if ($role ne 'login') {
10715:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
10716:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
10717:                             $changes{$role}{'fontmenu'} = 1;
10718:                         }
10719:                     } else {
10720:                         if ($confhash->{$role}{'fontmenu'}) {
10721:                             $changes{$role}{'fontmenu'} = 1;
10722:                         }
10723:                     }
10724:                 }
10725:                 foreach my $item (@bgs) {
10726:                     if ($domconfig->{$role}{$item} ne '') {
10727:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
10728:                             $changes{$role}{'bgs'}{$item} = 1;
10729:                         } 
10730:                     } else {
10731:                         if ($confhash->{$role}{$item}) {
10732:                             $changes{$role}{'bgs'}{$item} = 1;
10733:                         }
10734:                     }
10735:                 }
10736:                 foreach my $item (@links) {
10737:                     if ($domconfig->{$role}{$item} ne '') {
10738:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
10739:                             $changes{$role}{'links'}{$item} = 1;
10740:                         }
10741:                     } else {
10742:                         if ($confhash->{$role}{$item}) {
10743:                             $changes{$role}{'links'}{$item} = 1;
10744:                         }
10745:                     }
10746:                 }
10747:                 foreach my $item (@logintext) {
10748:                     if ($domconfig->{$role}{$item} ne '') {
10749:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
10750:                             $changes{$role}{'logintext'}{$item} = 1;
10751:                         }
10752:                     } else {
10753:                         if ($confhash->{$role}{$item}) {
10754:                             $changes{$role}{'logintext'}{$item} = 1;
10755:                         }
10756:                     }
10757:                 }
10758:             } else {
10759:                 &default_change_checker($role,\@images,\@links,\@bgs,
10760:                                         \@logintext,$confhash,\%changes); 
10761:             }
10762:         } else {
10763:             &default_change_checker($role,\@images,\@links,\@bgs,
10764:                                     \@logintext,$confhash,\%changes); 
10765:         }
10766:     }
10767:     return ($errors,%changes);
10768: }
10769: 
10770: sub config_check {
10771:     my ($dom,$confname,$servadm) = @_;
10772:     my ($configuserok,$author_ok,$switchserver,%currroles);
10773:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
10774:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
10775:                                                    $confname,$servadm);
10776:     if ($configuserok eq 'ok') {
10777:         $switchserver = &check_switchserver($dom,$confname);
10778:         if ($switchserver eq '') {
10779:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
10780:         }
10781:     }
10782:     return ($configuserok,$author_ok,$switchserver);
10783: }
10784: 
10785: sub default_change_checker {
10786:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
10787:     foreach my $item (@{$links}) {
10788:         if ($confhash->{$role}{$item}) {
10789:             $changes->{$role}{'links'}{$item} = 1;
10790:         }
10791:     }
10792:     foreach my $item (@{$bgs}) {
10793:         if ($confhash->{$role}{$item}) {
10794:             $changes->{$role}{'bgs'}{$item} = 1;
10795:         }
10796:     }
10797:     foreach my $item (@{$logintext}) {
10798:         if ($confhash->{$role}{$item}) {
10799:             $changes->{$role}{'logintext'}{$item} = 1;
10800:         }
10801:     }
10802:     foreach my $img (@{$images}) {
10803:         if ($env{'form.'.$role.'_del_'.$img}) {
10804:             $confhash->{$role}{$img} = '';
10805:             $changes->{$role}{'images'}{$img} = 1;
10806:         }
10807:         if ($role eq 'login') {
10808:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
10809:                 $changes->{$role}{'showlogo'}{$img} = 1;
10810:             }
10811:         }
10812:     }
10813:     if ($confhash->{$role}{'font'}) {
10814:         $changes->{$role}{'font'} = 1;
10815:     }
10816: }
10817: 
10818: sub display_colorchgs {
10819:     my ($dom,$changes,$roles,$confhash) = @_;
10820:     my (%choices,$resulttext);
10821:     if (!grep(/^login$/,@{$roles})) {
10822:         $resulttext = &mt('Changes made:').'<br />';
10823:     }
10824:     foreach my $role (@{$roles}) {
10825:         if ($role eq 'login') {
10826:             %choices = &login_choices();
10827:         } else {
10828:             %choices = &color_font_choices();
10829:         }
10830:         if (ref($changes->{$role}) eq 'HASH') {
10831:             if ($role ne 'login') {
10832:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
10833:             }
10834:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
10835:                 if ($role ne 'login') {
10836:                     $resulttext .= '<ul>';
10837:                 }
10838:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
10839:                     if ($role ne 'login') {
10840:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
10841:                     }
10842:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
10843:                         if (($role eq 'login') && ($key eq 'showlogo')) {
10844:                             if ($confhash->{$role}{$key}{$item}) {
10845:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
10846:                             } else {
10847:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
10848:                             }
10849:                         } elsif ($confhash->{$role}{$item} eq '') {
10850:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
10851:                         } else {
10852:                             my $newitem = $confhash->{$role}{$item};
10853:                             if ($key eq 'images') {
10854:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" style="vertical-align: bottom" />';
10855:                             }
10856:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
10857:                         }
10858:                     }
10859:                     if ($role ne 'login') {
10860:                         $resulttext .= '</ul></li>';
10861:                     }
10862:                 } else {
10863:                     if ($confhash->{$role}{$key} eq '') {
10864:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
10865:                     } else {
10866:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
10867:                     }
10868:                 }
10869:                 if ($role ne 'login') {
10870:                     $resulttext .= '</ul>';
10871:                 }
10872:             }
10873:         }
10874:     }
10875:     return $resulttext;
10876: }
10877: 
10878: sub thumb_dimensions {
10879:     return ('200','50');
10880: }
10881: 
10882: sub check_dimensions {
10883:     my ($inputfile) = @_;
10884:     my ($fullwidth,$fullheight);
10885:     if ($inputfile =~ m|^[/\w.\-]+$|) {
10886:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
10887:             my $imageinfo = <PIPE>;
10888:             if (!close(PIPE)) {
10889:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
10890:             }
10891:             chomp($imageinfo);
10892:             my ($fullsize) = 
10893:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
10894:             if ($fullsize) {
10895:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
10896:             }
10897:         }
10898:     }
10899:     return ($fullwidth,$fullheight);
10900: }
10901: 
10902: sub check_configuser {
10903:     my ($uhome,$dom,$confname,$servadm) = @_;
10904:     my ($configuserok,%currroles);
10905:     if ($uhome eq 'no_host') {
10906:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
10907:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
10908:         $configuserok = 
10909:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
10910:                              $configpass,'','','','','',undef,$servadm);
10911:     } else {
10912:         $configuserok = 'ok';
10913:         %currroles = 
10914:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
10915:     }
10916:     return ($configuserok,%currroles);
10917: }
10918: 
10919: sub check_authorstatus {
10920:     my ($dom,$confname,%currroles) = @_;
10921:     my $author_ok;
10922:     if (!$currroles{':'.$dom.':au'}) {
10923:         my $start = time;
10924:         my $end = 0;
10925:         $author_ok = 
10926:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
10927:                                         'au',$end,$start,'','','domconfig');
10928:     } else {
10929:         $author_ok = 'ok';
10930:     }
10931:     return $author_ok;
10932: }
10933: 
10934: sub publishlogo {
10935:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
10936:     my ($output,$fname,$logourl,$madethumb);
10937:     if ($action eq 'upload') {
10938:         $fname=$env{'form.'.$formname.'.filename'};
10939:         chop($env{'form.'.$formname});
10940:     } else {
10941:         ($fname) = ($formname =~ /([^\/]+)$/);
10942:     }
10943:     if ($savefileas ne '') {
10944:         $fname = $savefileas;
10945:     }
10946:     $fname=&Apache::lonnet::clean_filename($fname);
10947: # See if there is anything left
10948:     unless ($fname) { return ('error: no uploaded file'); }
10949:     $fname="$subdir/$fname";
10950:     my $docroot=$r->dir_config('lonDocRoot');
10951:     my $filepath="$docroot/priv";
10952:     my $relpath = "$dom/$confname";
10953:     my ($fnamepath,$file,$fetchthumb);
10954:     $file=$fname;
10955:     if ($fname=~m|/|) {
10956:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
10957:     }
10958:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
10959:     my $count;
10960:     for ($count=5;$count<=$#parts;$count++) {
10961:         $filepath.="/$parts[$count]";
10962:         if ((-e $filepath)!=1) {
10963:             mkdir($filepath,02770);
10964:         }
10965:     }
10966:     # Check for bad extension and disallow upload
10967:     if ($file=~/\.(\w+)$/ &&
10968:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10969:         $output = 
10970:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
10971:     } elsif ($file=~/\.(\w+)$/ &&
10972:         !defined(&Apache::loncommon::fileembstyle($1))) {
10973:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
10974:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
10975:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
10976:     } elsif (-d "$filepath/$file") {
10977:         $output = &mt('Filename is a directory name - rename the file and re-upload');
10978:     } else {
10979:         my $source = $filepath.'/'.$file;
10980:         my $logfile;
10981:         if (!open($logfile,">>",$source.'.log')) {
10982:             return (&mt('No write permission to Authoring Space'));
10983:         }
10984:         print $logfile
10985: "\n================= Publish ".localtime()." ================\n".
10986: $env{'user.name'}.':'.$env{'user.domain'}."\n";
10987: # Save the file
10988:         if (!open(FH,">",$source)) {
10989:             &Apache::lonnet::logthis('Failed to create '.$source);
10990:             return (&mt('Failed to create file'));
10991:         }
10992:         if ($action eq 'upload') {
10993:             if (!print FH ($env{'form.'.$formname})) {
10994:                 &Apache::lonnet::logthis('Failed to write to '.$source);
10995:                 return (&mt('Failed to write file'));
10996:             }
10997:         } else {
10998:             my $original = &Apache::lonnet::filelocation('',$formname);
10999:             if(!copy($original,$source)) {
11000:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
11001:                 return (&mt('Failed to write file'));
11002:             }
11003:         }
11004:         close(FH);
11005:         chmod(0660, $source); # Permissions to rw-rw---.
11006: 
11007:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
11008:         my $copyfile=$targetdir.'/'.$file;
11009: 
11010:         my @parts=split(/\//,$targetdir);
11011:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
11012:         for (my $count=5;$count<=$#parts;$count++) {
11013:             $path.="/$parts[$count]";
11014:             if (!-e $path) {
11015:                 print $logfile "\nCreating directory ".$path;
11016:                 mkdir($path,02770);
11017:             }
11018:         }
11019:         my $versionresult;
11020:         if (-e $copyfile) {
11021:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
11022:         } else {
11023:             $versionresult = 'ok';
11024:         }
11025:         if ($versionresult eq 'ok') {
11026:             if (copy($source,$copyfile)) {
11027:                 print $logfile "\nCopied original source to ".$copyfile."\n";
11028:                 $output = 'ok';
11029:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
11030:                 push(@{$modified_urls},[$copyfile,$source]);
11031:                 my $metaoutput = 
11032:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
11033:                 unless ($registered_cleanup) {
11034:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
11035:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
11036:                     $registered_cleanup=1;
11037:                 }
11038:             } else {
11039:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
11040:                 $output = &mt('Failed to copy file to RES space').", $!";
11041:             }
11042:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
11043:                 my $inputfile = $filepath.'/'.$file;
11044:                 my $outfile = $filepath.'/'.'tn-'.$file;
11045:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
11046:                 if ($fullwidth ne '' && $fullheight ne '') { 
11047:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
11048:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
11049:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
11050:                         system({$args[0]} @args);
11051:                         chmod(0660, $filepath.'/tn-'.$file);
11052:                         if (-e $outfile) {
11053:                             my $copyfile=$targetdir.'/tn-'.$file;
11054:                             if (copy($outfile,$copyfile)) {
11055:                                 print $logfile "\nCopied source to ".$copyfile."\n";
11056:                                 my $thumb_metaoutput = 
11057:                                     &write_metadata($dom,$confname,$formname,
11058:                                                     $targetdir,'tn-'.$file,$logfile);
11059:                                 push(@{$modified_urls},[$copyfile,$outfile]);
11060:                                 unless ($registered_cleanup) {
11061:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
11062:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
11063:                                     $registered_cleanup=1;
11064:                                 }
11065:                                 $madethumb = 1;
11066:                             } else {
11067:                                 print $logfile "\nUnable to write ".$copyfile.
11068:                                                ':'.$!."\n";
11069:                             }
11070:                         }
11071:                     }
11072:                 }
11073:             }
11074:         } else {
11075:             $output = $versionresult;
11076:         }
11077:     }
11078:     return ($output,$logourl,$madethumb);
11079: }
11080: 
11081: sub logo_versioning {
11082:     my ($targetdir,$file,$logfile) = @_;
11083:     my $target = $targetdir.'/'.$file;
11084:     my ($maxversion,$fn,$extn,$output);
11085:     $maxversion = 0;
11086:     if ($file =~ /^(.+)\.(\w+)$/) {
11087:         $fn=$1;
11088:         $extn=$2;
11089:     }
11090:     opendir(DIR,$targetdir);
11091:     while (my $filename=readdir(DIR)) {
11092:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
11093:             $maxversion=($1>$maxversion)?$1:$maxversion;
11094:         }
11095:     }
11096:     $maxversion++;
11097:     print $logfile "\nCreating old version ".$maxversion."\n";
11098:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
11099:     if (copy($target,$copyfile)) {
11100:         print $logfile "Copied old target to ".$copyfile."\n";
11101:         $copyfile=$copyfile.'.meta';
11102:         if (copy($target.'.meta',$copyfile)) {
11103:             print $logfile "Copied old target metadata to ".$copyfile."\n";
11104:             $output = 'ok';
11105:         } else {
11106:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
11107:             $output = &mt('Failed to copy old meta').", $!, ";
11108:         }
11109:     } else {
11110:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
11111:         $output = &mt('Failed to copy old target').", $!, ";
11112:     }
11113:     return $output;
11114: }
11115: 
11116: sub write_metadata {
11117:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
11118:     my (%metadatafields,%metadatakeys,$output);
11119:     $metadatafields{'title'}=$formname;
11120:     $metadatafields{'creationdate'}=time;
11121:     $metadatafields{'lastrevisiondate'}=time;
11122:     $metadatafields{'copyright'}='public';
11123:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
11124:                                          $env{'user.domain'};
11125:     $metadatafields{'authorspace'}=$confname.':'.$dom;
11126:     $metadatafields{'domain'}=$dom;
11127:     {
11128:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
11129:         my $mfh;
11130:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
11131:             foreach (sort(keys(%metadatafields))) {
11132:                 unless ($_=~/\./) {
11133:                     my $unikey=$_;
11134:                     $unikey=~/^([A-Za-z]+)/;
11135:                     my $tag=$1;
11136:                     $tag=~tr/A-Z/a-z/;
11137:                     print $mfh "\n\<$tag";
11138:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
11139:                         my $value=$metadatafields{$unikey.'.'.$_};
11140:                         $value=~s/\"/\'\'/g;
11141:                         print $mfh ' '.$_.'="'.$value.'"';
11142:                     }
11143:                     print $mfh '>'.
11144:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
11145:                             .'</'.$tag.'>';
11146:                 }
11147:             }
11148:             $output = 'ok';
11149:             print $logfile "\nWrote metadata";
11150:             close($mfh);
11151:         } else {
11152:             print $logfile "\nFailed to open metadata file";
11153:             $output = &mt('Could not write metadata');
11154:         }
11155:     }
11156:     return $output;
11157: }
11158: 
11159: sub notifysubscribed {
11160:     foreach my $targetsource (@{$modified_urls}){
11161:         next unless (ref($targetsource) eq 'ARRAY');
11162:         my ($target,$source)=@{$targetsource};
11163:         if ($source ne '') {
11164:             if (open(my $logfh,">>",$source.'.log')) {
11165:                 print $logfh "\nCleanup phase: Notifications\n";
11166:                 my @subscribed=&subscribed_hosts($target);
11167:                 foreach my $subhost (@subscribed) {
11168:                     print $logfh "\nNotifying host ".$subhost.':';
11169:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
11170:                     print $logfh $reply;
11171:                 }
11172:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
11173:                 foreach my $subhost (@subscribedmeta) {
11174:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
11175:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
11176:                                                         $subhost);
11177:                     print $logfh $reply;
11178:                 }
11179:                 print $logfh "\n============ Done ============\n";
11180:                 close($logfh);
11181:             }
11182:         }
11183:     }
11184:     return OK;
11185: }
11186: 
11187: sub subscribed_hosts {
11188:     my ($target) = @_;
11189:     my @subscribed;
11190:     if (open(my $fh,"<","$target.subscription")) {
11191:         while (my $subline=<$fh>) {
11192:             if ($subline =~ /^($match_lonid):/) {
11193:                 my $host = $1;
11194:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
11195:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
11196:                         push(@subscribed,$host);
11197:                     }
11198:                 }
11199:             }
11200:         }
11201:     }
11202:     return @subscribed;
11203: }
11204: 
11205: sub check_switchserver {
11206:     my ($dom,$confname) = @_;
11207:     my ($allowed,$switchserver);
11208:     my $home = &Apache::lonnet::homeserver($confname,$dom);
11209:     if ($home eq 'no_host') {
11210:         $home = &Apache::lonnet::domain($dom,'primary');
11211:     }
11212:     my @ids=&Apache::lonnet::current_machine_ids();
11213:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
11214:     if (!$allowed) {
11215: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
11216:     }
11217:     return $switchserver;
11218: }
11219: 
11220: sub modify_quotas {
11221:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
11222:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
11223:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
11224:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
11225:         $validationfieldsref);
11226:     if ($action eq 'quotas') {
11227:         $context = 'tools'; 
11228:     } else {
11229:         $context = $action;
11230:     }
11231:     if ($context eq 'requestcourses') {
11232:         @usertools = ('official','unofficial','community','textbook','placement','lti');
11233:         @options =('norequest','approval','validate','autolimit');
11234:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
11235:         %titles = &courserequest_titles();
11236:         $toolregexp = join('|',@usertools);
11237:         %conditions = &courserequest_conditions();
11238:         $confname = $dom.'-domainconfig';
11239:         my $servadm = $r->dir_config('lonAdmEMail');
11240:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11241:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
11242:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
11243:     } elsif ($context eq 'requestauthor') {
11244:         @usertools = ('author');
11245:         %titles = &authorrequest_titles();
11246:     } else {
11247:         @usertools = ('aboutme','blog','webdav','portfolio');
11248:         %titles = &tool_titles();
11249:     }
11250:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
11251:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
11252:     foreach my $key (keys(%env)) {
11253:         if ($context eq 'requestcourses') {
11254:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
11255:                 my $item = $1;
11256:                 my $type = $2;
11257:                 if ($type =~ /^limit_(.+)/) {
11258:                     $limithash{$item}{$1} = $env{$key};
11259:                 } else {
11260:                     $confhash{$item}{$type} = $env{$key};
11261:                 }
11262:             }
11263:         } elsif ($context eq 'requestauthor') {
11264:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
11265:                 $confhash{$1} = $env{$key};
11266:             }
11267:         } else {
11268:             if ($key =~ /^form\.quota_(.+)$/) {
11269:                 $confhash{'defaultquota'}{$1} = $env{$key};
11270:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
11271:                 $confhash{'authorquota'}{$1} = $env{$key};
11272:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
11273:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
11274:             }
11275:         }
11276:     }
11277:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
11278:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
11279:         @approvalnotify = sort(@approvalnotify);
11280:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
11281:         my @crstypes = ('official','unofficial','community','textbook','placement','lti');
11282:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
11283:         foreach my $type (@hasuniquecode) {
11284:             if (grep(/^\Q$type\E$/,@crstypes)) {
11285:                 $confhash{'uniquecode'}{$type} = 1;
11286:             }
11287:         }
11288:         my (%newbook,%allpos);
11289:         if ($context eq 'requestcourses') {
11290:             foreach my $type ('textbooks','templates') {
11291:                 @{$allpos{$type}} = (); 
11292:                 my $invalid;
11293:                 if ($type eq 'textbooks') {
11294:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
11295:                 } else {
11296:                     $invalid = &mt('Invalid LON-CAPA course for template');
11297:                 }
11298:                 if ($env{'form.'.$type.'_addbook'}) {
11299:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
11300:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
11301:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
11302:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
11303:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
11304:                         } else {
11305:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
11306:                             my $position = $env{'form.'.$type.'_addbook_pos'};
11307:                             $position =~ s/\D+//g;
11308:                             if ($position ne '') {
11309:                                 $allpos{$type}[$position] = $newbook{$type};
11310:                             }
11311:                         }
11312:                     } else {
11313:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
11314:                     }
11315:                 }
11316:             } 
11317:         }
11318:         if (ref($domconfig{$action}) eq 'HASH') {
11319:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
11320:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
11321:                     $changes{'notify'}{'approval'} = 1;
11322:                 }
11323:             } else {
11324:                 if ($confhash{'notify'}{'approval'}) {
11325:                     $changes{'notify'}{'approval'} = 1;
11326:                 }
11327:             }
11328:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
11329:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
11330:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
11331:                         unless ($confhash{'uniquecode'}{$crstype}) {
11332:                             $changes{'uniquecode'} = 1;
11333:                         }
11334:                     }
11335:                     unless ($changes{'uniquecode'}) {
11336:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
11337:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
11338:                                 $changes{'uniquecode'} = 1;
11339:                             }
11340:                         }
11341:                     }
11342:                } else {
11343:                    $changes{'uniquecode'} = 1;
11344:                }
11345:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
11346:                 $changes{'uniquecode'} = 1;
11347:             }
11348:             if ($context eq 'requestcourses') {
11349:                 foreach my $type ('textbooks','templates') {
11350:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
11351:                         my %deletions;
11352:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
11353:                         if (@todelete) {
11354:                             map { $deletions{$_} = 1; } @todelete;
11355:                         }
11356:                         my %imgdeletions;
11357:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
11358:                         if (@todeleteimages) {
11359:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
11360:                         }
11361:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
11362:                         for (my $i=0; $i<=$maxnum; $i++) {
11363:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
11364:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
11365:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
11366:                                 if ($deletions{$key}) {
11367:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
11368:                                         #FIXME need to obsolete item in RES space
11369:                                     }
11370:                                     next;
11371:                                 } else {
11372:                                     my $newpos = $env{'form.'.$itemid};
11373:                                     $newpos =~ s/\D+//g;
11374:                                     foreach my $item ('subject','title','publisher','author') {
11375:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
11376:                                                  ($type eq 'templates'));
11377:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
11378:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
11379:                                             $changes{$type}{$key} = 1;
11380:                                         }
11381:                                     }
11382:                                     $allpos{$type}[$newpos] = $key;
11383:                                 }
11384:                                 if ($imgdeletions{$key}) {
11385:                                     $changes{$type}{$key} = 1;
11386:                                     #FIXME need to obsolete item in RES space
11387:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
11388:                                     my ($cdom,$cnum) = split(/_/,$key);
11389:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
11390:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
11391:                                     } else {
11392:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
11393:                                                                                       $cdom,$cnum,$type,$configuserok,
11394:                                                                                       $switchserver,$author_ok);
11395:                                         if ($imgurl) {
11396:                                             $confhash{$type}{$key}{'image'} = $imgurl;
11397:                                             $changes{$type}{$key} = 1; 
11398:                                         }
11399:                                         if ($error) {
11400:                                             &Apache::lonnet::logthis($error);
11401:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11402:                                         }
11403:                                     }
11404:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
11405:                                     $confhash{$type}{$key}{'image'} = 
11406:                                         $domconfig{$action}{$type}{$key}{'image'};
11407:                                 }
11408:                             }
11409:                         }
11410:                     }
11411:                 }
11412:             }
11413:         } else {
11414:             if ($confhash{'notify'}{'approval'}) {
11415:                 $changes{'notify'}{'approval'} = 1;
11416:             }
11417:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
11418:                 $changes{'uniquecode'} = 1;
11419:             }
11420:         }
11421:         if ($context eq 'requestcourses') {
11422:             foreach my $type ('textbooks','templates') {
11423:                 if ($newbook{$type}) {
11424:                     $changes{$type}{$newbook{$type}} = 1;
11425:                     foreach my $item ('subject','title','publisher','author') {
11426:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
11427:                                  ($type eq 'template'));
11428:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
11429:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
11430:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
11431:                         }
11432:                     }
11433:                     if ($type eq 'textbooks') {
11434:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
11435:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
11436:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
11437:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
11438:                             } else {
11439:                                 my ($imageurl,$error) =
11440:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
11441:                                                             $configuserok,$switchserver,$author_ok);
11442:                                 if ($imageurl) {
11443:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
11444:                                 }
11445:                                 if ($error) {
11446:                                     &Apache::lonnet::logthis($error);
11447:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11448:                                 }
11449:                             }
11450:                         }
11451:                     }
11452:                 }
11453:                 if (@{$allpos{$type}} > 0) {
11454:                     my $idx = 0;
11455:                     foreach my $item (@{$allpos{$type}}) {
11456:                         if ($item ne '') {
11457:                             $confhash{$type}{$item}{'order'} = $idx;
11458:                             if (ref($domconfig{$action}) eq 'HASH') {
11459:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
11460:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
11461:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
11462:                                             $changes{$type}{$item} = 1;
11463:                                         }
11464:                                     }
11465:                                 }
11466:                             }
11467:                             $idx ++;
11468:                         }
11469:                     }
11470:                 }
11471:             }
11472:             if (ref($validationitemsref) eq 'ARRAY') {
11473:                 foreach my $item (@{$validationitemsref}) {
11474:                     if ($item eq 'fields') {
11475:                         my @changed;
11476:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
11477:                         if (@{$confhash{'validation'}{$item}} > 0) {
11478:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
11479:                         }
11480:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11481:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11482:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
11483:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
11484:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
11485:                                 } else {
11486:                                     @changed = @{$confhash{'validation'}{$item}};
11487:                                 }
11488:                             } else {
11489:                                 @changed = @{$confhash{'validation'}{$item}};
11490:                             }
11491:                         } else {
11492:                             @changed = @{$confhash{'validation'}{$item}};
11493:                         }
11494:                         if (@changed) {
11495:                             if ($confhash{'validation'}{$item}) {
11496:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
11497:                             } else {
11498:                                 $changes{'validation'}{$item} = &mt('None');
11499:                             }
11500:                         }
11501:                     } else {
11502:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
11503:                         if ($item eq 'markup') {
11504:                             if ($env{'form.requestcourses_validation_'.$item}) {
11505:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
11506:                             }
11507:                         }
11508:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11509:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11510:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
11511:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11512:                                 }
11513:                             } else {
11514:                                 if ($confhash{'validation'}{$item} ne '') {
11515:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11516:                                 }
11517:                             }
11518:                         } else {
11519:                             if ($confhash{'validation'}{$item} ne '') {
11520:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
11521:                             }
11522:                         }
11523:                     }
11524:                 }
11525:             }
11526:             if ($env{'form.validationdc'}) {
11527:                 my $newval = $env{'form.validationdc'};
11528:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
11529:                 if (exists($domcoords{$newval})) {
11530:                     $confhash{'validation'}{'dc'} = $newval;
11531:                 }
11532:             }
11533:             if (ref($confhash{'validation'}) eq 'HASH') {
11534:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11535:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11536:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
11537:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
11538:                                 if ($confhash{'validation'}{'dc'} eq '') {
11539:                                     $changes{'validation'}{'dc'} = &mt('None');
11540:                                 } else {
11541:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11542:                                 }
11543:                             }
11544:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
11545:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11546:                         }
11547:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
11548:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11549:                     }
11550:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
11551:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
11552:                 }
11553:             } else {
11554:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
11555:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
11556:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
11557:                             $changes{'validation'}{'dc'} = &mt('None');
11558:                         }
11559:                     }
11560:                 }
11561:             }
11562:         }
11563:     } else {
11564:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
11565:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
11566:     }
11567:     foreach my $item (@usertools) {
11568:         foreach my $type (@{$types},'default','_LC_adv') {
11569:             my $unset; 
11570:             if ($context eq 'requestcourses') {
11571:                 $unset = '0';
11572:                 if ($type eq '_LC_adv') {
11573:                     $unset = '';
11574:                 }
11575:                 if ($confhash{$item}{$type} eq 'autolimit') {
11576:                     $confhash{$item}{$type} .= '=';
11577:                     unless ($limithash{$item}{$type} =~ /\D/) {
11578:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
11579:                     }
11580:                 }
11581:             } elsif ($context eq 'requestauthor') {
11582:                 $unset = '0';
11583:                 if ($type eq '_LC_adv') {
11584:                     $unset = '';
11585:                 }
11586:             } else {
11587:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
11588:                     $confhash{$item}{$type} = 1;
11589:                 } else {
11590:                     $confhash{$item}{$type} = 0;
11591:                 }
11592:             }
11593:             if (ref($domconfig{$action}) eq 'HASH') {
11594:                 if ($action eq 'requestauthor') {
11595:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
11596:                         $changes{$type} = 1;
11597:                     }
11598:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
11599:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
11600:                         $changes{$item}{$type} = 1;
11601:                     }
11602:                 } else {
11603:                     if ($context eq 'requestcourses') {
11604:                         if ($confhash{$item}{$type} ne $unset) {
11605:                             $changes{$item}{$type} = 1;
11606:                         }
11607:                     } else {
11608:                         if (!$confhash{$item}{$type}) {
11609:                             $changes{$item}{$type} = 1;
11610:                         }
11611:                     }
11612:                 }
11613:             } else {
11614:                 if ($context eq 'requestcourses') {
11615:                     if ($confhash{$item}{$type} ne $unset) {
11616:                         $changes{$item}{$type} = 1;
11617:                     }
11618:                 } elsif ($context eq 'requestauthor') {
11619:                     if ($confhash{$type} ne $unset) {
11620:                         $changes{$type} = 1;
11621:                     }
11622:                 } else {
11623:                     if (!$confhash{$item}{$type}) {
11624:                         $changes{$item}{$type} = 1;
11625:                     }
11626:                 }
11627:             }
11628:         }
11629:     }
11630:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
11631:         if (ref($domconfig{'quotas'}) eq 'HASH') {
11632:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
11633:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
11634:                     if (exists($confhash{'defaultquota'}{$key})) {
11635:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
11636:                             $changes{'defaultquota'}{$key} = 1;
11637:                         }
11638:                     } else {
11639:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
11640:                     }
11641:                 }
11642:             } else {
11643:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
11644:                     if (exists($confhash{'defaultquota'}{$key})) {
11645:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
11646:                             $changes{'defaultquota'}{$key} = 1;
11647:                         }
11648:                     } else {
11649:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
11650:                     }
11651:                 }
11652:             }
11653:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
11654:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
11655:                     if (exists($confhash{'authorquota'}{$key})) {
11656:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
11657:                             $changes{'authorquota'}{$key} = 1;
11658:                         }
11659:                     } else {
11660:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
11661:                     }
11662:                 }
11663:             }
11664:         }
11665:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
11666:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
11667:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
11668:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
11669:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
11670:                             $changes{'defaultquota'}{$key} = 1;
11671:                         }
11672:                     } else {
11673:                         if (!exists($domconfig{'quotas'}{$key})) {
11674:                             $changes{'defaultquota'}{$key} = 1;
11675:                         }
11676:                     }
11677:                 } else {
11678:                     $changes{'defaultquota'}{$key} = 1;
11679:                 }
11680:             }
11681:         }
11682:         if (ref($confhash{'authorquota'}) eq 'HASH') {
11683:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
11684:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
11685:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
11686:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
11687:                             $changes{'authorquota'}{$key} = 1;
11688:                         }
11689:                     } else {
11690:                         $changes{'authorquota'}{$key} = 1;
11691:                     }
11692:                 } else {
11693:                     $changes{'authorquota'}{$key} = 1;
11694:                 }
11695:             }
11696:         }
11697:     }
11698: 
11699:     if ($context eq 'requestauthor') {
11700:         $domdefaults{'requestauthor'} = \%confhash;
11701:     } else {
11702:         foreach my $key (keys(%confhash)) {
11703:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
11704:                 $domdefaults{$key} = $confhash{$key};
11705:             }
11706:         }
11707:     }
11708: 
11709:     my %quotahash = (
11710:                       $action => { %confhash }
11711:                     );
11712:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
11713:                                              $dom);
11714:     if ($putresult eq 'ok') {
11715:         if (keys(%changes) > 0) {
11716:             my $cachetime = 24*60*60;
11717:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
11718:             if (ref($lastactref) eq 'HASH') {
11719:                 $lastactref->{'domdefaults'} = 1;
11720:             }
11721:             $resulttext = &mt('Changes made:').'<ul>';
11722:             unless (($context eq 'requestcourses') ||
11723:                     ($context eq 'requestauthor')) {
11724:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
11725:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
11726:                     foreach my $type (@{$types},'default') {
11727:                         if (defined($changes{'defaultquota'}{$type})) {
11728:                             my $typetitle = $usertypes->{$type};
11729:                             if ($type eq 'default') {
11730:                                 $typetitle = $othertitle;
11731:                             }
11732:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
11733:                         }
11734:                     }
11735:                     $resulttext .= '</ul></li>';
11736:                 }
11737:                 if (ref($changes{'authorquota'}) eq 'HASH') {
11738:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
11739:                     foreach my $type (@{$types},'default') {
11740:                         if (defined($changes{'authorquota'}{$type})) {
11741:                             my $typetitle = $usertypes->{$type};
11742:                             if ($type eq 'default') {
11743:                                 $typetitle = $othertitle;
11744:                             }
11745:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
11746:                         }
11747:                     }
11748:                     $resulttext .= '</ul></li>';
11749:                 }
11750:             }
11751:             my %newenv;
11752:             foreach my $item (@usertools) {
11753:                 my (%haschgs,%inconf);
11754:                 if ($context eq 'requestauthor') {
11755:                     %haschgs = %changes;
11756:                     %inconf = %confhash;
11757:                 } else {
11758:                     if (ref($changes{$item}) eq 'HASH') {
11759:                         %haschgs = %{$changes{$item}};
11760:                     }
11761:                     if (ref($confhash{$item}) eq 'HASH') {
11762:                         %inconf = %{$confhash{$item}};
11763:                     }
11764:                 }
11765:                 if (keys(%haschgs) > 0) {
11766:                     my $newacc = 
11767:                         &Apache::lonnet::usertools_access($env{'user.name'},
11768:                                                           $env{'user.domain'},
11769:                                                           $item,'reload',$context);
11770:                     if (($context eq 'requestcourses') ||
11771:                         ($context eq 'requestauthor')) {
11772:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
11773:                             $newenv{'environment.canrequest.'.$item} = $newacc;
11774:                         }
11775:                     } else {
11776:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
11777:                             $newenv{'environment.availabletools.'.$item} = $newacc;
11778:                         }
11779:                     }
11780:                     unless ($context eq 'requestauthor') {
11781:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
11782:                     }
11783:                     foreach my $type (@{$types},'default','_LC_adv') {
11784:                         if ($haschgs{$type}) {
11785:                             my $typetitle = $usertypes->{$type};
11786:                             if ($type eq 'default') {
11787:                                 $typetitle = $othertitle;
11788:                             } elsif ($type eq '_LC_adv') {
11789:                                 $typetitle = 'LON-CAPA Advanced Users'; 
11790:                             }
11791:                             if ($inconf{$type}) {
11792:                                 if ($context eq 'requestcourses') {
11793:                                     my $cond;
11794:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
11795:                                         if ($1 eq '') {
11796:                                             $cond = &mt('(Automatic processing of any request).');
11797:                                         } else {
11798:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
11799:                                         }
11800:                                     } else { 
11801:                                         $cond = $conditions{$inconf{$type}};
11802:                                     }
11803:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
11804:                                 } elsif ($context eq 'requestauthor') {
11805:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
11806:                                                              $titles{$inconf{$type}},$typetitle);
11807: 
11808:                                 } else {
11809:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
11810:                                 }
11811:                             } else {
11812:                                 if ($type eq '_LC_adv') {
11813:                                     if ($inconf{$type} eq '0') {
11814:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
11815:                                     } else { 
11816:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
11817:                                     }
11818:                                 } else {
11819:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
11820:                                 }
11821:                             }
11822:                         }
11823:                     }
11824:                     unless ($context eq 'requestauthor') {
11825:                         $resulttext .= '</ul></li>';
11826:                     }
11827:                 }
11828:             }
11829:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
11830:                 if (ref($changes{'notify'}) eq 'HASH') {
11831:                     if ($changes{'notify'}{'approval'}) {
11832:                         if (ref($confhash{'notify'}) eq 'HASH') {
11833:                             if ($confhash{'notify'}{'approval'}) {
11834:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
11835:                             } else {
11836:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
11837:                             }
11838:                         }
11839:                     }
11840:                 }
11841:             }
11842:             if ($action eq 'requestcourses') {
11843:                 my @offon = ('off','on');
11844:                 if ($changes{'uniquecode'}) {
11845:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
11846:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
11847:                         $resulttext .= '<li>'.
11848:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
11849:                                        '</li>';
11850:                     } else {
11851:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
11852:                                        '</li>';
11853:                     }
11854:                 }
11855:                 foreach my $type ('textbooks','templates') {
11856:                     if (ref($changes{$type}) eq 'HASH') {
11857:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
11858:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
11859:                             my %coursehash = &Apache::lonnet::coursedescription($key);
11860:                             my $coursetitle = $coursehash{'description'};
11861:                             my $position = $confhash{$type}{$key}{'order'} + 1;
11862:                             $resulttext .= '<li>';
11863:                             foreach my $item ('subject','title','publisher','author') {
11864:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
11865:                                          ($type eq 'templates'));
11866:                                 my $name = $item.':';
11867:                                 $name =~ s/^(\w)/\U$1/;
11868:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
11869:                             }
11870:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
11871:                             if ($type eq 'textbooks') {
11872:                                 if ($confhash{$type}{$key}{'image'}) {
11873:                                     $resulttext .= ' '.&mt('Image: [_1]',
11874:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
11875:                                                    ' alt="Textbook cover" />').'<br />';
11876:                                 }
11877:                             }
11878:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
11879:                         }
11880:                         $resulttext .= '</ul></li>';
11881:                     }
11882:                 }
11883:                 if (ref($changes{'validation'}) eq 'HASH') {
11884:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
11885:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
11886:                         foreach my $item (@{$validationitemsref}) {
11887:                             if (exists($changes{'validation'}{$item})) {
11888:                                 if ($item eq 'markup') {
11889:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
11890:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
11891:                                 } else {
11892:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
11893:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
11894:                                 }
11895:                             }
11896:                         }
11897:                         if (exists($changes{'validation'}{'dc'})) {
11898:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
11899:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
11900:                         }
11901:                     }
11902:                 }
11903:             }
11904:             $resulttext .= '</ul>';
11905:             if (keys(%newenv)) {
11906:                 &Apache::lonnet::appenv(\%newenv);
11907:             }
11908:         } else {
11909:             if ($context eq 'requestcourses') {
11910:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
11911:             } elsif ($context eq 'requestauthor') {
11912:                 $resulttext = &mt('No changes made to rights to request author space.');
11913:             } else {
11914:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
11915:             }
11916:         }
11917:     } else {
11918:         $resulttext = '<span class="LC_error">'.
11919: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11920:     }
11921:     if ($errors) {
11922:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
11923:                        '<ul>'.$errors.'</ul></p>';
11924:     }
11925:     return $resulttext;
11926: }
11927: 
11928: sub process_textbook_image {
11929:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
11930:     my $filename = $env{'form.'.$caller.'.filename'};
11931:     my ($error,$url);
11932:     my ($width,$height) = (50,50);
11933:     if ($configuserok eq 'ok') {
11934:         if ($switchserver) {
11935:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
11936:                          $switchserver);
11937:         } elsif ($author_ok eq 'ok') {
11938:             my ($result,$imageurl) =
11939:                 &publishlogo($r,'upload',$caller,$dom,$confname,
11940:                              "$type/$cdom/$cnum/cover",$width,$height);
11941:             if ($result eq 'ok') {
11942:                 $url = $imageurl;
11943:             } else {
11944:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
11945:             }
11946:         } else {
11947:             $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);
11948:         }
11949:     } else {
11950:         $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);
11951:     }
11952:     return ($url,$error);
11953: }
11954: 
11955: sub modify_ltitools {
11956:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
11957:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
11958:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
11959:     my $confname = $dom.'-domainconfig';
11960:     my $servadm = $r->dir_config('lonAdmEMail');
11961:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11962:     my (%posslti,%possfield);
11963:     my @courseroles = ('cc','in','ta','ep','st');
11964:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
11965:     map { $posslti{$_} = 1; } @ltiroles;
11966:     my @allfields = ('fullname','firstname','lastname','email','user','roles');
11967:     map { $possfield{$_} = 1; } @allfields;
11968:     my %lt = &ltitools_names(); 
11969:     if ($env{'form.ltitools_add'}) {
11970:         my $title = $env{'form.ltitools_add_title'};
11971:         $title =~ s/(`)/'/g;
11972:         ($newid,my $error) = &get_ltitools_id($dom,$title);
11973:         if ($newid) {
11974:             my $position = $env{'form.ltitools_add_pos'};
11975:             $position =~ s/\D+//g;
11976:             if ($position ne '') {
11977:                 $allpos[$position] = $newid;
11978:             }
11979:             $changes{$newid} = 1;
11980:             foreach my $item ('title','url','key','secret','lifetime') {
11981:                 $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
11982:                 if ($item eq 'lifetime') {
11983:                     $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
11984:                 }
11985:                 if ($env{'form.ltitools_add_'.$item}) {
11986:                     if (($item eq 'key') || ($item eq 'secret')) {
11987:                         $encconfig{$newid}{$item} = $env{'form.ltitools_add_'.$item};
11988:                     } else {
11989:                         $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
11990:                     }
11991:                 }
11992:             }
11993:             if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
11994:                 $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
11995:             }
11996:             if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
11997:                 $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
11998:             }
11999:             if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
12000:                 $confhash{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
12001:             } else {
12002:                 $confhash{$newid}{'sigmethod'} = 'HMAC-SHA1';
12003:             }
12004:             foreach my $item ('width','height','linktext','explanation') {
12005:                 $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
12006:                 $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
12007:                 if (($item eq 'width') || ($item eq 'height')) {
12008:                     if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
12009:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
12010:                     }
12011:                 } else {
12012:                     if ($env{'form.ltitools_add_'.$item} ne '') {
12013:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item}; 
12014:                     }
12015:                 }
12016:             }
12017:             if ($env{'form.ltitools_add_target'} eq 'window') {
12018:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
12019:             } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
12020:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
12021:             } else {
12022:                 $confhash{$newid}{'display'}{'target'} = 'iframe';
12023:             }
12024:             foreach my $item ('passback','roster') {
12025:                 if ($env{'form.ltitools_'.$item.'_add'}) {
12026:                     $confhash{$newid}{$item} = 1;
12027:                     if ($env{'form.ltitools_'.$item.'valid_add'} ne '') {
12028:                         my $lifetime = $env{'form.ltitools_'.$item.'valid_add'};
12029:                         $lifetime =~ s/^\s+|\s+$//g;
12030:                         if ($lifetime =~ /^\d+\.?\d*$/) {
12031:                             $confhash{$newid}{$item.'valid'} = $lifetime;
12032:                         }
12033:                     }
12034:                 }
12035:             }
12036:             if ($env{'form.ltitools_add_image.filename'} ne '') {
12037:                 my ($imageurl,$error) =
12038:                     &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$newid,
12039:                                             $configuserok,$switchserver,$author_ok);
12040:                 if ($imageurl) {
12041:                     $confhash{$newid}{'image'} = $imageurl;
12042:                 }
12043:                 if ($error) {
12044:                     &Apache::lonnet::logthis($error);
12045:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12046:                 }
12047:             }
12048:             my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
12049:             foreach my $field (@fields) {
12050:                 if ($possfield{$field}) {
12051:                     if ($field eq 'roles') {
12052:                         foreach my $role (@courseroles) {
12053:                             my $choice = $env{'form.ltitools_add_roles_'.$role};
12054:                             if (($choice ne '') && ($posslti{$choice})) {
12055:                                 $confhash{$newid}{'roles'}{$role} = $choice;
12056:                                 if ($role eq 'cc') {
12057:                                     $confhash{$newid}{'roles'}{'co'} = $choice; 
12058:                                 }
12059:                             }
12060:                         }
12061:                     } else {
12062:                         $confhash{$newid}{'fields'}{$field} = 1;
12063:                     }
12064:                 }
12065:             }
12066:             if (ref($confhash{$newid}{'fields'}) eq 'HASH') {
12067:                 if ($confhash{$newid}{'fields'}{'user'}) {
12068:                     if ($env{'form.ltitools_userincdom_add'}) {
12069:                         $confhash{$newid}{'incdom'} = 1;
12070:                     }
12071:                 }
12072:             }
12073:             my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
12074:             foreach my $item (@courseconfig) {
12075:                 $confhash{$newid}{'crsconf'}{$item} = 1;
12076:             }
12077:             if ($env{'form.ltitools_add_custom'}) {
12078:                 my $name = $env{'form.ltitools_add_custom_name'};
12079:                 my $value = $env{'form.ltitools_add_custom_value'};
12080:                 $value =~ s/(`)/'/g;
12081:                 $name =~ s/(`)/'/g;
12082:                 $confhash{$newid}{'custom'}{$name} = $value;
12083:             }
12084:         } else {
12085:             my $error = &mt('Failed to acquire unique ID for new external tool');   
12086:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12087:         }
12088:     }
12089:     if (ref($domconfig{$action}) eq 'HASH') {
12090:         my %deletions;
12091:         my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
12092:         if (@todelete) {
12093:             map { $deletions{$_} = 1; } @todelete;
12094:         }
12095:         my %customadds;
12096:         my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
12097:         if (@newcustom) {
12098:             map { $customadds{$_} = 1; } @newcustom;
12099:         } 
12100:         my %imgdeletions;
12101:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
12102:         if (@todeleteimages) {
12103:             map { $imgdeletions{$_} = 1; } @todeleteimages;
12104:         }
12105:         my $maxnum = $env{'form.ltitools_maxnum'};
12106:         for (my $i=0; $i<=$maxnum; $i++) {
12107:             my $itemid = $env{'form.ltitools_id_'.$i};
12108:             $itemid =~ s/\D+//g;
12109:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
12110:                 if ($deletions{$itemid}) {
12111:                     if ($domconfig{$action}{$itemid}{'image'}) {
12112:                         #FIXME need to obsolete item in RES space
12113:                     }
12114:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
12115:                     next;
12116:                 } else {
12117:                     my $newpos = $env{'form.ltitools_'.$itemid};
12118:                     $newpos =~ s/\D+//g;
12119:                     foreach my $item ('title','url','lifetime') {
12120:                         $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
12121:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
12122:                             $changes{$itemid} = 1;
12123:                         }
12124:                     }
12125:                     foreach my $item ('key','secret') {
12126:                         $encconfig{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
12127:                         if ($domconfig{$action}{$itemid}{$item} ne $encconfig{$itemid}{$item}) {
12128:                             $changes{$itemid} = 1;
12129:                         }
12130:                     }
12131:                     if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
12132:                         $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
12133:                     }
12134:                     if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
12135:                         $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
12136:                     }
12137:                     if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
12138:                         $confhash{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
12139:                     } else {
12140:                         $confhash{$itemid}{'sigmethod'} = 'HMAC-SHA1'; 
12141:                     }
12142:                     if ($domconfig{$action}{$itemid}{'sigmethod'} eq '') {
12143:                         if ($confhash{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
12144:                             $changes{$itemid} = 1;
12145:                         }
12146:                     } elsif ($domconfig{$action}{$itemid}{'sigmethod'} ne $confhash{$itemid}{'sigmethod'}) {
12147:                         $changes{$itemid} = 1;
12148:                     }
12149:                     foreach my $size ('width','height') {
12150:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
12151:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
12152:                         if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
12153:                             $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
12154:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12155:                                 if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
12156:                                     $changes{$itemid} = 1;
12157:                                 }
12158:                             } else {
12159:                                 $changes{$itemid} = 1;
12160:                             }
12161:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12162:                             if ($domconfig{$action}{$itemid}{'display'}{$size} ne '') {
12163:                                 $changes{$itemid} = 1;
12164:                             }
12165:                         }
12166:                     }
12167:                     foreach my $item ('linktext','explanation') {
12168:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
12169:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
12170:                         if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
12171:                             $confhash{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
12172:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12173:                                 if ($domconfig{$action}{$itemid}{'display'}{$item} ne $confhash{$itemid}{'display'}{$item}) {
12174:                                     $changes{$itemid} = 1;
12175:                                 }
12176:                             } else {
12177:                                 $changes{$itemid} = 1;
12178:                             }
12179:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12180:                             if ($domconfig{$action}{$itemid}{'display'}{$item} ne '') {
12181:                                 $changes{$itemid} = 1;
12182:                             }
12183:                         }
12184:                     }
12185:                     if ($env{'form.ltitools_target_'.$i} eq 'window') {
12186:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
12187:                     } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
12188:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
12189:                     } else {
12190:                         $confhash{$itemid}{'display'}{'target'} = 'iframe';
12191:                     }
12192:                     if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
12193:                         if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
12194:                             $changes{$itemid} = 1;
12195:                         }
12196:                     } else {
12197:                         $changes{$itemid} = 1;
12198:                     }
12199:                     foreach my $extra ('passback','roster') {
12200:                         if ($env{'form.ltitools_'.$extra.'_'.$i}) {
12201:                             $confhash{$itemid}{$extra} = 1;
12202:                             if ($env{'form.ltitools_'.$extra.'valid_'.$i} ne '') {
12203:                                 my $lifetime = $env{'form.ltitools_'.$extra.'valid_'.$i};
12204:                                 $lifetime =~ s/^\s+|\s+$//g;
12205:                                 if ($lifetime =~ /^\d+\.?\d*$/) {
12206:                                     $confhash{$itemid}{$extra.'valid'} = $lifetime;
12207:                                 }
12208:                             }
12209:                         }
12210:                         if ($domconfig{$action}{$itemid}{$extra} ne $confhash{$itemid}{$extra}) {
12211:                             $changes{$itemid} = 1;
12212:                         }
12213:                         if ($domconfig{$action}{$itemid}{$extra.'valid'} ne $confhash{$itemid}{$extra.'valid'}) {
12214:                             $changes{$itemid} = 1;
12215:                         }
12216:                     }
12217:                     my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
12218:                     foreach my $item ('label','title','target','linktext','explanation','append') {
12219:                         if (grep(/^\Q$item\E$/,@courseconfig)) {
12220:                             $confhash{$itemid}{'crsconf'}{$item} = 1;
12221:                             if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
12222:                                 if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
12223:                                     $changes{$itemid} = 1;
12224:                                 }
12225:                             } else {
12226:                                 $changes{$itemid} = 1;
12227:                             }
12228:                         }
12229:                     }
12230:                     my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
12231:                     foreach my $field (@fields) {
12232:                         if ($possfield{$field}) {
12233:                             if ($field eq 'roles') {
12234:                                 foreach my $role (@courseroles) {
12235:                                     my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
12236:                                     if (($choice ne '') && ($posslti{$choice})) {
12237:                                         $confhash{$itemid}{'roles'}{$role} = $choice;
12238:                                         if ($role eq 'cc') {
12239:                                             $confhash{$itemid}{'roles'}{'co'} = $choice;
12240:                                         }
12241:                                     }
12242:                                     if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
12243:                                         if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
12244:                                             $changes{$itemid} = 1;
12245:                                         }
12246:                                     } elsif ($confhash{$itemid}{'roles'}{$role}) {
12247:                                         $changes{$itemid} = 1;
12248:                                     }
12249:                                 }
12250:                             } else {
12251:                                 $confhash{$itemid}{'fields'}{$field} = 1;
12252:                                 if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
12253:                                     if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
12254:                                         $changes{$itemid} = 1;
12255:                                     }
12256:                                 } else {
12257:                                     $changes{$itemid} = 1;
12258:                                 }
12259:                             }
12260:                         }
12261:                     }
12262:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
12263:                         if ($confhash{$itemid}{'fields'}{'user'}) {
12264:                             if ($env{'form.ltitools_userincdom_'.$i}) {
12265:                                 $confhash{$itemid}{'incdom'} = 1;
12266:                             }
12267:                             if ($domconfig{$action}{$itemid}{'incdom'} ne $confhash{$itemid}{'incdom'}) {
12268:                                 $changes{$itemid} = 1;
12269:                             }
12270:                         }
12271:                     }
12272:                     $allpos[$newpos] = $itemid;
12273:                 }
12274:                 if ($imgdeletions{$itemid}) {
12275:                     $changes{$itemid} = 1;
12276:                     #FIXME need to obsolete item in RES space
12277:                 } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
12278:                     my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
12279:                                                                  $itemid,$configuserok,$switchserver,
12280:                                                                  $author_ok);
12281:                     if ($imgurl) {
12282:                         $confhash{$itemid}{'image'} = $imgurl;
12283:                         $changes{$itemid} = 1;
12284:                     }
12285:                     if ($error) {
12286:                         &Apache::lonnet::logthis($error);
12287:                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12288:                     }
12289:                 } elsif ($domconfig{$action}{$itemid}{'image'}) {
12290:                     $confhash{$itemid}{'image'} =
12291:                        $domconfig{$action}{$itemid}{'image'};
12292:                 }
12293:                 if ($customadds{$i}) {
12294:                     my $name = $env{'form.ltitools_custom_name_'.$i};
12295:                     $name =~ s/(`)/'/g;
12296:                     $name =~ s/^\s+//;
12297:                     $name =~ s/\s+$//;
12298:                     my $value = $env{'form.ltitools_custom_value_'.$i};
12299:                     $value =~ s/(`)/'/g;
12300:                     $value =~ s/^\s+//;
12301:                     $value =~ s/\s+$//;
12302:                     if ($name ne '') {
12303:                         $confhash{$itemid}{'custom'}{$name} = $value;
12304:                         $changes{$itemid} = 1;
12305:                     }
12306:                 }
12307:                 my %customdels;
12308:                 my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i); 
12309:                 if (@customdeletions) {
12310:                     $changes{$itemid} = 1;
12311:                 }
12312:                 map { $customdels{$_} = 1; } @customdeletions;
12313:                 if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
12314:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
12315:                         unless ($customdels{$key}) {
12316:                             if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
12317:                                 $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i}; 
12318:                             }
12319:                             if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
12320:                                 $changes{$itemid} = 1;
12321:                             }
12322:                         }
12323:                     }
12324:                 }
12325:                 unless ($changes{$itemid}) {
12326:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
12327:                         if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
12328:                             if (ref($confhash{$itemid}{$key}) eq 'HASH') {
12329:                                 foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
12330:                                     unless (exists($confhash{$itemid}{$key}{$innerkey})) {
12331:                                         $changes{$itemid} = 1;
12332:                                         last;
12333:                                     }
12334:                                 }
12335:                             } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
12336:                                 $changes{$itemid} = 1;
12337:                             }
12338:                         }
12339:                         last if ($changes{$itemid});
12340:                     }
12341:                 }
12342:             }
12343:         }
12344:     }
12345:     if (@allpos > 0) {
12346:         my $idx = 0;
12347:         foreach my $itemid (@allpos) {
12348:             if ($itemid ne '') {
12349:                 $confhash{$itemid}{'order'} = $idx;
12350:                 if (ref($domconfig{$action}) eq 'HASH') {
12351:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
12352:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
12353:                             $changes{$itemid} = 1;
12354:                         }
12355:                     }
12356:                 }
12357:                 $idx ++;
12358:             }
12359:         }
12360:     }
12361:     my %ltitoolshash = (
12362:                           $action => { %confhash }
12363:                        );
12364:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
12365:                                              $dom);
12366:     if ($putresult eq 'ok') {
12367:         my %ltienchash = (
12368:                              $action => { %encconfig }
12369:                          );
12370:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom);
12371:         if (keys(%changes) > 0) {
12372:             my $cachetime = 24*60*60;
12373:             my %ltiall = %confhash;
12374:             foreach my $id (keys(%ltiall)) {
12375:                 if (ref($encconfig{$id}) eq 'HASH') {
12376:                     foreach my $item ('key','secret') {
12377:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
12378:                     }
12379:                 }
12380:             }
12381:             &Apache::lonnet::do_cache_new('ltitools',$dom,\%ltiall,$cachetime);
12382:             if (ref($lastactref) eq 'HASH') {
12383:                 $lastactref->{'ltitools'} = 1;
12384:             }
12385:             $resulttext = &mt('Changes made:').'<ul>';
12386:             my %bynum;
12387:             foreach my $itemid (sort(keys(%changes))) {
12388:                 my $position = $confhash{$itemid}{'order'};
12389:                 $bynum{$position} = $itemid;
12390:             }
12391:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
12392:                 my $itemid = $bynum{$pos}; 
12393:                 if (ref($confhash{$itemid}) ne 'HASH') {
12394:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
12395:                 } else {
12396:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
12397:                     if ($confhash{$itemid}{'image'}) {
12398:                         $resulttext .= '&nbsp;'.
12399:                                        '<img src="'.$confhash{$itemid}{'image'}.'"'.
12400:                                        ' alt="'.&mt('Tool Provider icon').'" />';
12401:                     }
12402:                     $resulttext .= '</li><ul>';
12403:                     my $position = $pos + 1;
12404:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
12405:                     foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
12406:                         if ($confhash{$itemid}{$item} ne '') {
12407:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
12408:                         }
12409:                     }
12410:                     if ($encconfig{$itemid}{'key'} ne '') {
12411:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
12412:                     }
12413:                     if ($encconfig{$itemid}{'secret'} ne '') {
12414:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
12415:                         my $num = length($encconfig{$itemid}{'secret'});
12416:                         $resulttext .= ('*'x$num).'</li>';
12417:                     }
12418:                     $resulttext .= '<li>'.&mt('Configurable in course:');
12419:                     my @possconfig = ('label','title','target','linktext','explanation','append');
12420:                     my $numconfig = 0; 
12421:                     if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') { 
12422:                         foreach my $item (@possconfig) {
12423:                             if ($confhash{$itemid}{'crsconf'}{$item}) {
12424:                                 $numconfig ++;
12425:                                 $resulttext .= ' "'.$lt{'crs'.$item}.'"';
12426:                             }
12427:                         }
12428:                     }
12429:                     if (!$numconfig) {
12430:                         $resulttext .= &mt('None');
12431:                     }
12432:                     $resulttext .= '</li>';
12433:                     foreach my $item ('passback','roster') {
12434:                         $resulttext .= '<li>'.$lt{$item}.'&nbsp;';
12435:                         if ($confhash{$itemid}{$item}) {
12436:                             $resulttext .= &mt('Yes');
12437:                             if ($confhash{$itemid}{$item.'valid'}) {
12438:                                 if ($item eq 'passback') {
12439:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,day] after launch',
12440:                                                            $confhash{$itemid}{$item.'valid'});
12441:                                 } else {
12442:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,second] after launch',
12443:                                                            $confhash{$itemid}{$item.'valid'});
12444:                                 }
12445:                             }
12446:                         } else {
12447:                             $resulttext .= &mt('No');
12448:                         }
12449:                         $resulttext .= '</li>';
12450:                     }
12451:                     if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
12452:                         my $displaylist;
12453:                         if ($confhash{$itemid}{'display'}{'target'}) {
12454:                             $displaylist = &mt('Display target').':&nbsp;'.
12455:                                            $confhash{$itemid}{'display'}{'target'}.',';
12456:                         }
12457:                         foreach my $size ('width','height') { 
12458:                             if ($confhash{$itemid}{'display'}{$size}) {
12459:                                 $displaylist .= ('&nbsp;'x2).$lt{$size}.':&nbsp;'.
12460:                                                 $confhash{$itemid}{'display'}{$size}.',';
12461:                             }
12462:                         }
12463:                         if ($displaylist) {
12464:                             $displaylist =~ s/,$//;
12465:                             $resulttext .= '<li>'.$displaylist.'</li>';
12466:                         }
12467:                         foreach my $item ('linktext','explanation') {
12468:                             if ($confhash{$itemid}{'display'}{$item}) {
12469:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{'display'}{$item}.'</li>';
12470:                             }
12471:                         }
12472:                     }
12473:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
12474:                         my $fieldlist;
12475:                         foreach my $field (@allfields) {
12476:                             if ($confhash{$itemid}{'fields'}{$field}) {
12477:                                 $fieldlist .= ('&nbsp;'x2).$lt{$field}.',';
12478:                             }
12479:                         }
12480:                         if ($fieldlist) {
12481:                             $fieldlist =~ s/,$//;
12482:                             if ($confhash{$itemid}{'fields'}{'user'}) {
12483:                                 if ($confhash{$itemid}{'incdom'}) {
12484:                                     $fieldlist .= ' ('.&mt('username:domain').')';
12485:                                 } else {
12486:                                     $fieldlist .= ' ('.&mt('username').')';
12487:                                 }
12488:                             }
12489:                             $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
12490:                         }
12491:                     }
12492:                     if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
12493:                         my $rolemaps;
12494:                         foreach my $role (@courseroles) {
12495:                             if ($confhash{$itemid}{'roles'}{$role}) {
12496:                                 $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
12497:                                              $confhash{$itemid}{'roles'}{$role}.',';
12498:                             }
12499:                         }
12500:                         if ($rolemaps) {
12501:                             $rolemaps =~ s/,$//; 
12502:                             $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
12503:                         }
12504:                     }
12505:                     if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
12506:                         my $customlist;
12507:                         if (keys(%{$confhash{$itemid}{'custom'}})) {
12508:                             foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
12509:                                 $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.('&nbsp;'x2);
12510:                             } 
12511:                         }
12512:                         if ($customlist) {
12513:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
12514:                         }
12515:                     } 
12516:                     $resulttext .= '</ul></li>';
12517:                 }
12518:             }
12519:             $resulttext .= '</ul>';
12520:         } else {
12521:             $resulttext = &mt('No changes made.');
12522:         }
12523:     } else {
12524:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
12525:     }
12526:     if ($errors) {
12527:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
12528:                        $errors.'</ul>';
12529:     }
12530:     return $resulttext;
12531: }
12532: 
12533: sub process_ltitools_image {
12534:     my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
12535:     my $filename = $env{'form.'.$caller.'.filename'};
12536:     my ($error,$url);
12537:     my ($width,$height) = (21,21);
12538:     if ($configuserok eq 'ok') {
12539:         if ($switchserver) {
12540:             $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
12541:                          $switchserver);
12542:         } elsif ($author_ok eq 'ok') {
12543:             my ($result,$imageurl,$madethumb) =
12544:                 &publishlogo($r,'upload',$caller,$dom,$confname,
12545:                              "ltitools/$itemid/icon",$width,$height);
12546:             if ($result eq 'ok') {
12547:                 if ($madethumb) {
12548:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
12549:                     my $imagethumb = "$path/tn-".$imagefile;
12550:                     $url = $imagethumb;
12551:                 } else {
12552:                     $url = $imageurl;
12553:                 }
12554:             } else {
12555:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
12556:             }
12557:         } else {
12558:             $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);
12559:         }
12560:     } else {
12561:         $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);
12562:     }
12563:     return ($url,$error);
12564: }
12565: 
12566: sub get_ltitools_id {
12567:     my ($cdom,$title) = @_;
12568:     # get lock on ltitools db
12569:     my $lockhash = {
12570:                       lock => $env{'user.name'}.
12571:                               ':'.$env{'user.domain'},
12572:                    };
12573:     my $tries = 0;
12574:     my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
12575:     my ($id,$error);
12576:  
12577:     while (($gotlock ne 'ok') && ($tries<10)) {
12578:         $tries ++;
12579:         sleep (0.1);
12580:         $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
12581:     }
12582:     if ($gotlock eq 'ok') {
12583:         my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
12584:         if ($currids{'lock'}) {
12585:             delete($currids{'lock'});
12586:             if (keys(%currids)) {
12587:                 my @curr = sort { $a <=> $b } keys(%currids);
12588:                 if ($curr[-1] =~ /^\d+$/) {
12589:                     $id = 1 + $curr[-1];
12590:                 }
12591:             } else {
12592:                 $id = 1;
12593:             }
12594:             if ($id) {
12595:                 unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
12596:                     $error = 'nostore';
12597:                 }
12598:             } else {
12599:                 $error = 'nonumber';
12600:             }
12601:         }
12602:         my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
12603:     } else {
12604:         $error = 'nolock';
12605:     }
12606:     return ($id,$error);
12607: }
12608: 
12609: sub modify_lti {
12610:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
12611:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12612:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
12613:     my (%posslti,%posslticrs,%posscrstype);
12614:     my @courseroles = ('cc','in','ta','ep','st');
12615:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
12616:     my @lticourseroles = qw(Instructor TeachingAssistant Mentor Learner);
12617:     my @coursetypes = ('official','unofficial','community','textbook','placement');
12618:     my %coursetypetitles = &Apache::lonlocal::texthash (
12619:                                official   => 'Official',
12620:                                unofficial => 'Unofficial',
12621:                                community  => 'Community',
12622:                                textbook   => 'Textbook',
12623:                                placement  => 'Placement Test',
12624:     );
12625:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
12626:     my %lt = &lti_names();
12627:     map { $posslti{$_} = 1; } @ltiroles;
12628:     map { $posslticrs{$_} = 1; } @lticourseroles;
12629:     map { $posscrstype{$_} = 1; } @coursetypes;
12630: 
12631:     my %menutitles = &ltimenu_titles();
12632: 
12633:     my (@items,%deletions,%itemids);
12634:     if ($env{'form.lti_add'}) {
12635:         my $consumer = $env{'form.lti_consumer_add'};
12636:         $consumer =~ s/(`)/'/g;
12637:         ($newid,my $error) = &get_lti_id($dom,$consumer);
12638:         if ($newid) {
12639:             $itemids{'add'} = $newid;
12640:             push(@items,'add');
12641:             $changes{$newid} = 1;
12642:         } else {
12643:             my $error = &mt('Failed to acquire unique ID for new LTI configuration');
12644:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12645:         }
12646:     }
12647:     if (ref($domconfig{$action}) eq 'HASH') {
12648:         my @todelete = &Apache::loncommon::get_env_multiple('form.lti_del');
12649:         if (@todelete) {
12650:             map { $deletions{$_} = 1; } @todelete;
12651:         }
12652:         my $maxnum = $env{'form.lti_maxnum'};
12653:         for (my $i=0; $i<=$maxnum; $i++) {
12654:             my $itemid = $env{'form.lti_id_'.$i};
12655:             $itemid =~ s/\D+//g;
12656:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
12657:                 if ($deletions{$itemid}) {
12658:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'consumer'};
12659:                 } else {
12660:                    push(@items,$i);
12661:                    $itemids{$i} = $itemid;
12662:                 }
12663:             }
12664:         }
12665:     }
12666:     foreach my $idx (@items) {
12667:         my $itemid = $itemids{$idx};
12668:         next unless ($itemid);
12669:         my $position = $env{'form.lti_pos_'.$idx};
12670:         $position =~ s/\D+//g;
12671:         if ($position ne '') {
12672:             $allpos[$position] = $itemid;
12673:         }
12674:         foreach my $item ('consumer','key','secret','lifetime','requser') {
12675:             my $formitem = 'form.lti_'.$item.'_'.$idx;
12676:             $env{$formitem} =~ s/(`)/'/g;
12677:             if ($item eq 'lifetime') {
12678:                 $env{$formitem} =~ s/[^\d.]//g;
12679:             }
12680:             if ($env{$formitem} ne '') {
12681:                 if (($item eq 'key') || ($item eq 'secret')) {
12682:                     $encconfig{$itemid}{$item} = $env{$formitem};
12683:                 } else {
12684:                     $confhash{$itemid}{$item} = $env{$formitem};
12685:                     unless (($idx eq 'add') || ($changes{$itemid})) {
12686:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
12687:                             $changes{$itemid} = 1;
12688:                         }
12689:                     }
12690:                 }
12691:             }
12692:         }
12693:         if ($env{'form.lti_version_'.$idx} eq 'LTI-1p0') {
12694:             $confhash{$itemid}{'version'} = $env{'form.lti_version_'.$idx};
12695:         }
12696:         if ($confhash{$itemid}{'requser'}) {
12697:             if ($env{'form.lti_mapuser_'.$idx} eq 'sourcedid') {
12698:                 $confhash{$itemid}{'mapuser'} = 'lis_person_sourcedid'; 
12699:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'email') {
12700:                 $confhash{$itemid}{'mapuser'} = 'lis_person_contact_email_primary';
12701:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'other') {
12702:                 my $mapuser = $env{'form.lti_customuser_'.$idx};
12703:                 $mapuser =~ s/(`)/'/g;
12704:                 $mapuser =~ s/^\s+|\s+$//g; 
12705:                 $confhash{$itemid}{'mapuser'} = $mapuser; 
12706:             }
12707:             foreach my $ltirole (@lticourseroles) {
12708:                 my $possrole = $env{'form.lti_maprole_'.$ltirole.'_'.$idx};
12709:                 if (grep(/^\Q$possrole\E$/,@courseroles)) {
12710:                     $confhash{$itemid}{'maproles'}{$ltirole} = $possrole;
12711:                 }
12712:             }
12713:             my @possmakeuser = &Apache::loncommon::get_env_multiple('form.lti_makeuser_'.$idx);
12714:             my @makeuser;
12715:             foreach my $ltirole (sort(@possmakeuser)) {
12716:                 if ($posslti{$ltirole}) {
12717:                     push(@makeuser,$ltirole);
12718:                 }
12719:             }
12720:             $confhash{$itemid}{'makeuser'} = \@makeuser;
12721:             if (@makeuser) {
12722:                 my $lcauth = $env{'form.lti_lcauth_'.$idx};
12723:                 if ($lcauth =~ /^(internal|krb4|krb5|localauth)$/) {
12724:                     $confhash{$itemid}{'lcauth'} = $lcauth;
12725:                     if ($lcauth ne 'internal') {
12726:                         my $lcauthparm = $env{'form.lti_lcauthparm_'.$idx};
12727:                         $lcauthparm =~ s/^(\s+|\s+)$//g;
12728:                         $lcauthparm =~ s/`//g;
12729:                         if ($lcauthparm ne '') {
12730:                             $confhash{$itemid}{'lcauthparm'} = $lcauthparm;
12731:                         }
12732:                     }
12733:                 } else {
12734:                     $confhash{$itemid}{'lcauth'} = 'lti';
12735:                 }
12736:             }
12737:             my @possinstdata =  &Apache::loncommon::get_env_multiple('form.lti_instdata_'.$idx);
12738:             if (@possinstdata) {
12739:                 foreach my $field (@possinstdata) {
12740:                     if (exists($fieldtitles{$field})) {
12741:                         push(@{$confhash{$itemid}{'instdata'}});
12742:                     }
12743:                 }
12744:             }
12745:             if (($env{'form.lti_mapcrs_'.$idx} eq 'course_offering_sourcedid') ||
12746:                 ($env{'form.lti_mapcrs_'.$idx} eq 'context_id'))  {
12747:                 $confhash{$itemid}{'mapcrs'} = $env{'form.lti_mapcrs_'.$idx};
12748:             } elsif ($env{'form.lti_mapcrs_'.$idx} eq 'other') {
12749:                 my $mapcrs = $env{'form.lti_mapcrsfield_'.$idx}; 
12750:                 $mapcrs =~ s/(`)/'/g;
12751:                 $mapcrs =~ s/^\s+|\s+$//g;
12752:                 $confhash{$itemid}{'mapcrs'} = $mapcrs;
12753:             }
12754:             my @posstypes = &Apache::loncommon::get_env_multiple('form.lti_mapcrstype_'.$idx);
12755:             my @crstypes;
12756:             foreach my $type (sort(@posstypes)) {
12757:                 if ($posscrstype{$type}) {
12758:                     push(@crstypes,$type);
12759:                 }
12760:             }
12761:             $confhash{$itemid}{'mapcrstype'} = \@crstypes;
12762:             if ($env{'form.lti_makecrs_'.$idx}) {
12763:                 $confhash{$itemid}{'makecrs'} = 1;
12764:             }
12765:             my @possenroll = &Apache::loncommon::get_env_multiple('form.lti_selfenroll_'.$idx);
12766:             my @selfenroll;
12767:             foreach my $type (sort(@possenroll)) {
12768:                 if ($posslticrs{$type}) {
12769:                     push(@selfenroll,$type);
12770:                 }
12771:             }
12772:             $confhash{$itemid}{'selfenroll'} = \@selfenroll;
12773:             if ($env{'form.lti_crssec_'.$idx}) {
12774:                 if ($env{'form.lti_crssecsrc_'.$idx} eq 'course_section_sourcedid') {
12775:                     $confhash{$itemid}{'section'} = $env{'form.lti_crssecsrc_'.$idx};
12776:                 } elsif ($env{'form.lti_crssecsrc_'.$idx} eq 'other') {
12777:                     my $section = $env{'form.lti_customsection_'.$idx};
12778:                     $section =~ s/(`)/'/g;
12779:                     $section =~ s/^\s+|\s+$//g;
12780:                     if ($section ne '') {
12781:                         $confhash{$itemid}{'section'} = $section;
12782:                     }
12783:                 }
12784:             }
12785:             if ($env{'form.lti_callback_'.$idx}) {
12786:                 if ($env{'form.lti_callbackparam_'.$idx}) {
12787:                     my $callback = $env{'form.lti_callbackparam_'.$idx};
12788:                     $callback =~ s/^\s+|\s+$//g;
12789:                     $confhash{$itemid}{'callback'} = $callback;
12790:                 }
12791:             }
12792:             foreach my $field ('passback','roster','topmenu','inlinemenu') {
12793:                 if ($env{'form.lti_'.$field.'_'.$idx}) {
12794:                     $confhash{$itemid}{$field} = 1;
12795:                 }
12796:             }
12797:             if ($env{'form.lti_passback_'.$idx}) {
12798:                 if ($env{'form.lti_passbackformat_'.$idx} eq '1.0') {
12799:                     $confhash{$itemid}{'passbackformat'} = '1.0';
12800:                 } else {
12801:                     $confhash{$itemid}{'passbackformat'} = '1.1';
12802:                 }
12803:             }
12804:             if ($env{'form.lti_topmenu_'.$idx} || $env{'form.lti_inlinemenu_'.$idx}) {
12805:                 $confhash{$itemid}{lcmenu} = [];
12806:                 my @possmenu = &Apache::loncommon::get_env_multiple('form.lti_menuitem_'.$idx);
12807:                 foreach my $field (@possmenu) {
12808:                     if (exists($menutitles{$field})) {
12809:                         if ($field eq 'grades') {
12810:                             next unless ($env{'form.lti_inlinemenu_'.$idx});
12811:                         }
12812:                         push(@{$confhash{$itemid}{lcmenu}},$field);
12813:                     }
12814:                 }
12815:             }
12816:             unless (($idx eq 'add') || ($changes{$itemid})) {
12817:                 foreach my $field ('mapuser','mapcrs','makecrs','section','passback','roster','lcauth','lcauthparm','topmenu','inlinemenu','callback') {
12818:                     if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
12819:                         $changes{$itemid} = 1;
12820:                     }
12821:                 }
12822:                 unless ($changes{$itemid}) {
12823:                     if ($domconfig{$action}{$itemid}{'passback'} eq $confhash{$itemid}{'passback'}) {
12824:                         if ($domconfig{$action}{$itemid}{'passbackformat'} ne $confhash{$itemid}{'passbackformat'}) {
12825:                             $changes{$itemid} = 1;
12826:                         }
12827:                     }
12828:                 }
12829:                 foreach my $field ('makeuser','mapcrstype','selfenroll','instdata','lcmenu') {
12830:                     unless ($changes{$itemid}) {
12831:                         if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
12832:                             if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
12833:                                 my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
12834:                                                                                $confhash{$itemid}{$field});
12835:                                 if (@diffs) {
12836:                                     $changes{$itemid} = 1;
12837:                                 }
12838:                             } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
12839:                                 $changes{$itemid} = 1;
12840:                             }
12841:                         } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
12842:                             if (@{$confhash{$itemid}{$field}} > 0) {
12843:                                 $changes{$itemid} = 1;
12844:                             }
12845:                         }
12846:                     }
12847:                 }
12848:                 unless ($changes{$itemid}) {
12849:                     if (ref($domconfig{$action}{$itemid}{'maproles'}) eq 'HASH') {
12850:                         if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
12851:                             foreach my $ltirole (keys(%{$domconfig{$action}{$itemid}{'maproles'}})) {
12852:                                 if ($domconfig{$action}{$itemid}{'maproles'}{$ltirole} ne 
12853:                                     $confhash{$itemid}{'maproles'}{$ltirole}) {
12854:                                     $changes{$itemid} = 1;
12855:                                     last;
12856:                                 }
12857:                             }
12858:                             unless ($changes{$itemid}) {
12859:                                 foreach my $ltirole (keys(%{$confhash{$itemid}{'maproles'}})) {
12860:                                     if ($confhash{$itemid}{'maproles'}{$ltirole} ne 
12861:                                         $domconfig{$action}{$itemid}{'maproles'}{$ltirole}) {
12862:                                         $changes{$itemid} = 1;
12863:                                         last;
12864:                                     }
12865:                                 }
12866:                             }
12867:                         } elsif (keys(%{$domconfig{$action}{$itemid}{'maproles'}}) > 0) {
12868:                             $changes{$itemid} = 1;
12869:                         }
12870:                     } elsif (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
12871:                         unless ($changes{$itemid}) {
12872:                             if (keys(%{$confhash{$itemid}{'maproles'}}) > 0) {
12873:                                 $changes{$itemid} = 1;
12874:                             }
12875:                         }
12876:                     }
12877:                 }
12878:             }
12879:         }
12880:     }
12881:     if (@allpos > 0) {
12882:         my $idx = 0;
12883:         foreach my $itemid (@allpos) {
12884:             if ($itemid ne '') {
12885:                 $confhash{$itemid}{'order'} = $idx;
12886:                 if (ref($domconfig{$action}) eq 'HASH') {
12887:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
12888:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
12889:                             $changes{$itemid} = 1;
12890:                         }
12891:                     }
12892:                 }
12893:                 $idx ++;
12894:             }
12895:         }
12896:     }
12897:     my %ltihash = (
12898:                           $action => { %confhash }
12899:                        );
12900:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,
12901:                                              $dom);
12902:     if ($putresult eq 'ok') {
12903:         my %ltienchash = (
12904:                              $action => { %encconfig }
12905:                          );
12906:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom);
12907:         if (keys(%changes) > 0) {
12908:             my $cachetime = 24*60*60;
12909:             my %ltiall = %confhash;
12910:             foreach my $id (keys(%ltiall)) {
12911:                 if (ref($encconfig{$id}) eq 'HASH') {
12912:                     foreach my $item ('key','secret') {
12913:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
12914:                     }
12915:                 }
12916:             }
12917:             &Apache::lonnet::do_cache_new('lti',$dom,\%ltiall,$cachetime);
12918:             if (ref($lastactref) eq 'HASH') {
12919:                 $lastactref->{'lti'} = 1;
12920:             }
12921:             $resulttext = &mt('Changes made:').'<ul>';
12922:             my %bynum;
12923:             foreach my $itemid (sort(keys(%changes))) {
12924:                 my $position = $confhash{$itemid}{'order'};
12925:                 $bynum{$position} = $itemid;
12926:             }
12927:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
12928:                 my $itemid = $bynum{$pos};
12929:                 if (ref($confhash{$itemid}) ne 'HASH') {
12930:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
12931:                 } else {
12932:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'consumer'}.'</b></li><ul>';
12933:                     my $position = $pos + 1;
12934:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
12935:                     foreach my $item ('version','lifetime') {
12936:                         if ($confhash{$itemid}{$item} ne '') {
12937:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
12938:                         }
12939:                     }
12940:                     if ($encconfig{$itemid}{'key'} ne '') {
12941:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
12942:                     }
12943:                     if ($encconfig{$itemid}{'secret'} ne '') {
12944:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
12945:                         my $num = length($encconfig{$itemid}{'secret'});
12946:                         $resulttext .= ('*'x$num).'</li>';
12947:                     }
12948:                     if ($confhash{$itemid}{'requser'}) {
12949:                         if ($confhash{$itemid}{'mapuser'}) {
12950:                             my $shownmapuser;
12951:                             if ($confhash{$itemid}{'mapuser'} eq 'lis_person_sourcedid') {
12952:                                 $shownmapuser = $lt{'sourcedid'}.' (lis_person_sourcedid)';
12953:                             } elsif ($confhash{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') {
12954:                                 $shownmapuser = $lt{'email'}.' (lis_person_contact_email_primary)';
12955:                             } else {
12956:                                 $shownmapuser = &mt('Other').' ('.$confhash{$itemid}{'mapuser'}.')';
12957:                             }
12958:                             $resulttext .= '<li>'.&mt('LON-CAPA username').': '.$shownmapuser.'</li>';
12959:                         }
12960:                         if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
12961:                             my $rolemaps;
12962:                             foreach my $role (@ltiroles) {
12963:                                 if ($confhash{$itemid}{'maproles'}{$role}) {
12964:                                     $rolemaps .= ('&nbsp;'x2).$role.'='.
12965:                                                  &Apache::lonnet::plaintext($confhash{$itemid}{'maproles'}{$role},
12966:                                                                             'Course').',';
12967:                                 }
12968:                             }
12969:                             if ($rolemaps) {
12970:                                 $rolemaps =~ s/,$//;
12971:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
12972:                             }
12973:                         }
12974:                         if (ref($confhash{$itemid}{'makeuser'}) eq 'ARRAY') {
12975:                             if (@{$confhash{$itemid}{'makeuser'}} > 0) { 
12976:                                 $resulttext .= '<li>'.&mt('Following roles may create user accounts: [_1]',
12977:                                                           join(', ',@{$confhash{$itemid}{'makeuser'}})).'<br />';
12978:                                 if ($confhash{$itemid}{'lcauth'} eq 'lti') {
12979:                                     $resulttext .= &mt('New users will only be able to authenticate via LTI').'</li>';
12980:                                 } else {
12981:                                     $resulttext .= &mt('New users will be assigned LON-CAPA authentication: [_1]',
12982:                                                        $confhash{$itemid}{'lcauth'});
12983:                                     if ($confhash{$itemid}{'lcauth'} eq 'internal') {
12984:                                         $resulttext .= '; '.&mt('a randomly generated password will be created');
12985:                                     } elsif ($confhash{$itemid}{'lcauth'} eq 'localauth') {
12986:                                         if ($confhash{$itemid}{'lcauthparm'} ne '') {
12987:                                             $resulttext .= ' '.&mt('with argument: [_1]',$confhash{$itemid}{'lcauthparm'});
12988:                                         }
12989:                                     } else {
12990:                                         $resulttext .= '; '.&mt('Kerberos domain: [_1]',$confhash{$itemid}{'lcauthparm'});
12991:                                     }
12992:                                 }
12993:                                 $resulttext .= '</li>';
12994:                             } else {
12995:                                 $resulttext .= '<li>'.&mt('User account creation not permitted.').'</li>';
12996:                             }
12997:                         }
12998:                         if (ref($confhash{$itemid}{'instdata'}) eq 'ARRAY') {
12999:                             if (@{$confhash{$itemid}{'instdata'}} > 0) {
13000:                                 $resulttext .= '<li>'.&mt('Institutional data will be used when creating a new user for: [_1]',
13001:                                                           join(', ',map { $fieldtitles{$_}; } @{$confhash{$itemid}{'instdata'}})).'</li>';
13002:                             } else {
13003:                                 $resulttext .= '<li>'.&mt('No institutional data used when creating a new user.').'</li>';
13004:                             }
13005:                         }
13006:                         if ($confhash{$itemid}{'mapcrs'}) {
13007:                             $resulttext .= '<li>'.&mt('Unique course identifier').': '.$confhash{$itemid}{'mapcrs'}.'</li>';
13008:                         }
13009:                         if (ref($confhash{$itemid}{'mapcrstype'}) eq 'ARRAY') {
13010:                             if (@{$confhash{$itemid}{'mapcrstype'}} > 0) {
13011:                                 $resulttext .= '<li>'.&mt('Mapping for the following LON-CAPA course types: [_1]',
13012:                                                join(', ',map { $coursetypetitles{$_}; } @coursetypes)).
13013:                                                '</li>';
13014:                             } else {
13015:                                 $resulttext .= '<li>'.&mt('No mapping to LON-CAPA courses').'</li>';
13016:                             }
13017:                         }
13018:                         if ($confhash{$itemid}{'makecrs'}) {
13019:                             $resulttext .= '<li>'.&mt('Instructor may create course (if absent).').'</li>';
13020:                         } else {
13021:                             $resulttext .= '<li>'.&mt('Instructor may not create course (if absent).').'</li>';
13022:                         }
13023:                         if (ref($confhash{$itemid}{'selfenroll'}) eq 'ARRAY') {
13024:                             if (@{$confhash{$itemid}{'selfenroll'}} > 0) {
13025:                                 $resulttext .= '<li>'.&mt('Self-enrollment for following roles: [_1]',
13026:                                                           join(', ',@{$confhash{$itemid}{'selfenroll'}})).
13027:                                                '</li>';
13028:                             } else {
13029:                                 $resulttext .= '<li>'.&mt('Self-enrollment not permitted').'</li>';
13030:                             }
13031:                         }
13032:                         if ($confhash{$itemid}{'section'}) {
13033:                             if ($confhash{$itemid}{'section'} eq 'course_section_sourcedid') {
13034:                                 $resulttext .= '<li>'.&mt('User section from standard field:').
13035:                                                      ' (course_section_sourcedid)'.'</li>';  
13036:                             } else {
13037:                                 $resulttext .= '<li>'.&mt('User section from:').' '.
13038:                                                       $confhash{$itemid}{'section'}.'</li>';
13039:                             }
13040:                         } else {
13041:                             $resulttext .= '<li>'.&mt('No section assignment').'</li>';
13042:                         }
13043:                         if ($confhash{$itemid}{'callback'}) {
13044:                             $resulttext .= '<li>'.&mt('Callback setting').': '.$confhash{$itemid}{'callback'}.'</li>';
13045:                         } else {
13046:                             $resulttext .= '<li>'.&mt('No callback to logout LON-CAPA session when user logs out of Comsumer');
13047:                         }
13048:                         foreach my $item ('passback','roster','topmenu','inlinemenu') {
13049:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
13050:                             if ($confhash{$itemid}{$item}) {
13051:                                 $resulttext .= &mt('Yes');
13052:                                 if ($item eq 'passback') {
13053:                                     if ($confhash{$itemid}{'passbackformat'} eq '1.0') {
13054:                                         $resulttext .= '&nbsp;('.&mt('Outcomes Extension (1.0)').')';
13055:                                     } elsif ($confhash{$itemid}{'passbackformat'} eq '1.1') {
13056:                                         $resulttext .= '&nbsp;('.&mt('Outcomes Service (1.1)').')';
13057:                                     }
13058:                                 }
13059:                             } else {
13060:                                 $resulttext .= &mt('No');
13061:                             }
13062:                             $resulttext .= '</li>';
13063:                         }
13064:                         if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
13065:                             if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
13066:                                 $resulttext .= '<li>'.&mt('Menu items:').' '.
13067:                                                join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>'; 
13068:                             } else {
13069:                                 $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>'; 
13070:                             }
13071:                         }
13072:                     }
13073:                     $resulttext .= '</ul></li>';
13074:                 }
13075:             }
13076:             $resulttext .= '</ul>';
13077:         } else {
13078:             $resulttext = &mt('No changes made.');
13079:         }
13080:     } else {
13081:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
13082:     }
13083:     if ($errors) {
13084:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
13085:                        $errors.'</ul>';
13086:     }
13087:     return $resulttext;
13088: }
13089: 
13090: sub get_lti_id {
13091:     my ($domain,$consumer) = @_;
13092:     # get lock on lti db
13093:     my $lockhash = {
13094:                       lock => $env{'user.name'}.
13095:                               ':'.$env{'user.domain'},
13096:                    };
13097:     my $tries = 0;
13098:     my $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
13099:     my ($id,$error);
13100: 
13101:     while (($gotlock ne 'ok') && ($tries<10)) {
13102:         $tries ++;
13103:         sleep (0.1);
13104:         $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
13105:     }
13106:     if ($gotlock eq 'ok') {
13107:         my %currids = &Apache::lonnet::dump_dom('lti',$domain);
13108:         if ($currids{'lock'}) {
13109:             delete($currids{'lock'});
13110:             if (keys(%currids)) {
13111:                 my @curr = sort { $a <=> $b } keys(%currids);
13112:                 if ($curr[-1] =~ /^\d+$/) {
13113:                     $id = 1 + $curr[-1];
13114:                 }
13115:             } else {
13116:                 $id = 1;
13117:             }
13118:             if ($id) {
13119:                 unless (&Apache::lonnet::newput_dom('lti',{ $id => $consumer },$domain) eq 'ok') {
13120:                     $error = 'nostore';
13121:                 }
13122:             } else {
13123:                 $error = 'nonumber';
13124:             }
13125:         }
13126:         my $dellockoutcome = &Apache::lonnet::del_dom('lti',['lock'],$domain);
13127:     } else {
13128:         $error = 'nolock';
13129:     }
13130:     return ($id,$error);
13131: }
13132: 
13133: sub modify_autoenroll {
13134:     my ($dom,$lastactref,%domconfig) = @_;
13135:     my ($resulttext,%changes);
13136:     my %currautoenroll;
13137:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
13138:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
13139:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
13140:         }
13141:     }
13142:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
13143:     my %title = ( run => 'Auto-enrollment active',
13144:                   sender => 'Sender for notification messages',
13145:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
13146:                   failsafe => 'Failsafe for no drops if institutional data missing for a section');
13147:     my @offon = ('off','on');
13148:     my $sender_uname = $env{'form.sender_uname'};
13149:     my $sender_domain = $env{'form.sender_domain'};
13150:     if ($sender_domain eq '') {
13151:         $sender_uname = '';
13152:     } elsif ($sender_uname eq '') {
13153:         $sender_domain = '';
13154:     }
13155:     my $coowners = $env{'form.autoassign_coowners'};
13156:     my $failsafe = $env{'form.autoenroll_failsafe'};
13157:     $failsafe =~ s{^\s+|\s+$}{}g;
13158:     if ($failsafe =~ /\D/) {
13159:         undef($failsafe);
13160:     }
13161:     my %autoenrollhash =  (
13162:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
13163:                                        'sender_uname' => $sender_uname,
13164:                                        'sender_domain' => $sender_domain,
13165:                                        'co-owners' => $coowners,
13166:                                        'autofailsafe' => $failsafe,
13167:                                 }
13168:                      );
13169:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
13170:                                              $dom);
13171:     if ($putresult eq 'ok') {
13172:         if (exists($currautoenroll{'run'})) {
13173:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
13174:                  $changes{'run'} = 1;
13175:              }
13176:         } elsif ($autorun) {
13177:             if ($env{'form.autoenroll_run'} ne '1') {
13178:                  $changes{'run'} = 1;
13179:             }
13180:         }
13181:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
13182:             $changes{'sender'} = 1;
13183:         }
13184:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
13185:             $changes{'sender'} = 1;
13186:         }
13187:         if ($currautoenroll{'co-owners'} ne '') {
13188:             if ($currautoenroll{'co-owners'} ne $coowners) {
13189:                 $changes{'coowners'} = 1;
13190:             }
13191:         } elsif ($coowners) {
13192:             $changes{'coowners'} = 1;
13193:         }
13194:         if ($currautoenroll{'autofailsafe'} ne $failsafe) {
13195:             $changes{'autofailsafe'} = 1;
13196:         }
13197:         if (keys(%changes) > 0) {
13198:             $resulttext = &mt('Changes made:').'<ul>';
13199:             if ($changes{'run'}) {
13200:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
13201:             }
13202:             if ($changes{'sender'}) {
13203:                 if ($sender_uname eq '' || $sender_domain eq '') {
13204:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
13205:                 } else {
13206:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
13207:                 }
13208:             }
13209:             if ($changes{'coowners'}) {
13210:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
13211:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
13212:                 if (ref($lastactref) eq 'HASH') {
13213:                     $lastactref->{'domainconfig'} = 1;
13214:                 }
13215:             }
13216:             if ($changes{'autofailsafe'}) {
13217:                 if ($failsafe ne '') {
13218:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$failsafe).'</li>';
13219:                 } else {
13220:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section: deleted');
13221:                 }
13222:                 &Apache::lonnet::get_domain_defaults($dom,1);
13223:                 if (ref($lastactref) eq 'HASH') {
13224:                     $lastactref->{'domdefaults'} = 1;
13225:                 }
13226:             }
13227:             $resulttext .= '</ul>';
13228:         } else {
13229:             $resulttext = &mt('No changes made to auto-enrollment settings');
13230:         }
13231:     } else {
13232:         $resulttext = '<span class="LC_error">'.
13233: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
13234:     }
13235:     return $resulttext;
13236: }
13237: 
13238: sub modify_autoupdate {
13239:     my ($dom,%domconfig) = @_;
13240:     my ($resulttext,%currautoupdate,%fields,%changes);
13241:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
13242:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
13243:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
13244:         }
13245:     }
13246:     my @offon = ('off','on');
13247:     my %title = &Apache::lonlocal::texthash (
13248:                    run => 'Auto-update:',
13249:                    classlists => 'Updates to user information in classlists?'
13250:                 );
13251:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13252:     my %fieldtitles = &Apache::lonlocal::texthash (
13253:                         id => 'Student/Employee ID',
13254:                         permanentemail => 'E-mail address',
13255:                         lastname => 'Last Name',
13256:                         firstname => 'First Name',
13257:                         middlename => 'Middle Name',
13258:                         generation => 'Generation',
13259:                       );
13260:     $othertitle = &mt('All users');
13261:     if (keys(%{$usertypes}) >  0) {
13262:         $othertitle = &mt('Other users');
13263:     }
13264:     foreach my $key (keys(%env)) {
13265:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
13266:             my ($usertype,$item) = ($1,$2);
13267:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
13268:                 if ($usertype eq 'default') {   
13269:                     push(@{$fields{$1}},$2);
13270:                 } elsif (ref($types) eq 'ARRAY') {
13271:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
13272:                         push(@{$fields{$1}},$2);
13273:                     }
13274:                 }
13275:             }
13276:         }
13277:     }
13278:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
13279:     @lockablenames = sort(@lockablenames);
13280:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
13281:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
13282:         if (@changed) {
13283:             $changes{'lockablenames'} = 1;
13284:         }
13285:     } else {
13286:         if (@lockablenames) {
13287:             $changes{'lockablenames'} = 1;
13288:         }
13289:     }
13290:     my %updatehash = (
13291:                       autoupdate => { run => $env{'form.autoupdate_run'},
13292:                                       classlists => $env{'form.classlists'},
13293:                                       fields => {%fields},
13294:                                       lockablenames => \@lockablenames,
13295:                                     }
13296:                      );
13297:     foreach my $key (keys(%currautoupdate)) {
13298:         if (($key eq 'run') || ($key eq 'classlists')) {
13299:             if (exists($updatehash{autoupdate}{$key})) {
13300:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
13301:                     $changes{$key} = 1;
13302:                 }
13303:             }
13304:         } elsif ($key eq 'fields') {
13305:             if (ref($currautoupdate{$key}) eq 'HASH') {
13306:                 foreach my $item (@{$types},'default') {
13307:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
13308:                         my $change = 0;
13309:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
13310:                             if (!exists($fields{$item})) {
13311:                                 $change = 1;
13312:                                 last;
13313:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
13314:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
13315:                                     $change = 1;
13316:                                     last;
13317:                                 }
13318:                             }
13319:                         }
13320:                         if ($change) {
13321:                             push(@{$changes{$key}},$item);
13322:                         }
13323:                     } 
13324:                 }
13325:             }
13326:         } elsif ($key eq 'lockablenames') {
13327:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
13328:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
13329:                 if (@changed) {
13330:                     $changes{'lockablenames'} = 1;
13331:                 }
13332:             } else {
13333:                 if (@lockablenames) {
13334:                     $changes{'lockablenames'} = 1;
13335:                 }
13336:             }
13337:         }
13338:     }
13339:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
13340:         if (@lockablenames) {
13341:             $changes{'lockablenames'} = 1;
13342:         }
13343:     }
13344:     foreach my $item (@{$types},'default') {
13345:         if (defined($fields{$item})) {
13346:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
13347:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
13348:                     my $change = 0;
13349:                     if (ref($fields{$item}) eq 'ARRAY') {
13350:                         foreach my $type (@{$fields{$item}}) {
13351:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
13352:                                 $change = 1;
13353:                                 last;
13354:                             }
13355:                         }
13356:                     }
13357:                     if ($change) {
13358:                         push(@{$changes{'fields'}},$item);
13359:                     }
13360:                 } else {
13361:                     push(@{$changes{'fields'}},$item);
13362:                 }
13363:             } else {
13364:                 push(@{$changes{'fields'}},$item);
13365:             }
13366:         }
13367:     }
13368:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
13369:                                              $dom);
13370:     if ($putresult eq 'ok') {
13371:         if (keys(%changes) > 0) {
13372:             $resulttext = &mt('Changes made:').'<ul>';
13373:             foreach my $key (sort(keys(%changes))) {
13374:                 if ($key eq 'lockablenames') {
13375:                     $resulttext .= '<li>';
13376:                     if (@lockablenames) {
13377:                         $usertypes->{'default'} = $othertitle;
13378:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
13379:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
13380:                     } else {
13381:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
13382:                     }
13383:                     $resulttext .= '</li>';
13384:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
13385:                     foreach my $item (@{$changes{$key}}) {
13386:                         my @newvalues;
13387:                         foreach my $type (@{$fields{$item}}) {
13388:                             push(@newvalues,$fieldtitles{$type});
13389:                         }
13390:                         my $newvaluestr;
13391:                         if (@newvalues > 0) {
13392:                             $newvaluestr = join(', ',@newvalues);
13393:                         } else {
13394:                             $newvaluestr = &mt('none');
13395:                         }
13396:                         if ($item eq 'default') {
13397:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
13398:                         } else {
13399:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
13400:                         }
13401:                     }
13402:                 } else {
13403:                     my $newvalue;
13404:                     if ($key eq 'run') {
13405:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
13406:                     } else {
13407:                         $newvalue = $offon[$env{'form.'.$key}];
13408:                     }
13409:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
13410:                 }
13411:             }
13412:             $resulttext .= '</ul>';
13413:         } else {
13414:             $resulttext = &mt('No changes made to autoupdates');
13415:         }
13416:     } else {
13417:         $resulttext = '<span class="LC_error">'.
13418: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
13419:     }
13420:     return $resulttext;
13421: }
13422: 
13423: sub modify_autocreate {
13424:     my ($dom,%domconfig) = @_;
13425:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
13426:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
13427:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
13428:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
13429:         }
13430:     }
13431:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
13432:                  req => 'Auto-creation of validated requests for official courses',
13433:                  xmldc => 'Identity of course creator of courses from XML files',
13434:                );
13435:     my @types = ('xml','req');
13436:     foreach my $item (@types) {
13437:         $newvals{$item} = $env{'form.autocreate_'.$item};
13438:         $newvals{$item} =~ s/\D//g;
13439:         $newvals{$item} = 0 if ($newvals{$item} eq '');
13440:     }
13441:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
13442:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
13443:     unless (exists($domcoords{$newvals{'xmldc'}})) {
13444:         $newvals{'xmldc'} = '';
13445:     } 
13446:     %autocreatehash =  (
13447:                         autocreate => { xml => $newvals{'xml'},
13448:                                         req => $newvals{'req'},
13449:                                       }
13450:                        );
13451:     if ($newvals{'xmldc'} ne '') {
13452:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
13453:     }
13454:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
13455:                                              $dom);
13456:     if ($putresult eq 'ok') {
13457:         my @items = @types;
13458:         if ($newvals{'xml'}) {
13459:             push(@items,'xmldc');
13460:         }
13461:         foreach my $item (@items) {
13462:             if (exists($currautocreate{$item})) {
13463:                 if ($currautocreate{$item} ne $newvals{$item}) {
13464:                     $changes{$item} = 1;
13465:                 }
13466:             } elsif ($newvals{$item}) {
13467:                 $changes{$item} = 1;
13468:             }
13469:         }
13470:         if (keys(%changes) > 0) {
13471:             my @offon = ('off','on'); 
13472:             $resulttext = &mt('Changes made:').'<ul>';
13473:             foreach my $item (@types) {
13474:                 if ($changes{$item}) {
13475:                     my $newtxt = $offon[$newvals{$item}];
13476:                     $resulttext .= '<li>'.
13477:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
13478:                                        '<b>','</b>').
13479:                                    '</li>';
13480:                 }
13481:             }
13482:             if ($changes{'xmldc'}) {
13483:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
13484:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
13485:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
13486:             }
13487:             $resulttext .= '</ul>';
13488:         } else {
13489:             $resulttext = &mt('No changes made to auto-creation settings');
13490:         }
13491:     } else {
13492:         $resulttext = '<span class="LC_error">'.
13493:             &mt('An error occurred: [_1]',$putresult).'</span>';
13494:     }
13495:     return $resulttext;
13496: }
13497: 
13498: sub modify_directorysrch {
13499:     my ($dom,$lastactref,%domconfig) = @_;
13500:     my ($resulttext,%changes);
13501:     my %currdirsrch;
13502:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
13503:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
13504:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
13505:         }
13506:     }
13507:     my %title = ( available => 'Institutional directory search available',
13508:                   localonly => 'Other domains can search institution',
13509:                   lcavailable => 'LON-CAPA directory search available',
13510:                   lclocalonly => 'Other domains can search LON-CAPA domain',
13511:                   searchby => 'Search types',
13512:                   searchtypes => 'Search latitude');
13513:     my @offon = ('off','on');
13514:     my @otherdoms = ('Yes','No');
13515: 
13516:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
13517:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
13518:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
13519: 
13520:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13521:     if (keys(%{$usertypes}) == 0) {
13522:         @cansearch = ('default');
13523:     } else {
13524:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
13525:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
13526:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
13527:                     push(@{$changes{'cansearch'}},$type);
13528:                 }
13529:             }
13530:             foreach my $type (@cansearch) {
13531:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
13532:                     push(@{$changes{'cansearch'}},$type);
13533:                 }
13534:             }
13535:         } else {
13536:             push(@{$changes{'cansearch'}},@cansearch);
13537:         }
13538:     }
13539: 
13540:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
13541:         foreach my $by (@{$currdirsrch{'searchby'}}) {
13542:             if (!grep(/^\Q$by\E$/,@searchby)) {
13543:                 push(@{$changes{'searchby'}},$by);
13544:             }
13545:         }
13546:         foreach my $by (@searchby) {
13547:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
13548:                 push(@{$changes{'searchby'}},$by);
13549:             }
13550:         }
13551:     } else {
13552:         push(@{$changes{'searchby'}},@searchby);
13553:     }
13554: 
13555:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
13556:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
13557:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
13558:                 push(@{$changes{'searchtypes'}},$type);
13559:             }
13560:         }
13561:         foreach my $type (@searchtypes) {
13562:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
13563:                 push(@{$changes{'searchtypes'}},$type);
13564:             }
13565:         }
13566:     } else {
13567:         if (exists($currdirsrch{'searchtypes'})) {
13568:             foreach my $type (@searchtypes) {  
13569:                 if ($type ne $currdirsrch{'searchtypes'}) { 
13570:                     push(@{$changes{'searchtypes'}},$type);
13571:                 }
13572:             }
13573:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
13574:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
13575:             }   
13576:         } else {
13577:             push(@{$changes{'searchtypes'}},@searchtypes); 
13578:         }
13579:     }
13580: 
13581:     my %dirsrch_hash =  (
13582:             directorysrch => { available => $env{'form.dirsrch_available'},
13583:                                cansearch => \@cansearch,
13584:                                localonly => $env{'form.dirsrch_instlocalonly'},
13585:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
13586:                                lcavailable => $env{'form.dirsrch_domavailable'},
13587:                                searchby => \@searchby,
13588:                                searchtypes => \@searchtypes,
13589:                              }
13590:             );
13591:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
13592:                                              $dom);
13593:     if ($putresult eq 'ok') {
13594:         if (exists($currdirsrch{'available'})) {
13595:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
13596:                  $changes{'available'} = 1;
13597:              }
13598:         } else {
13599:             if ($env{'form.dirsrch_available'} eq '1') {
13600:                 $changes{'available'} = 1;
13601:             }
13602:         }
13603:         if (exists($currdirsrch{'lcavailable'})) {
13604:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
13605:                 $changes{'lcavailable'} = 1;
13606:             }
13607:         } else {
13608:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
13609:                 $changes{'lcavailable'} = 1;
13610:             }
13611:         }
13612:         if (exists($currdirsrch{'localonly'})) {
13613:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
13614:                 $changes{'localonly'} = 1;
13615:             }
13616:         } else {
13617:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
13618:                 $changes{'localonly'} = 1;
13619:             }
13620:         }
13621:         if (exists($currdirsrch{'lclocalonly'})) {
13622:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
13623:                 $changes{'lclocalonly'} = 1;
13624:             }
13625:         } else {
13626:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
13627:                 $changes{'lclocalonly'} = 1;
13628:             }
13629:         }
13630:         if (keys(%changes) > 0) {
13631:             $resulttext = &mt('Changes made:').'<ul>';
13632:             if ($changes{'available'}) {
13633:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
13634:             }
13635:             if ($changes{'lcavailable'}) {
13636:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
13637:             }
13638:             if ($changes{'localonly'}) {
13639:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
13640:             }
13641:             if ($changes{'lclocalonly'}) {
13642:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
13643:             }
13644:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
13645:                 my $chgtext;
13646:                 if (ref($usertypes) eq 'HASH') {
13647:                     if (keys(%{$usertypes}) > 0) {
13648:                         foreach my $type (@{$types}) {
13649:                             if (grep(/^\Q$type\E$/,@cansearch)) {
13650:                                 $chgtext .= $usertypes->{$type}.'; ';
13651:                             }
13652:                         }
13653:                         if (grep(/^default$/,@cansearch)) {
13654:                             $chgtext .= $othertitle;
13655:                         } else {
13656:                             $chgtext =~ s/\; $//;
13657:                         }
13658:                         $resulttext .=
13659:                             '<li>'.
13660:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
13661:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
13662:                             '</li>';
13663:                     }
13664:                 }
13665:             }
13666:             if (ref($changes{'searchby'}) eq 'ARRAY') {
13667:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
13668:                 my $chgtext;
13669:                 foreach my $type (@{$titleorder}) {
13670:                     if (grep(/^\Q$type\E$/,@searchby)) {
13671:                         if (defined($searchtitles->{$type})) {
13672:                             $chgtext .= $searchtitles->{$type}.'; ';
13673:                         }
13674:                     }
13675:                 }
13676:                 $chgtext =~ s/\; $//;
13677:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
13678:             }
13679:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
13680:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
13681:                 my $chgtext;
13682:                 foreach my $type (@{$srchtypeorder}) {
13683:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
13684:                         if (defined($srchtypes_desc->{$type})) {
13685:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
13686:                         }
13687:                     }
13688:                 }
13689:                 $chgtext =~ s/\; $//;
13690:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
13691:             }
13692:             $resulttext .= '</ul>';
13693:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
13694:             if (ref($lastactref) eq 'HASH') {
13695:                 $lastactref->{'directorysrch'} = 1;
13696:             }
13697:         } else {
13698:             $resulttext = &mt('No changes made to directory search settings');
13699:         }
13700:     } else {
13701:         $resulttext = '<span class="LC_error">'.
13702:                       &mt('An error occurred: [_1]',$putresult).'</span>';
13703:     }
13704:     return $resulttext;
13705: }
13706: 
13707: sub modify_contacts {
13708:     my ($dom,$lastactref,%domconfig) = @_;
13709:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
13710:     if (ref($domconfig{'contacts'}) eq 'HASH') {
13711:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
13712:             $currsetting{$key} = $domconfig{'contacts'}{$key};
13713:         }
13714:     }
13715:     my (%others,%to,%bcc,%includestr,%includeloc);
13716:     my @contacts = ('supportemail','adminemail');
13717:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
13718:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
13719:     my @toggles = ('reporterrors','reportupdates','reportstatus');
13720:     my @lonstatus = ('threshold','sysmail','weights','excluded');
13721:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
13722:     foreach my $type (@mailings) {
13723:         @{$newsetting{$type}} = 
13724:             &Apache::loncommon::get_env_multiple('form.'.$type);
13725:         foreach my $item (@contacts) {
13726:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
13727:                 $contacts_hash{contacts}{$type}{$item} = 1;
13728:             } else {
13729:                 $contacts_hash{contacts}{$type}{$item} = 0;
13730:             }
13731:         }
13732:         $others{$type} = $env{'form.'.$type.'_others'};
13733:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
13734:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
13735:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
13736:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
13737:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
13738:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
13739:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
13740:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
13741:             }
13742:         }
13743:     }
13744:     foreach my $item (@contacts) {
13745:         $to{$item} = $env{'form.'.$item};
13746:         $contacts_hash{'contacts'}{$item} = $to{$item};
13747:     }
13748:     foreach my $item (@toggles) {
13749:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
13750:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
13751:         }
13752:     }
13753:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
13754:     foreach my $item (@lonstatus) {
13755:         if ($item eq 'excluded') {
13756:             my (%serverhomes,@excluded);
13757:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
13758:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
13759:             if (@possexcluded) {
13760:                 foreach my $id (sort(@possexcluded)) {
13761:                     if ($serverhomes{$id}) {
13762:                         push(@excluded,$id);
13763:                     }
13764:                 }
13765:             }
13766:             if (@excluded) {
13767:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
13768:             }
13769:         } elsif ($item eq 'weights') {
13770:             foreach my $type ('E','W','N') {
13771:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
13772:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
13773:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
13774:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
13775:                             $env{'form.error'.$item.'_'.$type};
13776:                     }
13777:                 }
13778:             }
13779:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
13780:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
13781:             if ($env{'form.error'.$item} =~ /^\d+$/) {
13782:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
13783:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
13784:                 }
13785:             }
13786:         }
13787:     }
13788:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
13789:         foreach my $field (@{$fields}) {
13790:             if (ref($possoptions->{$field}) eq 'ARRAY') {
13791:                 my $value = $env{'form.helpform_'.$field};
13792:                 $value =~ s/^\s+|\s+$//g;
13793:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
13794:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
13795:                     if ($field eq 'screenshot') {
13796:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
13797:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
13798:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
13799:                         }
13800:                     }
13801:                 }
13802:             }
13803:         }
13804:     }
13805:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13806:     my (@statuses,%usertypeshash,@overrides);
13807:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
13808:         @statuses = @{$types};
13809:         if (ref($usertypes) eq 'HASH') {
13810:             %usertypeshash = %{$usertypes};
13811:         }
13812:     }
13813:     if (@statuses) {
13814:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
13815:         foreach my $type (@possoverrides) {
13816:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
13817:                 push(@overrides,$type);
13818:             }
13819:         }
13820:         if (@overrides) {
13821:             foreach my $type (@overrides) {
13822:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
13823:                 foreach my $item (@contacts) {
13824:                     if (grep(/^\Q$item\E$/,@standard)) {
13825:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
13826:                         $newsetting{'override_'.$type}{$item} = 1;
13827:                     } else {
13828:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
13829:                         $newsetting{'override_'.$type}{$item} = 0;
13830:                     }
13831:                 }
13832:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
13833:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
13834:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
13835:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
13836:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
13837:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
13838:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
13839:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
13840:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
13841:                 }
13842:             }     
13843:         }
13844:     }
13845:     if (keys(%currsetting) > 0) {
13846:         foreach my $item (@contacts) {
13847:             if ($to{$item} ne $currsetting{$item}) {
13848:                 $changes{$item} = 1;
13849:             }
13850:         }
13851:         foreach my $type (@mailings) {
13852:             foreach my $item (@contacts) {
13853:                 if (ref($currsetting{$type}) eq 'HASH') {
13854:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
13855:                         push(@{$changes{$type}},$item);
13856:                     }
13857:                 } else {
13858:                     push(@{$changes{$type}},@{$newsetting{$type}});
13859:                 }
13860:             }
13861:             if ($others{$type} ne $currsetting{$type}{'others'}) {
13862:                 push(@{$changes{$type}},'others');
13863:             }
13864:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
13865:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
13866:                     push(@{$changes{$type}},'bcc'); 
13867:                 }
13868:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
13869:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
13870:                     push(@{$changes{$type}},'include');
13871:                 }
13872:             }
13873:         }
13874:         if (ref($fields) eq 'ARRAY') {
13875:             if (ref($currsetting{'helpform'}) eq 'HASH') {
13876:                 foreach my $field (@{$fields}) {
13877:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
13878:                         push(@{$changes{'helpform'}},$field);
13879:                     }
13880:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
13881:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
13882:                             push(@{$changes{'helpform'}},'maxsize');
13883:                         }
13884:                     }
13885:                 }
13886:             } else {
13887:                 foreach my $field (@{$fields}) {
13888:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
13889:                         push(@{$changes{'helpform'}},$field);
13890:                     }
13891:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
13892:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
13893:                             push(@{$changes{'helpform'}},'maxsize');
13894:                         }
13895:                     }
13896:                 }
13897:             }
13898:         }
13899:         if (@statuses) {
13900:             if (ref($currsetting{'overrides'}) eq 'HASH') { 
13901:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
13902:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
13903:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
13904:                             foreach my $item (@contacts,'bcc','others','include') {
13905:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) { 
13906:                                     push(@{$changes{'overrides'}},$key);
13907:                                     last;
13908:                                 }
13909:                             }
13910:                         } else {
13911:                             push(@{$changes{'overrides'}},$key);
13912:                         }
13913:                     }
13914:                 }
13915:                 foreach my $key (@overrides) {
13916:                     unless (exists($currsetting{'overrides'}{$key})) {
13917:                         push(@{$changes{'overrides'}},$key);
13918:                     }
13919:                 }
13920:             } else {
13921:                 foreach my $key (@overrides) {
13922:                     push(@{$changes{'overrides'}},$key); 
13923:                 }
13924:             }
13925:         }
13926:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
13927:             foreach my $key ('excluded','weights','threshold','sysmail') {
13928:                 if ($key eq 'excluded') {
13929:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
13930:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
13931:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
13932:                             (@{$currsetting{'lonstatus'}{$key}})) {
13933:                             my @diffs =
13934:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
13935:                                                                    $currsetting{'lonstatus'}{$key});
13936:                             if (@diffs) {
13937:                                 push(@{$changes{'lonstatus'}},$key);
13938:                             }
13939:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
13940:                             push(@{$changes{'lonstatus'}},$key);
13941:                         }
13942:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
13943:                              (@{$currsetting{'lonstatus'}{$key}})) {
13944:                         push(@{$changes{'lonstatus'}},$key);
13945:                     }
13946:                 } elsif ($key eq 'weights') {
13947:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
13948:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
13949:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
13950:                             foreach my $type ('E','W','N','U') {
13951:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
13952:                                         $currsetting{'lonstatus'}{$key}{$type}) {
13953:                                     push(@{$changes{'lonstatus'}},$key);
13954:                                     last;
13955:                                 }
13956:                             }
13957:                         } else {
13958:                             foreach my $type ('E','W','N','U') {
13959:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
13960:                                     push(@{$changes{'lonstatus'}},$key);
13961:                                     last;
13962:                                 }
13963:                             }
13964:                         }
13965:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
13966:                         foreach my $type ('E','W','N','U') {
13967:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
13968:                                 push(@{$changes{'lonstatus'}},$key);
13969:                                 last;
13970:                             }
13971:                         }
13972:                     }
13973:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
13974:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
13975:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
13976:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
13977:                                 push(@{$changes{'lonstatus'}},$key);
13978:                             }
13979:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
13980:                             push(@{$changes{'lonstatus'}},$key);
13981:                         }
13982:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
13983:                         push(@{$changes{'lonstatus'}},$key);
13984:                     }
13985:                 }
13986:             }
13987:         } else {
13988:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
13989:                 foreach my $key ('excluded','weights','threshold','sysmail') {
13990:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
13991:                         push(@{$changes{'lonstatus'}},$key);
13992:                     }
13993:                 }
13994:             }
13995:         }
13996:     } else {
13997:         my %default;
13998:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
13999:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
14000:         $default{'errormail'} = 'adminemail';
14001:         $default{'packagesmail'} = 'adminemail';
14002:         $default{'helpdeskmail'} = 'supportemail';
14003:         $default{'otherdomsmail'} = 'supportemail';
14004:         $default{'lonstatusmail'} = 'adminemail';
14005:         $default{'requestsmail'} = 'adminemail';
14006:         $default{'updatesmail'} = 'adminemail';
14007:         $default{'hostipmail'} = 'adminemail';
14008:         foreach my $item (@contacts) {
14009:            if ($to{$item} ne $default{$item}) {
14010:                $changes{$item} = 1;
14011:            }
14012:         }
14013:         foreach my $type (@mailings) {
14014:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
14015:                 push(@{$changes{$type}},@{$newsetting{$type}});
14016:             }
14017:             if ($others{$type} ne '') {
14018:                 push(@{$changes{$type}},'others');
14019:             }
14020:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
14021:                 if ($bcc{$type} ne '') {
14022:                     push(@{$changes{$type}},'bcc');
14023:                 }
14024:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
14025:                     push(@{$changes{$type}},'include');
14026:                 }
14027:             }
14028:         }
14029:         if (ref($fields) eq 'ARRAY') {
14030:             foreach my $field (@{$fields}) {
14031:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
14032:                     push(@{$changes{'helpform'}},$field);
14033:                 }
14034:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
14035:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
14036:                         push(@{$changes{'helpform'}},'maxsize');
14037:                     }
14038:                 }
14039:             }
14040:         }
14041:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
14042:             foreach my $key ('excluded','weights','threshold','sysmail') {
14043:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
14044:                     push(@{$changes{'lonstatus'}},$key);
14045:                 }
14046:             }
14047:         }
14048:     }
14049:     foreach my $item (@toggles) {
14050:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
14051:             $changes{$item} = 1;
14052:         } elsif ((!$env{'form.'.$item}) &&
14053:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
14054:             $changes{$item} = 1;
14055:         }
14056:     }
14057:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
14058:                                              $dom);
14059:     if ($putresult eq 'ok') {
14060:         if (keys(%changes) > 0) {
14061:             &Apache::loncommon::devalidate_domconfig_cache($dom);
14062:             if (ref($lastactref) eq 'HASH') {
14063:                 $lastactref->{'domainconfig'} = 1;
14064:             }
14065:             my ($titles,$short_titles)  = &contact_titles();
14066:             $resulttext = &mt('Changes made:').'<ul>';
14067:             foreach my $item (@contacts) {
14068:                 if ($changes{$item}) {
14069:                     $resulttext .= '<li>'.$titles->{$item}.
14070:                                     &mt(' set to: ').
14071:                                     '<span class="LC_cusr_emph">'.
14072:                                     $to{$item}.'</span></li>';
14073:                 }
14074:             }
14075:             foreach my $type (@mailings) {
14076:                 if (ref($changes{$type}) eq 'ARRAY') {
14077:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
14078:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
14079:                     } else {
14080:                         $resulttext .= '<li>'.$titles->{$type}.': ';
14081:                     }
14082:                     my @text;
14083:                     foreach my $item (@{$newsetting{$type}}) {
14084:                         push(@text,$short_titles->{$item});
14085:                     }
14086:                     if ($others{$type} ne '') {
14087:                         push(@text,$others{$type});
14088:                     }
14089:                     if (@text) {
14090:                         $resulttext .= '<span class="LC_cusr_emph">'.
14091:                                        join(', ',@text).'</span>';
14092:                     }
14093:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
14094:                         if ($bcc{$type} ne '') {
14095:                             my $bcctext;
14096:                             if (@text) {
14097:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
14098:                             } else {
14099:                                 $bcctext = '(Bcc)';
14100:                             }
14101:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
14102:                         } elsif (!@text) {
14103:                             $resulttext .= &mt('No one');
14104:                         }   
14105:                         if ($includestr{$type} ne '') {
14106:                             if ($includeloc{$type} eq 'b') {
14107:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
14108:                             } elsif ($includeloc{$type} eq 's') {
14109:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
14110:                             }
14111:                         }
14112:                     } elsif (!@text) {
14113:                         $resulttext .= &mt('No recipients');
14114:                     }
14115:                     $resulttext .= '</li>';
14116:                 }
14117:             }
14118:             if (ref($changes{'overrides'}) eq 'ARRAY') {
14119:                 my @deletions;
14120:                 foreach my $type (@{$changes{'overrides'}}) {
14121:                     if ($usertypeshash{$type}) {
14122:                         if (grep(/^\Q$type\E/,@overrides)) {
14123:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
14124:                                                       $usertypeshash{$type}).'<ul><li>';
14125:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
14126:                                 my @text;
14127:                                 foreach my $item (@contacts) {
14128:                                     if ($newsetting{'override_'.$type}{$item}) { 
14129:                                         push(@text,$short_titles->{$item});
14130:                                     }
14131:                                 }
14132:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
14133:                                     push(@text,$newsetting{'override_'.$type}{'others'});
14134:                                 }
14135:   
14136:                                 if (@text) {
14137:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
14138:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
14139:                                 }
14140:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
14141:                                     my $bcctext;
14142:                                     if (@text) {
14143:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
14144:                                     } else {
14145:                                         $bcctext = '(Bcc)';
14146:                                     }
14147:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
14148:                                 } elsif (!@text) {
14149:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
14150:                                 }
14151:                                 $resulttext .= '</li>';
14152:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
14153:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
14154:                                     if ($loc eq 'b') {
14155:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
14156:                                     } elsif ($loc eq 's') {
14157:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
14158:                                     }
14159:                                 }
14160:                             }
14161:                             $resulttext .= '</li></ul></li>';
14162:                         } else {
14163:                             push(@deletions,$usertypeshash{$type});
14164:                         }
14165:                     }
14166:                 }
14167:                 if (@deletions) {
14168:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
14169:                                               join(', ',@deletions)).'</li>';
14170:                 }
14171:             }
14172:             my @offon = ('off','on');
14173:             my $corelink = &core_link_msu();
14174:             if ($changes{'reporterrors'}) {
14175:                 $resulttext .= '<li>'.
14176:                                &mt('E-mail error reports to [_1] set to "'.
14177:                                    $offon[$env{'form.reporterrors'}].'".',
14178:                                    $corelink).
14179:                                '</li>';
14180:             }
14181:             if ($changes{'reportupdates'}) {
14182:                 $resulttext .= '<li>'.
14183:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
14184:                                     $offon[$env{'form.reportupdates'}].'".',
14185:                                     $corelink).
14186:                                 '</li>';
14187:             }
14188:             if ($changes{'reportstatus'}) {
14189:                 $resulttext .= '<li>'.
14190:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
14191:                                     $offon[$env{'form.reportstatus'}].'".',
14192:                                     $corelink).
14193:                                 '</li>';
14194:             }
14195:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
14196:                 $resulttext .= '<li>'.
14197:                                &mt('Nightly status check e-mail settings').':<ul>';
14198:                 my (%defval,%use_def,%shown);
14199:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
14200:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
14201:                 $defval{'weights'} =
14202:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
14203:                 $defval{'excluded'} = &mt('None');
14204:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
14205:                     foreach my $item ('threshold','sysmail','weights','excluded') {
14206:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
14207:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
14208:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
14209:                             } elsif ($item eq 'weights') {
14210:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
14211:                                     foreach my $type ('E','W','N','U') {
14212:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
14213:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
14214:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
14215:                                         } else {
14216:                                             $shown{$item} .= $lonstatus_defs->{$type};
14217:                                         }
14218:                                         $shown{$item} .= ', ';
14219:                                     }
14220:                                     $shown{$item} =~ s/, $//;
14221:                                 } else {
14222:                                     $shown{$item} = $defval{$item};
14223:                                 }
14224:                             } elsif ($item eq 'excluded') {
14225:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
14226:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
14227:                                 } else {
14228:                                     $shown{$item} = $defval{$item};
14229:                                 }
14230:                             }
14231:                         } else {
14232:                             $shown{$item} = $defval{$item};
14233:                         }
14234:                     }
14235:                 } else {
14236:                     foreach my $item ('threshold','weights','excluded','sysmail') {
14237:                         $shown{$item} = $defval{$item};
14238:                     }
14239:                 }
14240:                 foreach my $item ('threshold','weights','excluded','sysmail') {
14241:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
14242:                                           $shown{$item}).'</li>';
14243:                 }
14244:                 $resulttext .= '</ul></li>';
14245:             }
14246:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
14247:                 my (@optional,@required,@unused,$maxsizechg);
14248:                 foreach my $field (@{$changes{'helpform'}}) {
14249:                     if ($field eq 'maxsize') {
14250:                         $maxsizechg = 1;
14251:                         next;
14252:                     }
14253:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
14254:                         push(@optional,$field);
14255:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
14256:                         push(@unused,$field);
14257:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
14258:                         push(@required,$field);
14259:                     }
14260:                 }
14261:                 if (@optional) {
14262:                     $resulttext .= '<li>'.
14263:                                    &mt('Help form fields changed to "Optional": [_1].',
14264:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
14265:                                    '</li>';
14266:                 }
14267:                 if (@required) {
14268:                     $resulttext .= '<li>'.
14269:                                    &mt('Help form fields changed to "Required": [_1].',
14270:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
14271:                                    '</li>';
14272:                 }
14273:                 if (@unused) {
14274:                     $resulttext .= '<li>'.
14275:                                    &mt('Help form fields changed to "Not shown": [_1].',
14276:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
14277:                                    '</li>';
14278:                 }
14279:                 if ($maxsizechg) {
14280:                     $resulttext .= '<li>'.
14281:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
14282:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
14283:                                    '</li>';
14284:                 }
14285:             }
14286:             $resulttext .= '</ul>';
14287:         } else {
14288:             $resulttext = &mt('No changes made to contacts and form settings');
14289:         }
14290:     } else {
14291:         $resulttext = '<span class="LC_error">'.
14292:             &mt('An error occurred: [_1].',$putresult).'</span>';
14293:     }
14294:     return $resulttext;
14295: }
14296: 
14297: sub modify_privacy {
14298:     my ($dom,%domconfig) = @_;
14299:     my ($resulttext,%current,%changes);
14300:     if (ref($domconfig{'privacy'}) eq 'HASH') {
14301:         %current = %{$domconfig{'privacy'}};
14302:     }
14303:     my @fields = ('lastname','firstname','middlename','generation','permanentemail','id');
14304:     my @items = ('domain','author','course','community');
14305:     my %names = &Apache::lonlocal::texthash (
14306:                    domain => 'Assigned domain role(s)',
14307:                    author => 'Assigned co-author role(s)',
14308:                    course => 'Assigned course role(s)',
14309:                    community => 'Assigned community role',
14310:                 );
14311:     my %roles = &Apache::lonlocal::texthash (
14312:                    domain => 'Domain role',
14313:                    author => 'Co-author role',
14314:                    course => 'Course role',
14315:                    community => 'Community role',
14316:                 );
14317:     my %titles = &Apache::lonlocal::texthash (
14318:                   approval => 'Approval for role in different domain',
14319:                   othdom   => 'User information available in other domain',
14320:                   priv     => 'Information viewable by privileged user in same domain',
14321:                   unpriv   => 'Information viewable by unprivileged user in same domain',
14322:                   instdom  => 'Other domain shares institution/provider',
14323:                   extdom   => 'Other domain has different institution/provider',
14324:                   none     => 'Not allowed',
14325:                   user     => 'User authorizes',
14326:                   domain   => 'Domain Coordinator authorizes',
14327:                   auto     => 'Unrestricted',
14328:     );
14329:     my %fieldnames = &Apache::lonlocal::texthash (
14330:                         id => 'Student/Employee ID',
14331:                         permanentemail => 'E-mail address',
14332:                         lastname => 'Last Name',
14333:                         firstname => 'First Name',
14334:                         middlename => 'Middle Name',
14335:                         generation => 'Generation',
14336:     );
14337:     my ($othertitle,$usertypes,$types) =
14338:         &Apache::loncommon::sorted_inst_types($dom);
14339:     my (%by_ip,%by_location,@intdoms,@instdoms);
14340:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
14341: 
14342:     my %privacyhash = (
14343:                        'approval' => {
14344:                                        instdom => {},
14345:                                        extdom  => {},
14346:                                      },
14347:                        'othdom'   => {},
14348:                        'priv'     => {},
14349:                        'unpriv'   => {},
14350:                       );
14351:     foreach my $item (@items) {
14352:         if (@instdoms > 1) {
14353:             if ($env{'form.privacy_approval_instdom'.$item} =~ /^(none|user|domain|auto)$/) {
14354:                 $privacyhash{'approval'}{'instdom'}{$item} = $env{'form.privacy_approval_instdom_'.$item};
14355:             }
14356:             if (ref($current{'approval'}) eq 'HASH') {
14357:                 if (ref($current{'approval'}{'instdom'}) eq 'HASH') {
14358:                     unless ($privacyhash{'approval'}{'instdom'}{$item} eq $current{'approval'}{'instdom'}{$item}) {
14359:                         $changes{'approval'} = 1;
14360:                     }
14361:                 }
14362:             } elsif ($privacyhash{'approval'}{'instdom'}{$item} ne 'auto') {
14363:                 $changes{'approval'} = 1;
14364:             }
14365:         }
14366:         if (keys(%by_location) > 0) {
14367:             if ($env{'form.privacy_approval_extdom_'.$item} =~ /^(none|user|domain|auto)$/) {
14368:                 $privacyhash{'approval'}{'extdom'}{$item} = $env{'form.privacy_approval_extdom_'.$item};
14369:             }
14370:             if (ref($current{'approval'}) eq 'HASH') {
14371:                 if (ref($current{'approval'}{'extdom'}) eq 'HASH') {
14372:                     unless ($privacyhash{'approval'}{'extdom'}{$item} eq $current{'approval'}{'extdom'}{$item}) {
14373:                         $changes{'approval'} = 1;
14374:                     }
14375:                 }
14376:             } elsif ($privacyhash{'approval'}{'extdom'}{$item} ne 'auto') {
14377:                 $changes{'approval'} = 1;
14378:             }
14379:         }
14380:         foreach my $status ('priv','unpriv') {
14381:             my @possibles = sort(&Apache::loncommon::get_env_multiple('form.privacy_'.$status.'_'.$item));
14382:             my @newvalues;
14383:             foreach my $field (@possibles) {
14384:                 if (grep(/^\Q$field\E$/,@fields)) {
14385:                     $privacyhash{$status}{$item}{$field} = 1;
14386:                     push(@newvalues,$field);
14387:                 }
14388:             }
14389:             @newvalues = sort(@newvalues);
14390:             if (ref($current{$status}) eq 'HASH') {
14391:                 if (ref($current{$status}{$item}) eq 'HASH') {
14392:                     my @currvalues = sort(keys(%{$current{$status}{$item}}));
14393:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
14394:                     if (@diffs > 0) {
14395:                         $changes{$status} = 1;
14396:                     }
14397:                 }
14398:             } else {
14399:                 my @stdfields;
14400:                 foreach my $field (@fields) {
14401:                     if ($field eq 'id') {
14402:                         next if ($status eq 'unpriv');
14403:                         next if (($status eq 'priv') && ($item eq 'community'));
14404:                     }
14405:                     push(@stdfields,$field);
14406:                 }
14407:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
14408:                 if (@diffs > 0) {
14409:                     $changes{$status} = 1;
14410:                 }
14411:             }
14412:         }
14413:     }
14414:     if ((@instdoms > 1) || (keys(%by_location) > 0)) {
14415:         my @statuses;
14416:         if (ref($types) eq 'ARRAY') {
14417:             @statuses = @{$types};
14418:         }
14419:         foreach my $type (@statuses,'default') {
14420:             my @possfields = &Apache::loncommon::get_env_multiple('form.privacy_othdom_'.$type);
14421:             my @newvalues;
14422:             foreach my $field (sort(@possfields)) {
14423:                 if (grep(/^\Q$field\E$/,@fields)) {
14424:                     $privacyhash{'othdom'}{$type}{$field} = 1;
14425:                     push(@newvalues,$field);
14426:                 }
14427:             }
14428:             @newvalues = sort(@newvalues);
14429:             if (ref($current{'othdom'}) eq 'HASH') {
14430:                 if (ref($current{'othdom'}{$type}) eq 'HASH') {
14431:                     my @currvalues = sort(keys(%{$current{'othdom'}{$type}}));
14432:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
14433:                     if (@diffs > 0) {
14434:                         $changes{'othdom'} = 1;
14435:                     }
14436:                 }
14437:             } else {
14438:                 my @stdfields = ('lastname','firstname','middlename','generation','permanentemail');
14439:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
14440:                 if (@diffs > 0) {
14441:                     $changes{'othdom'} = 1;
14442:                 }
14443:             }
14444:         }
14445:     }
14446:     my %confighash = (
14447:                         privacy => \%privacyhash,
14448:                      );
14449:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
14450:     if ($putresult eq 'ok') {
14451:         if (keys(%changes) > 0) {
14452:             $resulttext = &mt('Changes made: ').'<ul>';
14453:             foreach my $key ('approval','othdom','priv','unpriv') {
14454:                 if ($changes{$key}) {
14455:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
14456:                     if ($key eq 'approval') {
14457:                         if (keys(%{$privacyhash{$key}{instdom}})) {
14458:                             $resulttext .= '<li>'.$titles{'instdom'}.'<ul>';
14459:                             foreach my $item (@items) {
14460:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{instdom}{$item}}.'</li>';
14461:                             }
14462:                             $resulttext .= '</ul></li>';
14463:                         }
14464:                         if (keys(%{$privacyhash{$key}{extdom}})) {
14465:                             $resulttext .= '<li>'.$titles{'extdom'}.'<ul>';
14466:                             foreach my $item (@items) {
14467:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{extdom}{$item}}.'</li>';
14468:                             }
14469:                             $resulttext .= '</ul></li>';
14470:                         }
14471:                     } elsif ($key eq 'othdom') {
14472:                         my @statuses;
14473:                         if (ref($types) eq 'ARRAY') {
14474:                             @statuses = @{$types};
14475:                         }
14476:                         if (ref($privacyhash{$key}) eq 'HASH') {
14477:                             foreach my $status (@statuses,'default') {
14478:                                 if ($status eq 'default') {
14479:                                     $resulttext .= '<li>'.$othertitle.': ';
14480:                                 } elsif (ref($usertypes) eq 'HASH') {
14481:                                     $resulttext .= '<li>'.$usertypes->{$status}.': ';
14482:                                 } else {
14483:                                     next;
14484:                                 }
14485:                                 if (ref($privacyhash{$key}{$status}) eq 'HASH') {
14486:                                     if (keys(%{$privacyhash{$key}{$status}})) {
14487:                                         $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$status}}))));
14488:                                     } else {
14489:                                         $resulttext .= &mt('none');
14490:                                     }
14491:                                 }
14492:                                 $resulttext .= '</li>';
14493:                             }
14494:                         }
14495:                     } else {
14496:                         foreach my $item (@items) {
14497:                             if (ref($privacyhash{$key}{$item}) eq 'HASH') {
14498:                                 $resulttext .= '<li>'.$names{$item}.': ';
14499:                                 if (keys(%{$privacyhash{$key}{$item}})) {
14500:                                     $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$item}}))));
14501:                                 } else {
14502:                                     $resulttext .= &mt('none');
14503:                                 }
14504:                                 $resulttext .= '</li>';
14505:                             }
14506:                         }
14507:                     }
14508:                     $resulttext .= '</ul></li>';
14509:                 }
14510:             }
14511:         } else {
14512:             $resulttext = &mt('No changes made to user information settings');
14513:         }
14514:     } else {
14515:         $resulttext = '<span class="LC_error">'.
14516:             &mt('An error occurred: [_1]',$putresult).'</span>';
14517:     }
14518:     return $resulttext;
14519: }
14520: 
14521: sub modify_passwords {
14522:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
14523:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
14524:         $updatedefaults,$updateconf);
14525:     my $customfn = 'resetpw.html';
14526:     if (ref($domconfig{'passwords'}) eq 'HASH') {
14527:         %current = %{$domconfig{'passwords'}};
14528:     }
14529:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14530:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
14531:     if (ref($types) eq 'ARRAY') {
14532:         @oktypes = @{$types};
14533:     }
14534:     push(@oktypes,'default');
14535: 
14536:     my %titles = &Apache::lonlocal::texthash (
14537:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
14538:         intauth_check  => 'Check bcrypt cost if authenticated',
14539:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
14540:         permanent      => 'Permanent e-mail address',
14541:         critical       => 'Critical notification address',
14542:         notify         => 'Notification address',
14543:         min            => 'Minimum password length',
14544:         max            => 'Maximum password length',
14545:         chars          => 'Required characters',
14546:         expire         => 'Password expiration (days)',
14547:         numsaved       => 'Number of previous passwords to save',
14548:         reset          => 'Resetting Forgotten Password',
14549:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
14550:         rules          => 'Rules for LON-CAPA Passwords',
14551:         crsownerchg    => 'Course Owner Changing Student Passwords',
14552:         username       => 'Username',
14553:         email          => 'E-mail address',
14554:     );
14555: 
14556: #
14557: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
14558: #
14559:     my (%curr_defaults,%save_defaults);
14560:     if (ref($domconfig{'defaults'}) eq 'HASH') {
14561:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
14562:             if ($key =~ /^intauth_(cost|check|switch)$/) {
14563:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
14564:             } else {
14565:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
14566:             }
14567:         }
14568:     }
14569:     my %staticdefaults = (
14570:         'resetlink'      => 2,
14571:         'resetcase'      => \@oktypes,
14572:         'resetprelink'   => 'both',
14573:         'resetemail'     => ['critical','notify','permanent'],
14574:         'intauth_cost'   => 10,
14575:         'intauth_check'  => 0,
14576:         'intauth_switch' => 0,
14577:     );
14578:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
14579:     foreach my $type (@oktypes) {
14580:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
14581:     }
14582:     my $linklife = $env{'form.passwords_link'};
14583:     $linklife =~ s/^\s+|\s+$//g;
14584:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
14585:         $newvalues{'resetlink'} = $linklife;
14586:         if ($current{'resetlink'}) {
14587:             if ($current{'resetlink'} ne $linklife) {
14588:                 $changes{'reset'} = 1;
14589:             }
14590:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
14591:             if ($staticdefaults{'resetlink'} ne $linklife) {
14592:                 $changes{'reset'} = 1;
14593:             }
14594:         }
14595:     } elsif ($current{'resetlink'}) {
14596:         $changes{'reset'} = 1;
14597:     }
14598:     my @casesens;
14599:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
14600:     foreach my $case (sort(@posscase)) {
14601:         if (grep(/^\Q$case\E$/,@oktypes)) {
14602:             push(@casesens,$case);
14603:         }
14604:     }
14605:     $newvalues{'resetcase'} = \@casesens;
14606:     if (ref($current{'resetcase'}) eq 'ARRAY') {
14607:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
14608:         if (@diffs > 0) {
14609:             $changes{'reset'} = 1;
14610:         }
14611:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
14612:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
14613:         if (@diffs > 0) {
14614:             $changes{'reset'} = 1;
14615:         }
14616:     }
14617:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
14618:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
14619:         if (exists($current{'resetprelink'})) {
14620:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
14621:                 $changes{'reset'} = 1;
14622:             }
14623:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
14624:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
14625:                 $changes{'reset'} = 1;
14626:             }
14627:         }
14628:     } elsif ($current{'resetprelink'}) {
14629:         $changes{'reset'} = 1;
14630:     }
14631:     foreach my $type (@oktypes) {
14632:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
14633:         my @postlink;
14634:         foreach my $item (sort(@possplink)) {
14635:             if ($item =~ /^(email|username)$/) {
14636:                 push(@postlink,$item);
14637:             }
14638:         }
14639:         $newvalues{'resetpostlink'}{$type} = \@postlink;
14640:         unless ($changes{'reset'}) {
14641:             if (ref($current{'resetpostlink'}) eq 'HASH') {
14642:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
14643:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
14644:                     if (@diffs > 0) {
14645:                         $changes{'reset'} = 1;
14646:                     }
14647:                 } else {
14648:                     $changes{'reset'} = 1;
14649:                 }
14650:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
14651:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
14652:                 if (@diffs > 0) {
14653:                     $changes{'reset'} = 1;
14654:                 }
14655:             }
14656:         }
14657:     }
14658:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
14659:     my @resetemail;
14660:     foreach my $item (sort(@possemailsrc)) {
14661:         if ($item =~ /^(permanent|critical|notify)$/) {
14662:             push(@resetemail,$item);
14663:         }
14664:     }
14665:     $newvalues{'resetemail'} = \@resetemail;
14666:     unless ($changes{'reset'}) {
14667:         if (ref($current{'resetemail'}) eq 'ARRAY') {
14668:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
14669:             if (@diffs > 0) {
14670:                 $changes{'reset'} = 1;
14671:             }
14672:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
14673:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
14674:             if (@diffs > 0) {
14675:                 $changes{'reset'} = 1;
14676:             }
14677:         }
14678:     }
14679:     if ($env{'form.passwords_stdtext'} == 0) {
14680:         $newvalues{'resetremove'} = 1;
14681:         unless ($current{'resetremove'}) {
14682:             $changes{'reset'} = 1;
14683:         }
14684:     } elsif ($current{'resetremove'}) {
14685:         $changes{'reset'} = 1;
14686:     }
14687:     if ($env{'form.passwords_customfile.filename'} ne '') {
14688:         my $servadm = $r->dir_config('lonAdmEMail');
14689:         my ($configuserok,$author_ok,$switchserver) =
14690:             &config_check($dom,$confname,$servadm);
14691:         my $error;
14692:         if ($configuserok eq 'ok') {
14693:             if ($switchserver) {
14694:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
14695:             } else {
14696:                 if ($author_ok eq 'ok') {
14697:                     my ($result,$customurl) =
14698:                         &publishlogo($r,'upload','passwords_customfile',$dom,
14699:                                      $confname,'customtext/resetpw','','',$customfn);
14700:                     if ($result eq 'ok') {
14701:                         $newvalues{'resetcustom'} = $customurl;
14702:                         $changes{'reset'} = 1;
14703:                     } else {
14704:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
14705:                     }
14706:                 } else {
14707:                     $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);
14708:                 }
14709:             }
14710:         } else {
14711:             $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);
14712:         }
14713:         if ($error) {
14714:             &Apache::lonnet::logthis($error);
14715:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14716:         }
14717:     } elsif ($current{'resetcustom'}) {
14718:         if ($env{'form.passwords_custom_del'}) {
14719:             $changes{'reset'} = 1;
14720:         } else {
14721:             $newvalues{'resetcustom'} = $current{'resetcustom'};
14722:         }
14723:     }
14724:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
14725:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
14726:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
14727:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
14728:             $changes{'intauth'} = 1;
14729:         }
14730:     } else {
14731:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
14732:     }
14733:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
14734:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
14735:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
14736:             $changes{'intauth'} = 1;
14737:         }
14738:     } else {
14739:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
14740:     }
14741:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
14742:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
14743:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
14744:             $changes{'intauth'} = 1;
14745:         }
14746:     } else {
14747:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
14748:     }
14749:     foreach my $item ('cost','check','switch') {
14750:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
14751:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
14752:             $updatedefaults = 1;
14753:         }
14754:     }
14755:     foreach my $rule ('min','max','expire','numsaved') {
14756:         $env{'form.passwords_'.$rule} =~ s/^\s+|\s+$//g;
14757:         my $ruleok;
14758:         if ($rule eq 'expire') {
14759:             if (($env{'form.passwords_'.$rule} =~ /^\d+(|\.\d*)$/) &&
14760:                 ($env{'form.passwords_'.$rule} ne '0')) {
14761:                 $ruleok = 1;
14762:             }
14763:         } elsif ($rule eq 'min') {
14764:             if ($env{'form.passwords_'.$rule} =~ /^\d+$/) {
14765:                 if ($env{'form.passwords_'.$rule} >= $Apache::lonnet::passwdmin) {
14766:                     $ruleok = 1;
14767:                 }
14768:             }
14769:         } elsif (($env{'form.passwords_'.$rule} =~ /^\d+$/) &&
14770:                  ($env{'form.passwords_'.$rule} ne '0')) {
14771:             $ruleok = 1;
14772:         }
14773:         if ($ruleok) {
14774:             $newvalues{$rule} = $env{'form.passwords_'.$rule};
14775:             if (exists($current{$rule})) {
14776:                 if ($newvalues{$rule} ne $current{$rule}) {
14777:                     $changes{'rules'} = 1;
14778:                 }
14779:             } elsif ($rule eq 'min') {
14780:                 if ($staticdefaults{$rule} ne $newvalues{$rule}) {
14781:                     $changes{'rules'} = 1;
14782:                 }
14783:             } else {
14784:                 $changes{'rules'} = 1;
14785:             }
14786:         } elsif (exists($current{$rule})) {
14787:             $changes{'rules'} = 1;
14788:         }
14789:     }
14790:     my @posschars = &Apache::loncommon::get_env_multiple('form.passwords_chars');
14791:     my @chars;
14792:     foreach my $item (sort(@posschars)) {
14793:         if ($item =~ /^(uc|lc|num|spec)$/) {
14794:             push(@chars,$item);
14795:         }
14796:     }
14797:     $newvalues{'chars'} = \@chars;
14798:     unless ($changes{'rules'}) {
14799:         if (ref($current{'chars'}) eq 'ARRAY') {
14800:             my @diffs = &Apache::loncommon::compare_arrays($current{'chars'},\@chars);
14801:             if (@diffs > 0) {
14802:                 $changes{'rules'} = 1;
14803:             }
14804:         } else {
14805:             if (@chars > 0) {
14806:                 $changes{'rules'} = 1;
14807:             }
14808:         }
14809:     }
14810:     my %crsownerchg = (
14811:                         by => [],
14812:                         for => [],
14813:                       );
14814:     foreach my $item ('by','for') {
14815:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
14816:         foreach my $type (sort(@posstypes)) {
14817:             if (grep(/^\Q$type\E$/,@oktypes)) {
14818:                 push(@{$crsownerchg{$item}},$type);
14819:             }
14820:         }
14821:     }
14822:     $newvalues{'crsownerchg'} = \%crsownerchg;
14823:     if (ref($current{'crsownerchg'}) eq 'HASH') {
14824:         foreach my $item ('by','for') {
14825:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
14826:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
14827:                 if (@diffs > 0) {
14828:                     $changes{'crsownerchg'} = 1;
14829:                     last;
14830:                 }
14831:             }
14832:         }
14833:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
14834:         foreach my $item ('by','for') {
14835:             if (@{$crsownerchg{$item}} > 0) {
14836:                 $changes{'crsownerchg'} = 1;
14837:                 last;
14838:             }
14839:         }
14840:     }
14841: 
14842:     my %confighash = (
14843:                         defaults  => \%save_defaults,
14844:                         passwords => \%newvalues,
14845:                      );
14846:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
14847: 
14848:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
14849:     if ($putresult eq 'ok') {
14850:         if (keys(%changes) > 0) {
14851:             $resulttext = &mt('Changes made: ').'<ul>';
14852:             foreach my $key ('reset','intauth','rules','crsownerchg') {
14853:                 if ($changes{$key}) {
14854:                     unless ($key eq 'intauth') {
14855:                         $updateconf = 1;
14856:                     }
14857:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
14858:                     if ($key eq 'reset') {
14859:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
14860:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
14861:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
14862:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
14863:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
14864:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
14865:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
14866:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
14867:                             }
14868:                         } else {
14869:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
14870:                         }
14871:                         if ($confighash{'passwords'}{'resetlink'}) {
14872:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
14873:                         } else {
14874:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
14875:                                                   &mt('Will default to 2 hours').'</li>';
14876:                         }
14877:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
14878:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
14879:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
14880:                             } else {
14881:                                 my $casesens;
14882:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
14883:                                     if ($type eq 'default') {
14884:                                         $casesens .= $othertitle.', ';
14885:                                     } elsif ($usertypes->{$type} ne '') {
14886:                                         $casesens .= $usertypes->{$type}.', ';
14887:                                     }
14888:                                 }
14889:                                 $casesens =~ s/\Q, \E$//;
14890:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
14891:                             }
14892:                         } else {
14893:                             $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>';
14894:                         }
14895:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
14896:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
14897:                         } else {
14898:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
14899:                         }
14900:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
14901:                             my $output;
14902:                             if (ref($types) eq 'ARRAY') {
14903:                                 foreach my $type (@{$types}) {
14904:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
14905:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
14906:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
14907:                                         } else {
14908:                                             $output .= $usertypes->{$type}.' -- '.
14909:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
14910:                                         }
14911:                                     }
14912:                                 }
14913:                             }
14914:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
14915:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
14916:                                     $output .= $othertitle.' -- '.&mt('none');
14917:                                 } else {
14918:                                     $output .= $othertitle.' -- '.
14919:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
14920:                                 }
14921:                             }
14922:                             if ($output) {
14923:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
14924:                             } else {
14925:                                 $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>';
14926:                             }
14927:                         } else {
14928:                             $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>';
14929:                         }
14930:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
14931:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
14932:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
14933:                             } else {
14934:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
14935:                             }
14936:                         } else {
14937:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA usedfor verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
14938:                         }
14939:                         if ($confighash{'passwords'}{'resetremove'}) {
14940:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
14941:                         } else {
14942:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
14943:                         }
14944:                         if ($confighash{'passwords'}{'resetcustom'}) {
14945:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
14946:                                                                             &mt('custom text'),600,500,undef,undef,
14947:                                                                             undef,undef,'background-color:#ffffff');
14948:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
14949:                         } else {
14950:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
14951:                         }
14952:                     } elsif ($key eq 'intauth') {
14953:                         foreach my $item ('cost','switch','check') {
14954:                             my $value = $save_defaults{$key.'_'.$item};
14955:                             if ($item eq 'switch') {
14956:                                 my %optiondesc = &Apache::lonlocal::texthash (
14957:                                                      0 => 'No',
14958:                                                      1 => 'Yes',
14959:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
14960:                                                  );
14961:                                 if ($value =~ /^(0|1|2)$/) {
14962:                                     $value = $optiondesc{$value};
14963:                                 } else {
14964:                                     $value = &mt('none -- defaults to No');
14965:                                 }
14966:                             } elsif ($item eq 'check') {
14967:                                 my %optiondesc = &Apache::lonlocal::texthash (
14968:                                                      0 => 'No',
14969:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
14970:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
14971:                                                  );
14972:                                 if ($value =~ /^(0|1|2)$/) {
14973:                                     $value = $optiondesc{$value};
14974:                                 } else {
14975:                                     $value = &mt('none -- defaults to No');
14976:                                 }
14977:                             }
14978:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
14979:                         }
14980:                     } elsif ($key eq 'rules') {
14981:                         foreach my $rule ('min','max','expire','numsaved') {
14982:                             if ($confighash{'passwords'}{$rule} eq '') {
14983:                                 if ($rule eq 'min') {
14984:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
14985:                                                    ' '.&mt('Default of [_1] will be used',
14986:                                                            $Apache::lonnet::passwdmin).'</li>';
14987:                                 } else {
14988:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
14989:                                 }
14990:                             } else {
14991:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
14992:                             }
14993:                         }
14994:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
14995:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
14996:                                 my %rulenames = &Apache::lonlocal::texthash(
14997:                                                      uc => 'At least one upper case letter',
14998:                                                      lc => 'At least one lower case letter',
14999:                                                      num => 'At least one number',
15000:                                                      spec => 'At least one non-alphanumeric',
15001:                                                    );
15002:                                 my $needed = '<ul><li>'.
15003:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
15004:                                              '</li></ul>'; 
15005:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
15006:                             } else {
15007:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
15008:                             }
15009:                         } else {
15010:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
15011:                         }
15012:                     } elsif ($key eq 'crsownerchg') {
15013:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
15014:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
15015:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
15016:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
15017:                             } else {
15018:                                 my %crsownerstr;
15019:                                 foreach my $item ('by','for') {
15020:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
15021:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
15022:                                             if ($type eq 'default') {
15023:                                                 $crsownerstr{$item} .= $othertitle.', ';
15024:                                             } elsif ($usertypes->{$type} ne '') {
15025:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
15026:                                             }
15027:                                         }
15028:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
15029:                                     }
15030:                                 }
15031:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
15032:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
15033:                             }
15034:                         } else {
15035:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
15036:                         }
15037:                     }
15038:                     $resulttext .= '</ul></li>';
15039:                 }
15040:             }
15041:             $resulttext .= '</ul>';
15042:         } else {
15043:             $resulttext = &mt('No changes made to password settings');
15044:         }
15045:         my $cachetime = 24*60*60;
15046:         if ($updatedefaults) {
15047:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
15048:             if (ref($lastactref) eq 'HASH') {
15049:                 $lastactref->{'domdefaults'} = 1;
15050:             }
15051:         }
15052:         if ($updateconf) {
15053:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
15054:             if (ref($lastactref) eq 'HASH') {
15055:                 $lastactref->{'passwdconf'} = 1;
15056:             }
15057:         }
15058:     } else {
15059:         $resulttext = '<span class="LC_error">'.
15060:             &mt('An error occurred: [_1]',$putresult).'</span>';
15061:     }
15062:     if ($errors) {
15063:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
15064:                        $errors.'</ul></p>';
15065:     }
15066:     return $resulttext;
15067: }
15068: 
15069: sub modify_usercreation {
15070:     my ($dom,%domconfig) = @_;
15071:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
15072:     my $warningmsg;
15073:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
15074:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
15075:             if ($key eq 'cancreate') {
15076:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
15077:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
15078:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
15079:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
15080:                         } else {
15081:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
15082:                         }
15083:                     }
15084:                 }
15085:             } elsif ($key eq 'email_rule') {
15086:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
15087:             } else {
15088:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
15089:             }
15090:         }
15091:     }
15092:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
15093:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
15094:     my @contexts = ('author','course','requestcrs');
15095:     foreach my $item(@contexts) {
15096:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
15097:     }
15098:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
15099:         foreach my $item (@contexts) {
15100:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
15101:                 push(@{$changes{'cancreate'}},$item);
15102:             }
15103:         }
15104:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
15105:         foreach my $item (@contexts) {
15106:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
15107:                 if ($cancreate{$item} ne 'any') {
15108:                     push(@{$changes{'cancreate'}},$item);
15109:                 }
15110:             } else {
15111:                 if ($cancreate{$item} ne 'none') {
15112:                     push(@{$changes{'cancreate'}},$item);
15113:                 }
15114:             }
15115:         }
15116:     } else {
15117:         foreach my $item (@contexts)  {
15118:             push(@{$changes{'cancreate'}},$item);
15119:         }
15120:     }
15121: 
15122:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
15123:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
15124:             if (!grep(/^\Q$type\E$/,@username_rule)) {
15125:                 push(@{$changes{'username_rule'}},$type);
15126:             }
15127:         }
15128:         foreach my $type (@username_rule) {
15129:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
15130:                 push(@{$changes{'username_rule'}},$type);
15131:             }
15132:         }
15133:     } else {
15134:         push(@{$changes{'username_rule'}},@username_rule);
15135:     }
15136: 
15137:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
15138:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
15139:             if (!grep(/^\Q$type\E$/,@id_rule)) {
15140:                 push(@{$changes{'id_rule'}},$type);
15141:             }
15142:         }
15143:         foreach my $type (@id_rule) {
15144:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
15145:                 push(@{$changes{'id_rule'}},$type);
15146:             }
15147:         }
15148:     } else {
15149:         push(@{$changes{'id_rule'}},@id_rule);
15150:     }
15151: 
15152:     my @authen_contexts = ('author','course','domain');
15153:     my @authtypes = ('int','krb4','krb5','loc','lti');
15154:     my %authhash;
15155:     foreach my $item (@authen_contexts) {
15156:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
15157:         foreach my $auth (@authtypes) {
15158:             if (grep(/^\Q$auth\E$/,@authallowed)) {
15159:                 $authhash{$item}{$auth} = 1;
15160:             } else {
15161:                 $authhash{$item}{$auth} = 0;
15162:             }
15163:         }
15164:     }
15165:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
15166:         foreach my $item (@authen_contexts) {
15167:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
15168:                 foreach my $auth (@authtypes) {
15169:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
15170:                         push(@{$changes{'authtypes'}},$item);
15171:                         last;
15172:                     }
15173:                 }
15174:             }
15175:         }
15176:     } else {
15177:         foreach my $item (@authen_contexts) {
15178:             push(@{$changes{'authtypes'}},$item);
15179:         }
15180:     }
15181: 
15182:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
15183:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
15184:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
15185:     $save_usercreate{'id_rule'} = \@id_rule;
15186:     $save_usercreate{'username_rule'} = \@username_rule,
15187:     $save_usercreate{'authtypes'} = \%authhash;
15188: 
15189:     my %usercreation_hash =  (
15190:         usercreation     => \%save_usercreate,
15191:     );
15192: 
15193:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
15194:                                              $dom);
15195: 
15196:     if ($putresult eq 'ok') {
15197:         if (keys(%changes) > 0) {
15198:             $resulttext = &mt('Changes made:').'<ul>';
15199:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
15200:                 my %lt = &usercreation_types();
15201:                 foreach my $type (@{$changes{'cancreate'}}) {
15202:                     my $chgtext = $lt{$type}.', ';
15203:                     if ($cancreate{$type} eq 'none') {
15204:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
15205:                     } elsif ($cancreate{$type} eq 'any') {
15206:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
15207:                     } elsif ($cancreate{$type} eq 'official') {
15208:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
15209:                     } elsif ($cancreate{$type} eq 'unofficial') {
15210:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
15211:                     }
15212:                     $resulttext .= '<li>'.$chgtext.'</li>';
15213:                 }
15214:             }
15215:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
15216:                 my ($rules,$ruleorder) = 
15217:                     &Apache::lonnet::inst_userrules($dom,'username');
15218:                 my $chgtext = '<ul>';
15219:                 foreach my $type (@username_rule) {
15220:                     if (ref($rules->{$type}) eq 'HASH') {
15221:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
15222:                     }
15223:                 }
15224:                 $chgtext .= '</ul>';
15225:                 if (@username_rule > 0) {
15226:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
15227:                 } else {
15228:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
15229:                 }
15230:             }
15231:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
15232:                 my ($idrules,$idruleorder) = 
15233:                     &Apache::lonnet::inst_userrules($dom,'id');
15234:                 my $chgtext = '<ul>';
15235:                 foreach my $type (@id_rule) {
15236:                     if (ref($idrules->{$type}) eq 'HASH') {
15237:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
15238:                     }
15239:                 }
15240:                 $chgtext .= '</ul>';
15241:                 if (@id_rule > 0) {
15242:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
15243:                 } else {
15244:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
15245:                 }
15246:             }
15247:             my %authname = &authtype_names();
15248:             my %context_title = &context_names();
15249:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
15250:                 my $chgtext = '<ul>';
15251:                 foreach my $type (@{$changes{'authtypes'}}) {
15252:                     my @allowed;
15253:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
15254:                     foreach my $auth (@authtypes) {
15255:                         if ($authhash{$type}{$auth}) {
15256:                             push(@allowed,$authname{$auth});
15257:                         }
15258:                     }
15259:                     if (@allowed > 0) {
15260:                         $chgtext .= join(', ',@allowed).'</li>';
15261:                     } else {
15262:                         $chgtext .= &mt('none').'</li>';
15263:                     }
15264:                 }
15265:                 $chgtext .= '</ul>';
15266:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
15267:                 $resulttext .= '</li>';
15268:             }
15269:             $resulttext .= '</ul>';
15270:         } else {
15271:             $resulttext = &mt('No changes made to user creation settings');
15272:         }
15273:     } else {
15274:         $resulttext = '<span class="LC_error">'.
15275:             &mt('An error occurred: [_1]',$putresult).'</span>';
15276:     }
15277:     if ($warningmsg ne '') {
15278:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
15279:     }
15280:     return $resulttext;
15281: }
15282: 
15283: sub modify_selfcreation {
15284:     my ($dom,$lastactref,%domconfig) = @_;
15285:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
15286:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
15287:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15288:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
15289:     if (ref($typesref) eq 'ARRAY') {
15290:         @types = @{$typesref};
15291:     }
15292:     if (ref($usertypesref) eq 'HASH') {
15293:         %usertypes = %{$usertypesref};
15294:     }
15295:     $usertypes{'default'} = $othertitle;
15296: #
15297: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
15298: #
15299:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
15300:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
15301:             if ($key eq 'cancreate') {
15302:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
15303:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
15304:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
15305:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
15306:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
15307:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
15308:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
15309:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
15310:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
15311:                         } else {
15312:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
15313:                         }
15314:                     }
15315:                 }
15316:             } elsif ($key eq 'email_rule') {
15317:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
15318:             } else {
15319:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
15320:             }
15321:         }
15322:     }
15323: #
15324: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
15325: #
15326:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
15327:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
15328:             if ($key eq 'selfcreate') {
15329:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
15330:             } else {
15331:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
15332:             }
15333:         }
15334:     }
15335: #
15336: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
15337: #
15338:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
15339:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
15340:             if ($key eq 'inststatusguest') {
15341:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
15342:             } else {
15343:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
15344:             }
15345:         }
15346:     }
15347: 
15348:     my @contexts = ('selfcreate');
15349:     @{$cancreate{'selfcreate'}} = ();
15350:     %{$cancreate{'emailusername'}} = ();
15351:     if (@types) {
15352:         @{$cancreate{'statustocreate'}} = ();
15353:     }
15354:     %{$cancreate{'selfcreateprocessing'}} = ();
15355:     %{$cancreate{'shibenv'}} = ();
15356:     %{$cancreate{'emailverified'}} = ();
15357:     %{$cancreate{'emailoptions'}} = ();
15358:     %{$cancreate{'emaildomain'}} = ();
15359:     my %selfcreatetypes = (
15360:                              sso   => 'users authenticated by institutional single sign on',
15361:                              login => 'users authenticated by institutional log-in',
15362:                              email => 'users verified by e-mail',
15363:                           );
15364: #
15365: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
15366: # is permitted.
15367: #
15368:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
15369: 
15370:     my (@statuses,%email_rule);
15371:     foreach my $item ('login','sso','email') {
15372:         if ($item eq 'email') {
15373:             if ($env{'form.cancreate_email'}) {
15374:                 if (@types) {
15375:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
15376:                     foreach my $status (@poss_statuses) {
15377:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
15378:                             push(@statuses,$status);
15379:                         }
15380:                     }
15381:                     $save_inststatus{'inststatusguest'} = \@statuses;
15382:                 } else {
15383:                     push(@statuses,'default');
15384:                 }
15385:                 if (@statuses) {
15386:                     my %curr_rule;
15387:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
15388:                         foreach my $type (@statuses) {
15389:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
15390:                         }
15391:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
15392:                         foreach my $type (@statuses) {
15393:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
15394:                         }
15395:                     }
15396:                     push(@{$cancreate{'selfcreate'}},'email');
15397:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
15398:                     my %curremaildom;
15399:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
15400:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
15401:                     }
15402:                     foreach my $type (@statuses) {
15403:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
15404:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
15405:                         }
15406:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
15407:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
15408:                         }
15409:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
15410: #
15411: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
15412: #
15413:                             my $chosen = $1;
15414:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
15415:                                 my $emaildom;
15416:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
15417:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type}; 
15418:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
15419:                                     if (ref($curremaildom{$type}) eq 'HASH') {
15420:                                         if (exists($curremaildom{$type}{$chosen})) {
15421:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
15422:                                                 push(@{$changes{'cancreate'}},'emaildomain');
15423:                                             }
15424:                                         } elsif ($emaildom ne '') {
15425:                                             push(@{$changes{'cancreate'}},'emaildomain');
15426:                                         }
15427:                                     } elsif ($emaildom ne '') {
15428:                                         push(@{$changes{'cancreate'}},'emaildomain');
15429:                                     } 
15430:                                 }
15431:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
15432:                             } elsif ($chosen eq 'custom') {
15433:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
15434:                                 $email_rule{$type} = [];
15435:                                 if (ref($emailrules) eq 'HASH') {
15436:                                     foreach my $rule (@possemail_rules) {
15437:                                         if (exists($emailrules->{$rule})) {
15438:                                             push(@{$email_rule{$type}},$rule);
15439:                                         }
15440:                                     }
15441:                                 }
15442:                                 if (@{$email_rule{$type}}) {
15443:                                     $cancreate{'emailoptions'}{$type} = 'custom';
15444:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
15445:                                         if (@{$curr_rule{$type}} > 0) {
15446:                                             foreach my $rule (@{$curr_rule{$type}}) {
15447:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
15448:                                                     push(@{$changes{'email_rule'}},$type);
15449:                                                 }
15450:                                             }
15451:                                         }
15452:                                         foreach my $type (@{$email_rule{$type}}) {
15453:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
15454:                                                 push(@{$changes{'email_rule'}},$type);
15455:                                             }
15456:                                         }
15457:                                     } else {
15458:                                         push(@{$changes{'email_rule'}},$type);
15459:                                     }
15460:                                 }
15461:                             } else {
15462:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
15463:                             }
15464:                         }
15465:                     }
15466:                     if (@types) {
15467:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
15468:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
15469:                             if (@changed) {
15470:                                 push(@{$changes{'inststatus'}},'inststatusguest');
15471:                             }
15472:                         } else {
15473:                             push(@{$changes{'inststatus'}},'inststatusguest');
15474:                         }
15475:                     }
15476:                 } else {
15477:                     delete($env{'form.cancreate_email'});
15478:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
15479:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
15480:                             push(@{$changes{'inststatus'}},'inststatusguest');
15481:                         }
15482:                     }
15483:                 }
15484:             } else {
15485:                 $save_inststatus{'inststatusguest'} = [];
15486:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
15487:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
15488:                         push(@{$changes{'inststatus'}},'inststatusguest');
15489:                     }
15490:                 }
15491:             }
15492:         } else {
15493:             if ($env{'form.cancreate_'.$item}) {
15494:                 push(@{$cancreate{'selfcreate'}},$item);
15495:             }
15496:         }
15497:     }
15498:     my (%userinfo,%savecaptcha);
15499:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
15500: #
15501: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
15502: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
15503: #
15504: 
15505:     if ($env{'form.cancreate_email'}) {
15506:         push(@contexts,'emailusername');
15507:         if (@statuses) {
15508:             foreach my $type (@statuses) {
15509:                 if (ref($infofields) eq 'ARRAY') {
15510:                     foreach my $field (@{$infofields}) {
15511:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
15512:                             $cancreate{'emailusername'}{$type}{$field} = $1;
15513:                         }
15514:                     }
15515:                 }
15516:             }
15517:         }
15518: #
15519: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
15520: # queued requests for self-creation of account verified by e-mail.
15521: #
15522: 
15523:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
15524:         @approvalnotify = sort(@approvalnotify);
15525:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
15526:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
15527:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
15528:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
15529:                     push(@{$changes{'cancreate'}},'notify');
15530:                 }
15531:             } else {
15532:                 if ($cancreate{'notify'}{'approval'}) {
15533:                     push(@{$changes{'cancreate'}},'notify');
15534:                 }
15535:             }
15536:         } elsif ($cancreate{'notify'}{'approval'}) {
15537:             push(@{$changes{'cancreate'}},'notify');
15538:         }
15539: 
15540:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
15541:     }
15542: #  
15543: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
15544: # institutional log-in.
15545: #
15546:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
15547:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
15548:                ($domdefaults{'auth_def'} eq 'localauth'))) {
15549:             $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.').' '.
15550:                           &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.');
15551:         }
15552:     }
15553:     my @fields = ('lastname','firstname','middlename','generation',
15554:                   'permanentemail','id');
15555:     my @shibfields = (@fields,'inststatus');
15556:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
15557: #
15558: # Where usernames may created for institutional log-in and/or institutional single sign on:
15559: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
15560: # may self-create accounts 
15561: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
15562: # which the user may supply, if institutional data is unavailable.
15563: #
15564:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
15565:         if (@types) {
15566:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
15567:             push(@contexts,'statustocreate');
15568:             foreach my $type (@types) {
15569:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
15570:                 foreach my $field (@fields) {
15571:                     if (grep(/^\Q$field\E$/,@modifiable)) {
15572:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
15573:                     } else {
15574:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
15575:                     }
15576:                 }
15577:             }
15578:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
15579:                 foreach my $type (@types) {
15580:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
15581:                         foreach my $field (@fields) {
15582:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
15583:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
15584:                                 push(@{$changes{'selfcreate'}},$type);
15585:                                 last;
15586:                             }
15587:                         }
15588:                     }
15589:                 }
15590:             } else {
15591:                 foreach my $type (@types) {
15592:                     push(@{$changes{'selfcreate'}},$type);
15593:                 }
15594:             }
15595:         }
15596:         foreach my $field (@shibfields) {
15597:             if ($env{'form.shibenv_'.$field} ne '') {
15598:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
15599:             }
15600:         }
15601:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
15602:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
15603:                 foreach my $field (@shibfields) {
15604:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
15605:                         push(@{$changes{'cancreate'}},'shibenv');
15606:                     }
15607:                 }
15608:             } else {
15609:                 foreach my $field (@shibfields) {
15610:                     if ($env{'form.shibenv_'.$field}) {
15611:                         push(@{$changes{'cancreate'}},'shibenv');
15612:                         last;
15613:                     }
15614:                 }
15615:             }
15616:         }
15617:     }
15618:     foreach my $item (@contexts) {
15619:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
15620:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
15621:                 if (ref($cancreate{$item}) eq 'ARRAY') {
15622:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
15623:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15624:                             push(@{$changes{'cancreate'}},$item);
15625:                         }
15626:                     }
15627:                 }
15628:             }
15629:             if (ref($cancreate{$item}) eq 'ARRAY') {
15630:                 foreach my $type (@{$cancreate{$item}}) {
15631:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
15632:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15633:                             push(@{$changes{'cancreate'}},$item);
15634:                         }
15635:                     }
15636:                 }
15637:             }
15638:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
15639:             if (ref($cancreate{$item}) eq 'HASH') {
15640:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
15641:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
15642:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
15643:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
15644:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15645:                                     push(@{$changes{'cancreate'}},$item);
15646:                                 }
15647:                             }
15648:                         }
15649:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
15650:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
15651:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15652:                                 push(@{$changes{'cancreate'}},$item);
15653:                             }
15654:                         }
15655:                     }
15656:                 }
15657:                 foreach my $type (keys(%{$cancreate{$item}})) {
15658:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
15659:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
15660:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
15661:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
15662:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15663:                                         push(@{$changes{'cancreate'}},$item);
15664:                                     }
15665:                                 }
15666:                             } else {
15667:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15668:                                     push(@{$changes{'cancreate'}},$item);
15669:                                 }
15670:                             }
15671:                         }
15672:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
15673:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
15674:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15675:                                 push(@{$changes{'cancreate'}},$item);
15676:                             }
15677:                         }
15678:                     }
15679:                 }
15680:             }
15681:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
15682:             if (ref($cancreate{$item}) eq 'ARRAY') {
15683:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
15684:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15685:                         push(@{$changes{'cancreate'}},$item);
15686:                     }
15687:                 }
15688:             }
15689:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
15690:             if (ref($cancreate{$item}) eq 'HASH') {
15691:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15692:                     push(@{$changes{'cancreate'}},$item);
15693:                 }
15694:             }
15695:         } elsif ($item eq 'emailusername') {
15696:             if (ref($cancreate{$item}) eq 'HASH') {
15697:                 foreach my $type (keys(%{$cancreate{$item}})) {
15698:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
15699:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
15700:                             if ($cancreate{$item}{$type}{$field}) {
15701:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
15702:                                     push(@{$changes{'cancreate'}},$item);
15703:                                 }
15704:                                 last;
15705:                             }
15706:                         }
15707:                     }
15708:                 }
15709:             }
15710:         }
15711:     }
15712: #
15713: # Populate %save_usercreate hash with updates to self-creation configuration.
15714: #
15715:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
15716:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
15717:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
15718:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
15719:     if (ref($cancreate{'notify'}) eq 'HASH') {
15720:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
15721:     }
15722:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
15723:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
15724:     }
15725:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
15726:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
15727:     }
15728:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
15729:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
15730:     }
15731:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
15732:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
15733:     }
15734:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
15735:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
15736:     }
15737:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
15738:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
15739:     }
15740:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
15741:     $save_usercreate{'email_rule'} = \%email_rule;
15742: 
15743:     my %userconfig_hash = (
15744:             usercreation     => \%save_usercreate,
15745:             usermodification => \%save_usermodify,
15746:             inststatus       => \%save_inststatus,
15747:     );
15748: 
15749:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
15750:                                              $dom);
15751: #
15752: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
15753: #
15754:     if ($putresult eq 'ok') {
15755:         if (keys(%changes) > 0) {
15756:             $resulttext = &mt('Changes made:').'<ul>';
15757:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
15758:                 my %lt = &selfcreation_types();
15759:                 foreach my $type (@{$changes{'cancreate'}}) {
15760:                     my $chgtext = '';
15761:                     if ($type eq 'selfcreate') {
15762:                         if (@{$cancreate{$type}} == 0) {
15763:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
15764:                         } else {
15765:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
15766:                                         '<ul>';
15767:                             foreach my $case (@{$cancreate{$type}}) {
15768:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
15769:                             }
15770:                             $chgtext .= '</ul>';
15771:                             if (ref($cancreate{$type}) eq 'ARRAY') {
15772:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
15773:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
15774:                                         if (@{$cancreate{'statustocreate'}} == 0) {
15775:                                             $chgtext .= '<span class="LC_warning">'.
15776:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
15777:                                                         '</span><br />';
15778:                                         }
15779:                                     }
15780:                                 }
15781:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
15782:                                     if (!@statuses) {
15783:                                         $chgtext .= '<span class="LC_warning">'.
15784:                                                     &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.").
15785:                                                     '</span><br />';
15786: 
15787:                                     }
15788:                                 }
15789:                             }
15790:                         }
15791:                     } elsif ($type eq 'shibenv') {
15792:                         if (keys(%{$cancreate{$type}}) == 0) {
15793:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
15794:                         } else {
15795:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
15796:                                         '<ul>';
15797:                             foreach my $field (@shibfields) {
15798:                                 next if ($cancreate{$type}{$field} eq '');
15799:                                 if ($field eq 'inststatus') {
15800:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
15801:                                 } else {
15802:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
15803:                                 }
15804:                             }
15805:                             $chgtext .= '</ul>';
15806:                         }
15807:                     } elsif ($type eq 'statustocreate') {
15808:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
15809:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
15810:                             if (@{$cancreate{'selfcreate'}} > 0) {
15811:                                 if (@{$cancreate{'statustocreate'}} == 0) {
15812:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
15813:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
15814:                                         $chgtext .= '<br />'.
15815:                                                     '<span class="LC_warning">'.
15816:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
15817:                                                     '</span>';
15818:                                     }
15819:                                 } elsif (keys(%usertypes) > 0) {
15820:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
15821:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
15822:                                     } else {
15823:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
15824:                                     }
15825:                                     $chgtext .= '<ul>';
15826:                                     foreach my $case (@{$cancreate{$type}}) {
15827:                                         if ($case eq 'default') {
15828:                                             $chgtext .= '<li>'.$othertitle.'</li>';
15829:                                         } else {
15830:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
15831:                                         }
15832:                                     }
15833:                                     $chgtext .= '</ul>';
15834:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
15835:                                         $chgtext .= '<span class="LC_warning">'.
15836:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
15837:                                                     '</span>';
15838:                                     }
15839:                                 }
15840:                             } else {
15841:                                 if (@{$cancreate{$type}} == 0) {
15842:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
15843:                                 } else {
15844:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
15845:                                 }
15846:                             }
15847:                             $chgtext .= '<br />';
15848:                         }
15849:                     } elsif ($type eq 'selfcreateprocessing') {
15850:                         my %choices = &Apache::lonlocal::texthash (
15851:                                                                     automatic => 'Automatic approval',
15852:                                                                     approval  => 'Queued for approval',
15853:                                                                   );
15854:                         if (@types) {
15855:                             if (@statuses) {
15856:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:'). 
15857:                                             '<ul>';
15858:                                 foreach my $status (@statuses) {
15859:                                     if ($status eq 'default') {
15860:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
15861:                                     } else {
15862:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
15863:                                     }
15864:                                 }
15865:                                 $chgtext .= '</ul>';
15866:                             }
15867:                         } else {
15868:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
15869:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
15870:                         }
15871:                     } elsif ($type eq 'emailverified') {
15872:                         my %options = &Apache::lonlocal::texthash (
15873:                                                                     all   => 'Same as e-mail',
15874:                                                                     first => 'Omit @domain',
15875:                                                                     free  => 'Free to choose',
15876:                                                                   );
15877:                         if (@types) {
15878:                             if (@statuses) {
15879:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
15880:                                             '<ul>';
15881:                                 foreach my $status (@statuses) {
15882:                                     if ($status eq 'default') {
15883:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
15884:                                     } else {
15885:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
15886:                                     }
15887:                                 }
15888:                                 $chgtext .= '</ul>';
15889:                             }
15890:                         } else {
15891:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
15892:                                             $options{$cancreate{'emailverified'}{'default'}});
15893:                         }
15894:                     } elsif ($type eq 'emailoptions') {
15895:                         my %options = &Apache::lonlocal::texthash (
15896:                                                                     any     => 'Any e-mail',
15897:                                                                     inst    => 'Institutional only',
15898:                                                                     noninst => 'Non-institutional only',
15899:                                                                     custom  => 'Custom restrictions',
15900:                                                                   );
15901:                         if (@types) {
15902:                             if (@statuses) {
15903:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
15904:                                             '<ul>';
15905:                                 foreach my $status (@statuses) {
15906:                                     if ($type eq 'default') {
15907:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
15908:                                     } else {
15909:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
15910:                                     }
15911:                                 }
15912:                                 $chgtext .= '</ul>';
15913:                             }
15914:                         } else {
15915:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
15916:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
15917:                             } else {
15918:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
15919:                                                 $options{$cancreate{'emailoptions'}{'default'}});
15920:                             }
15921:                         }
15922:                     } elsif ($type eq 'emaildomain') {
15923:                         my $output;
15924:                         if (@statuses) {
15925:                             foreach my $type (@statuses) {
15926:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
15927:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
15928:                                         if ($type eq 'default') {
15929:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15930:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
15931:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
15932:                                             } else {
15933:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
15934:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
15935:                                             }
15936:                                         } else {
15937:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15938:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
15939:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
15940:                                             } else {
15941:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
15942:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>'; 
15943:                                             }
15944:                                         }
15945:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
15946:                                         if ($type eq 'default') {
15947:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15948:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
15949:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
15950:                                             } else {
15951:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
15952:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
15953:                                             }
15954:                                         } else {
15955:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
15956:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
15957:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
15958:                                             } else {
15959:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
15960:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';   
15961:                                             }
15962:                                         }
15963:                                     }
15964:                                 }
15965:                             }
15966:                         }
15967:                         if ($output ne '') {
15968:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
15969:                                         '<ul>'.$output.'</ul>';
15970:                         }
15971:                     } elsif ($type eq 'captcha') {
15972:                         if ($savecaptcha{$type} eq 'notused') {
15973:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
15974:                         } else {
15975:                             my %captchas = &captcha_phrases();
15976:                             if ($captchas{$savecaptcha{$type}}) {
15977:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
15978:                             } else {
15979:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
15980:                             }
15981:                         }
15982:                     } elsif ($type eq 'recaptchakeys') {
15983:                         my ($privkey,$pubkey);
15984:                         if (ref($savecaptcha{$type}) eq 'HASH') {
15985:                             $pubkey = $savecaptcha{$type}{'public'};
15986:                             $privkey = $savecaptcha{$type}{'private'};
15987:                         }
15988:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
15989:                         if (!$pubkey) {
15990:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
15991:                         } else {
15992:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
15993:                         }
15994:                         if (!$privkey) {
15995:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
15996:                         } else {
15997:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
15998:                         }
15999:                         $chgtext .= '</ul>';
16000:                     } elsif ($type eq 'recaptchaversion') {
16001:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
16002:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
16003:                         }
16004:                     } elsif ($type eq 'emailusername') {
16005:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
16006:                             if (@statuses) {
16007:                                 foreach my $type (@statuses) {
16008:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
16009:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
16010:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
16011:                                                     '<ul>';
16012:                                             foreach my $field (@{$infofields}) {
16013:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
16014:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
16015:                                                 }
16016:                                             }
16017:                                             $chgtext .= '</ul>';
16018:                                         } else {
16019:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
16020:                                         }
16021:                                     } else {
16022:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
16023:                                     }
16024:                                 }
16025:                             }
16026:                         }
16027:                     } elsif ($type eq 'notify') {
16028:                         my $numapprove = 0;
16029:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
16030:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
16031:                                 if ($cancreate{'notify'}{'approval'}) {
16032:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
16033:                                     $numapprove ++;
16034:                                 }
16035:                             }
16036:                         }
16037:                         unless ($numapprove) {
16038:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
16039:                         }
16040:                     }
16041:                     if ($chgtext) {
16042:                         $resulttext .= '<li>'.$chgtext.'</li>';
16043:                     }
16044:                 }
16045:             }
16046:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
16047:                 my ($emailrules,$emailruleorder) =
16048:                     &Apache::lonnet::inst_userrules($dom,'email');
16049:                 foreach my $type (@{$changes{'email_rule'}}) {
16050:                     if (ref($email_rule{$type}) eq 'ARRAY') {
16051:                         my $chgtext = '<ul>';
16052:                         foreach my $rule (@{$email_rule{$type}}) {
16053:                             if (ref($emailrules->{$rule}) eq 'HASH') {
16054:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
16055:                             }
16056:                         }
16057:                         $chgtext .= '</ul>';
16058:                         my $typename;
16059:                         if (@types) {
16060:                             if ($type eq 'default') {
16061:                                 $typename = $othertitle;
16062:                             } else {
16063:                                 $typename = $usertypes{$type};
16064:                             } 
16065:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
16066:                         }
16067:                         if (@{$email_rule{$type}} > 0) {
16068:                             $resulttext .= '<li>'.
16069:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
16070:                                                $usertypes{$type}).
16071:                                            $chgtext.
16072:                                            '</li>';
16073:                         } else {
16074:                             $resulttext .= '<li>'.
16075:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
16076:                                            '</li>'.
16077:                                            &mt('(Affiliation: [_1])',$typename);
16078:                         }
16079:                     }
16080:                 }
16081:             }
16082:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
16083:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
16084:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
16085:                         my $chgtext = '<ul>';
16086:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
16087:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
16088:                         }
16089:                         $chgtext .= '</ul>';
16090:                         $resulttext .= '<li>'.
16091:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
16092:                                           $chgtext.
16093:                                        '</li>';
16094:                     } else {
16095:                         $resulttext .= '<li>'.
16096:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
16097:                                        '</li>';
16098:                     }
16099:                 }
16100:             }
16101:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
16102:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
16103:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
16104:                 foreach my $type (@{$changes{'selfcreate'}}) {
16105:                     my $typename = $type;
16106:                     if (keys(%usertypes) > 0) {
16107:                         if ($usertypes{$type} ne '') {
16108:                             $typename = $usertypes{$type};
16109:                         }
16110:                     }
16111:                     my @modifiable;
16112:                     $resulttext .= '<li>'.
16113:                                     &mt('Self-creation of account by users with status: [_1]',
16114:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
16115:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
16116:                     foreach my $field (@fields) {
16117:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
16118:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
16119:                         }
16120:                     }
16121:                     if (@modifiable > 0) {
16122:                         $resulttext .= join(', ',@modifiable);
16123:                     } else {
16124:                         $resulttext .= &mt('none');
16125:                     }
16126:                     $resulttext .= '</li>';
16127:                 }
16128:                 $resulttext .= '</ul></li>';
16129:             }
16130:             $resulttext .= '</ul>';
16131:             my $cachetime = 24*60*60;
16132:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
16133:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16134:             if (ref($lastactref) eq 'HASH') {
16135:                 $lastactref->{'domdefaults'} = 1;
16136:             }
16137:         } else {
16138:             $resulttext = &mt('No changes made to self-creation settings');
16139:         }
16140:     } else {
16141:         $resulttext = '<span class="LC_error">'.
16142:             &mt('An error occurred: [_1]',$putresult).'</span>';
16143:     }
16144:     if ($warningmsg ne '') {
16145:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
16146:     }
16147:     return $resulttext;
16148: }
16149: 
16150: sub process_captcha {
16151:     my ($container,$changes,$newsettings,$currsettings) = @_;
16152:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
16153:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
16154:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
16155:         $newsettings->{'captcha'} = 'original';
16156:     }
16157:     my %current;
16158:     if (ref($currsettings) eq 'HASH') {
16159:         %current = %{$currsettings};
16160:     }
16161:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
16162:         if ($container eq 'cancreate') {
16163:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
16164:                 push(@{$changes->{'cancreate'}},'captcha');
16165:             } elsif (!defined($changes->{'cancreate'})) {
16166:                 $changes->{'cancreate'} = ['captcha'];
16167:             }
16168:         } elsif ($container eq 'passwords') {
16169:             $changes->{'reset'} = 1;
16170:         } else {
16171:             $changes->{'captcha'} = 1;
16172:         }
16173:     }
16174:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
16175:     if ($newsettings->{'captcha'} eq 'recaptcha') {
16176:         $newpub = $env{'form.'.$container.'_recaptchapub'};
16177:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
16178:         $newpub =~ s/[^\w\-]//g;
16179:         $newpriv =~ s/[^\w\-]//g;
16180:         $newsettings->{'recaptchakeys'} = {
16181:                                              public  => $newpub,
16182:                                              private => $newpriv,
16183:                                           };
16184:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
16185:         $newversion =~ s/\D//g;
16186:         if ($newversion ne '2') {
16187:             $newversion = 1;
16188:         }
16189:         $newsettings->{'recaptchaversion'} = $newversion;
16190:     }
16191:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
16192:         $currpub = $current{'recaptchakeys'}{'public'};
16193:         $currpriv = $current{'recaptchakeys'}{'private'};
16194:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
16195:             $newsettings->{'recaptchakeys'} = {
16196:                                                  public  => '',
16197:                                                  private => '',
16198:                                               }
16199:         }
16200:     }
16201:     if ($current{'captcha'} eq 'recaptcha') {
16202:         $currversion = $current{'recaptchaversion'};
16203:         if ($currversion ne '2') {
16204:             $currversion = 1;
16205:         }
16206:     }
16207:     if ($currversion ne $newversion) {
16208:         if ($container eq 'cancreate') {
16209:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
16210:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
16211:             } elsif (!defined($changes->{'cancreate'})) {
16212:                 $changes->{'cancreate'} = ['recaptchaversion'];
16213:             }
16214:         } elsif ($container eq 'passwords') {
16215:             $changes->{'reset'} = 1;
16216:         } else {
16217:             $changes->{'recaptchaversion'} = 1;
16218:         }
16219:     }
16220:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
16221:         if ($container eq 'cancreate') {
16222:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
16223:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
16224:             } elsif (!defined($changes->{'cancreate'})) {
16225:                 $changes->{'cancreate'} = ['recaptchakeys'];
16226:             }
16227:         } elsif ($container eq 'passwords') {
16228:             $changes->{'reset'} = 1;
16229:         } else {
16230:             $changes->{'recaptchakeys'} = 1;
16231:         }
16232:     }
16233:     return;
16234: }
16235: 
16236: sub modify_usermodification {
16237:     my ($dom,%domconfig) = @_;
16238:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
16239:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
16240:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
16241:             if ($key eq 'selfcreate') {
16242:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
16243:             } else {  
16244:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
16245:             }
16246:         }
16247:     }
16248:     my @contexts = ('author','course');
16249:     my %context_title = (
16250:                            author => 'In author context',
16251:                            course => 'In course context',
16252:                         );
16253:     my @fields = ('lastname','firstname','middlename','generation',
16254:                   'permanentemail','id');
16255:     my %roles = (
16256:                   author => ['ca','aa'],
16257:                   course => ['st','ep','ta','in','cr'],
16258:                 );
16259:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
16260:     foreach my $context (@contexts) {
16261:         foreach my $role (@{$roles{$context}}) {
16262:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
16263:             foreach my $item (@fields) {
16264:                 if (grep(/^\Q$item\E$/,@modifiable)) {
16265:                     $modifyhash{$context}{$role}{$item} = 1;
16266:                 } else {
16267:                     $modifyhash{$context}{$role}{$item} = 0;
16268:                 }
16269:             }
16270:         }
16271:         if (ref($curr_usermodification{$context}) eq 'HASH') {
16272:             foreach my $role (@{$roles{$context}}) {
16273:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
16274:                     foreach my $field (@fields) {
16275:                         if ($modifyhash{$context}{$role}{$field} ne 
16276:                                 $curr_usermodification{$context}{$role}{$field}) {
16277:                             push(@{$changes{$context}},$role);
16278:                             last;
16279:                         }
16280:                     }
16281:                 }
16282:             }
16283:         } else {
16284:             foreach my $context (@contexts) {
16285:                 foreach my $role (@{$roles{$context}}) {
16286:                     push(@{$changes{$context}},$role);
16287:                 }
16288:             }
16289:         }
16290:     }
16291:     my %usermodification_hash =  (
16292:                                    usermodification => \%modifyhash,
16293:                                  );
16294:     my $putresult = &Apache::lonnet::put_dom('configuration',
16295:                                              \%usermodification_hash,$dom);
16296:     if ($putresult eq 'ok') {
16297:         if (keys(%changes) > 0) {
16298:             $resulttext = &mt('Changes made: ').'<ul>';
16299:             foreach my $context (@contexts) {
16300:                 if (ref($changes{$context}) eq 'ARRAY') {
16301:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
16302:                     if (ref($changes{$context}) eq 'ARRAY') {
16303:                         foreach my $role (@{$changes{$context}}) {
16304:                             my $rolename;
16305:                             if ($role eq 'cr') {
16306:                                 $rolename = &mt('Custom');
16307:                             } else {
16308:                                 $rolename = &Apache::lonnet::plaintext($role);
16309:                             }
16310:                             my @modifiable;
16311:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
16312:                             foreach my $field (@fields) {
16313:                                 if ($modifyhash{$context}{$role}{$field}) {
16314:                                     push(@modifiable,$fieldtitles{$field});
16315:                                 }
16316:                             }
16317:                             if (@modifiable > 0) {
16318:                                 $resulttext .= join(', ',@modifiable);
16319:                             } else {
16320:                                 $resulttext .= &mt('none'); 
16321:                             }
16322:                             $resulttext .= '</li>';
16323:                         }
16324:                         $resulttext .= '</ul></li>';
16325:                     }
16326:                 }
16327:             }
16328:             $resulttext .= '</ul>';
16329:         } else {
16330:             $resulttext = &mt('No changes made to user modification settings');
16331:         }
16332:     } else {
16333:         $resulttext = '<span class="LC_error">'.
16334:             &mt('An error occurred: [_1]',$putresult).'</span>';
16335:     }
16336:     return $resulttext;
16337: }
16338: 
16339: sub modify_defaults {
16340:     my ($dom,$lastactref,%domconfig) = @_;
16341:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
16342:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16343:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
16344:                  'portal_def');
16345:     my @authtypes = ('internal','krb4','krb5','localauth','lti');
16346:     foreach my $item (@items) {
16347:         $newvalues{$item} = $env{'form.'.$item};
16348:         if ($item eq 'auth_def') {
16349:             if ($newvalues{$item} ne '') {
16350:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
16351:                     push(@errors,$item);
16352:                 }
16353:             }
16354:         } elsif ($item eq 'lang_def') {
16355:             if ($newvalues{$item} ne '') {
16356:                 if ($newvalues{$item} =~ /^(\w+)/) {
16357:                     my $langcode = $1;
16358:                     if ($langcode ne 'x_chef') {
16359:                         if (code2language($langcode) eq '') {
16360:                             push(@errors,$item);
16361:                         }
16362:                     }
16363:                 } else {
16364:                     push(@errors,$item);
16365:                 }
16366:             }
16367:         } elsif ($item eq 'timezone_def') {
16368:             if ($newvalues{$item} ne '') {
16369:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
16370:                     push(@errors,$item);   
16371:                 }
16372:             }
16373:         } elsif ($item eq 'datelocale_def') {
16374:             if ($newvalues{$item} ne '') {
16375:                 my @datelocale_ids = DateTime::Locale->ids();
16376:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
16377:                     push(@errors,$item);
16378:                 }
16379:             }
16380:         } elsif ($item eq 'portal_def') {
16381:             if ($newvalues{$item} ne '') {
16382:                 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])\/?$/) {
16383:                     push(@errors,$item);
16384:                 }
16385:             }
16386:         }
16387:         if (grep(/^\Q$item\E$/,@errors)) {
16388:             $newvalues{$item} = $domdefaults{$item};
16389:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
16390:             $changes{$item} = 1;
16391:         }
16392:         $domdefaults{$item} = $newvalues{$item};
16393:     }
16394:     my %staticdefaults = (
16395:                            'intauth_cost'   => 10,
16396:                            'intauth_check'  => 0,
16397:                            'intauth_switch' => 0,
16398:                          );
16399:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
16400:         if (exists($domdefaults{$item})) {
16401:             $newvalues{$item} = $domdefaults{$item};
16402:         } else {
16403:             $newvalues{$item} = $staticdefaults{$item};
16404:         }
16405:     }
16406:     my %defaults_hash = (
16407:                          defaults => \%newvalues,
16408:                         );
16409:     my $title = &defaults_titles();
16410: 
16411:     my $currinststatus;
16412:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
16413:         $currinststatus = $domconfig{'inststatus'};
16414:     } else {
16415:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16416:         $currinststatus = {
16417:                              inststatustypes => $usertypes,
16418:                              inststatusorder => $types,
16419:                              inststatusguest => [],
16420:                           };
16421:     }
16422:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
16423:     my @allpos;
16424:     my %alltypes;
16425:     my @inststatusguest;
16426:     if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
16427:         foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
16428:             unless (grep(/^\Q$type\E$/,@todelete)) {
16429:                 push(@inststatusguest,$type);
16430:             }
16431:         }
16432:     }
16433:     my ($currtitles,$currorder);
16434:     if (ref($currinststatus) eq 'HASH') {
16435:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
16436:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
16437:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
16438:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
16439:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
16440:                     }
16441:                 }
16442:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
16443:                     my $position = $env{'form.inststatus_pos_'.$type};
16444:                     $position =~ s/\D+//g;
16445:                     $allpos[$position] = $type;
16446:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
16447:                     $alltypes{$type} =~ s/`//g;
16448:                 }
16449:             }
16450:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
16451:             $currtitles =~ s/,$//;
16452:         }
16453:     }
16454:     if ($env{'form.addinststatus'}) {
16455:         my $newtype = $env{'form.addinststatus'};
16456:         $newtype =~ s/\W//g;
16457:         unless (exists($alltypes{$newtype})) {
16458:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
16459:             $alltypes{$newtype} =~ s/`//g; 
16460:             my $position = $env{'form.addinststatus_pos'};
16461:             $position =~ s/\D+//g;
16462:             if ($position ne '') {
16463:                 $allpos[$position] = $newtype;
16464:             }
16465:         }
16466:     }
16467:     my @orderedstatus;
16468:     foreach my $type (@allpos) {
16469:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
16470:             push(@orderedstatus,$type);
16471:         }
16472:     }
16473:     foreach my $type (keys(%alltypes)) {
16474:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
16475:             delete($alltypes{$type});
16476:         }
16477:     }
16478:     $defaults_hash{'inststatus'} = {
16479:                                      inststatustypes => \%alltypes,
16480:                                      inststatusorder => \@orderedstatus,
16481:                                      inststatusguest => \@inststatusguest,
16482:                                    };
16483:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
16484:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
16485:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
16486:         }
16487:     }
16488:     if ($currorder ne join(',',@orderedstatus)) {
16489:         $changes{'inststatus'}{'inststatusorder'} = 1;
16490:     }
16491:     my $newtitles;
16492:     foreach my $item (@orderedstatus) {
16493:         $newtitles .= $alltypes{$item}.',';
16494:     }
16495:     $newtitles =~ s/,$//;
16496:     if ($currtitles ne $newtitles) {
16497:         $changes{'inststatus'}{'inststatustypes'} = 1;
16498:     }
16499:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
16500:                                              $dom);
16501:     if ($putresult eq 'ok') {
16502:         if (keys(%changes) > 0) {
16503:             $resulttext = &mt('Changes made:').'<ul>';
16504:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
16505:             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";
16506:             foreach my $item (sort(keys(%changes))) {
16507:                 if ($item eq 'inststatus') {
16508:                     if (ref($changes{'inststatus'}) eq 'HASH') {
16509:                         if (@orderedstatus) {
16510:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
16511:                             foreach my $type (@orderedstatus) { 
16512:                                 $resulttext .= $alltypes{$type}.', ';
16513:                             }
16514:                             $resulttext =~ s/, $//;
16515:                             $resulttext .= '</li>';
16516:                         } else {
16517:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>'; 
16518:                         }
16519:                     }
16520:                 } else {
16521:                     my $value = $env{'form.'.$item};
16522:                     if ($value eq '') {
16523:                         $value = &mt('none');
16524:                     } elsif ($item eq 'auth_def') {
16525:                         my %authnames = &authtype_names();
16526:                         my %shortauth = (
16527:                                           internal   => 'int',
16528:                                           krb4       => 'krb4',
16529:                                           krb5       => 'krb5',
16530:                                           localauth  => 'loc',
16531:                                           lti        => 'lti',
16532:                         );
16533:                         $value = $authnames{$shortauth{$value}};
16534:                     }
16535:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
16536:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
16537:                 }
16538:             }
16539:             $resulttext .= '</ul>';
16540:             $mailmsgtext .= "\n";
16541:             my $cachetime = 24*60*60;
16542:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16543:             if (ref($lastactref) eq 'HASH') {
16544:                 $lastactref->{'domdefaults'} = 1;
16545:             }
16546:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
16547:                 my $notify = 1;
16548:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
16549:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
16550:                         $notify = 0;
16551:                     }
16552:                 }
16553:                 if ($notify) {
16554:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
16555:                                                "LON-CAPA Domain Settings Change - $dom",
16556:                                                $mailmsgtext);
16557:                 }
16558:             }
16559:         } else {
16560:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
16561:         }
16562:     } else {
16563:         $resulttext = '<span class="LC_error">'.
16564:             &mt('An error occurred: [_1]',$putresult).'</span>';
16565:     }
16566:     if (@errors > 0) {
16567:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
16568:         foreach my $item (@errors) {
16569:             $resulttext .= ' "'.$title->{$item}.'",';
16570:         }
16571:         $resulttext =~ s/,$//;
16572:     }
16573:     return $resulttext;
16574: }
16575: 
16576: sub modify_scantron {
16577:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
16578:     my ($resulttext,%confhash,%changes,$errors);
16579:     my $custom = 'custom.tab';
16580:     my $default = 'default.tab';
16581:     my $servadm = $r->dir_config('lonAdmEMail');
16582:     my ($configuserok,$author_ok,$switchserver) =
16583:         &config_check($dom,$confname,$servadm);
16584:     if ($env{'form.scantronformat.filename'} ne '') {
16585:         my $error;
16586:         if ($configuserok eq 'ok') {
16587:             if ($switchserver) {
16588:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
16589:             } else {
16590:                 if ($author_ok eq 'ok') {
16591:                     my ($result,$scantronurl) =
16592:                         &publishlogo($r,'upload','scantronformat',$dom,
16593:                                      $confname,'scantron','','',$custom);
16594:                     if ($result eq 'ok') {
16595:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
16596:                         $changes{'scantronformat'} = 1;
16597:                     } else {
16598:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
16599:                     }
16600:                 } else {
16601:                     $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);
16602:                 }
16603:             }
16604:         } else {
16605:             $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);
16606:         }
16607:         if ($error) {
16608:             &Apache::lonnet::logthis($error);
16609:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
16610:         }
16611:     }
16612:     if (ref($domconfig{'scantron'}) eq 'HASH') {
16613:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
16614:             if ($env{'form.scantronformat_del'}) {
16615:                 $confhash{'scantron'}{'scantronformat'} = '';
16616:                 $changes{'scantronformat'} = 1;
16617:             } else {
16618:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
16619:             }
16620:         }
16621:     }
16622:     my @options = ('hdr','pad','rem');
16623:     my @fields = &scantroncsv_fields();
16624:     my %titles = &scantronconfig_titles();
16625:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
16626:     my ($newdat,$currdat,%newcol,%currcol);
16627:     if (grep(/^dat$/,@formats)) {
16628:         $confhash{'scantron'}{config}{dat} = 1;
16629:         $newdat = 1;
16630:     } else {
16631:         $newdat = 0;
16632:     }
16633:     if (grep(/^csv$/,@formats)) {
16634:         my %bynum;
16635:         foreach my $field (@fields) {
16636:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
16637:                 my $posscol = $1;
16638:                 if (($posscol < 20) && (!$bynum{$posscol})) {
16639:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
16640:                     $bynum{$posscol} = $field;
16641:                     $newcol{$field} = $posscol;
16642:                 }
16643:             }
16644:         }
16645:         if (keys(%newcol)) {
16646:             foreach my $option (@options) {
16647:                 if ($env{'form.scantroncsv_'.$option}) {
16648:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
16649:                 }
16650:             }
16651:         }
16652:     }
16653:     $currdat = 1;
16654:     if (ref($domconfig{'scantron'}) eq 'HASH') {
16655:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
16656:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
16657:                 $currdat = 0;
16658:             }
16659:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
16660:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
16661:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
16662:                 }
16663:             }
16664:         }
16665:     }
16666:     if ($currdat != $newdat) {
16667:         $changes{'config'} = 1;
16668:     } else {
16669:         foreach my $field (@fields) {
16670:             if ($currcol{$field} ne '') {
16671:                 if ($currcol{$field} ne $newcol{$field}) {
16672:                     $changes{'config'} = 1;
16673:                     last;
16674:                 }
16675:             } elsif ($newcol{$field} ne '') {
16676:                 $changes{'config'} = 1;
16677:                 last;
16678:             }
16679:         }
16680:     }
16681:     if (keys(%confhash) > 0) {
16682:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
16683:                                                  $dom);
16684:         if ($putresult eq 'ok') {
16685:             if (keys(%changes) > 0) {
16686:                 if (ref($confhash{'scantron'}) eq 'HASH') {
16687:                     $resulttext = &mt('Changes made:').'<ul>';
16688:                     if ($changes{'scantronformat'}) {
16689:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
16690:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
16691:                         } else {
16692:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
16693:                         }
16694:                     }
16695:                     if ($changes{'config'}) {
16696:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
16697:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
16698:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
16699:                             }
16700:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
16701:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
16702:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
16703:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
16704:                                         foreach my $field (@fields) {
16705:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
16706:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
16707:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
16708:                                             }
16709:                                         }
16710:                                         $resulttext .= '</ul></li>';
16711:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
16712:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
16713:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
16714:                                                 foreach my $option (@options) {
16715:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
16716:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
16717:                                                     }
16718:                                                 }
16719:                                                 $resulttext .= '</ul></li>';
16720:                                             }
16721:                                         }
16722:                                     }
16723:                                 }
16724:                             }
16725:                         } else {
16726:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
16727:                         }
16728:                     }
16729:                     $resulttext .= '</ul>';
16730:                 } else {
16731:                     $resulttext = &mt('Changes made to bubblesheet format file.');
16732:                 }
16733:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
16734:                 if (ref($lastactref) eq 'HASH') {
16735:                     $lastactref->{'domainconfig'} = 1;
16736:                 }
16737:             } else {
16738:                 $resulttext = &mt('No changes made to bubblesheet format settings');
16739:             }
16740:         } else {
16741:             $resulttext = '<span class="LC_error">'.
16742:                 &mt('An error occurred: [_1]',$putresult).'</span>';
16743:         }
16744:     } else {
16745:         $resulttext = &mt('No changes made to bubblesheet format file'); 
16746:     }
16747:     if ($errors) {
16748:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
16749:                        $errors.'</ul></p>';
16750:     }
16751:     return $resulttext;
16752: }
16753: 
16754: sub modify_coursecategories {
16755:     my ($dom,$lastactref,%domconfig) = @_;
16756:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
16757:         $cathash);
16758:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
16759:     my @catitems = ('unauth','auth');
16760:     my @cattypes = ('std','domonly','codesrch','none');
16761:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
16762:         $cathash = $domconfig{'coursecategories'}{'cats'};
16763:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
16764:             $changes{'togglecats'} = 1;
16765:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
16766:         }
16767:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
16768:             $changes{'categorize'} = 1;
16769:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
16770:         }
16771:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
16772:             $changes{'togglecatscomm'} = 1;
16773:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
16774:         }
16775:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
16776:             $changes{'categorizecomm'} = 1;
16777:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
16778: 
16779:         }
16780:         if ($domconfig{'coursecategories'}{'togglecatsplace'} ne $env{'form.togglecatsplace'}) {
16781:             $changes{'togglecatsplace'} = 1;
16782:             $domconfig{'coursecategories'}{'togglecatsplace'} = $env{'form.togglecatsplace'};
16783:         }
16784:         if ($domconfig{'coursecategories'}{'categorizeplace'} ne $env{'form.categorizeplace'}) {
16785:             $changes{'categorizeplace'} = 1;
16786:             $domconfig{'coursecategories'}{'categorizeplace'} = $env{'form.categorizeplace'};
16787:         }
16788:         foreach my $item (@catitems) {
16789:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
16790:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
16791:                     $changes{$item} = 1;
16792:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
16793:                 }
16794:             }
16795:         }
16796:     } else {
16797:         $changes{'togglecats'} = 1;
16798:         $changes{'categorize'} = 1;
16799:         $changes{'togglecatscomm'} = 1;
16800:         $changes{'categorizecomm'} = 1;
16801:         $changes{'togglecatsplace'} = 1;
16802:         $changes{'categorizeplace'} = 1;
16803:         $domconfig{'coursecategories'} = {
16804:                                              togglecats => $env{'form.togglecats'},
16805:                                              categorize => $env{'form.categorize'},
16806:                                              togglecatscomm => $env{'form.togglecatscomm'},
16807:                                              categorizecomm => $env{'form.categorizecomm'},
16808:                                              togglecatsplace => $env{'form.togglecatsplace'},
16809:                                              categorizeplace => $env{'form.categorizeplace'},
16810:                                          };
16811:         foreach my $item (@catitems) {
16812:             if ($env{'form.coursecat_'.$item} ne 'std') {
16813:                 $changes{$item} = 1;
16814:             }
16815:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
16816:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
16817:             }
16818:         }
16819:     }
16820:     if (ref($cathash) eq 'HASH') {
16821:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
16822:             push (@deletecategory,'instcode::0');
16823:         }
16824:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
16825:             push(@deletecategory,'communities::0');
16826:         }
16827:         if (($domconfig{'coursecategories'}{'cats'}{'placement::0'} ne '')  && ($env{'form.placement'} == 0)) {
16828:             push(@deletecategory,'placement::0');
16829:         }
16830:     }
16831:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
16832:     if (ref($cathash) eq 'HASH') {
16833:         if (@deletecategory > 0) {
16834:             #FIXME Need to remove category from all courses using a deleted category 
16835:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
16836:             foreach my $item (@deletecategory) {
16837:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
16838:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
16839:                     $deletions{$item} = 1;
16840:                     &recurse_cat_deletes($item,$cathash,\%deletions);
16841:                 }
16842:             }
16843:         }
16844:         foreach my $item (keys(%{$cathash})) {
16845:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
16846:             if ($cathash->{$item} ne $env{'form.'.$item}) {
16847:                 $reorderings{$item} = 1;
16848:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
16849:             }
16850:             if ($env{'form.addcategory_name_'.$item} ne '') {
16851:                 my $newcat = $env{'form.addcategory_name_'.$item};
16852:                 my $newdepth = $depth+1;
16853:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
16854:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
16855:                 $adds{$newitem} = 1; 
16856:             }
16857:             if ($env{'form.subcat_'.$item} ne '') {
16858:                 my $newcat = $env{'form.subcat_'.$item};
16859:                 my $newdepth = $depth+1;
16860:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
16861:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
16862:                 $adds{$newitem} = 1;
16863:             }
16864:         }
16865:     }
16866:     if ($env{'form.instcode'} eq '1') {
16867:         if (ref($cathash) eq 'HASH') {
16868:             my $newitem = 'instcode::0';
16869:             if ($cathash->{$newitem} eq '') {  
16870:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
16871:                 $adds{$newitem} = 1;
16872:             }
16873:         } else {
16874:             my $newitem = 'instcode::0';
16875:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
16876:             $adds{$newitem} = 1;
16877:         }
16878:     }
16879:     if ($env{'form.communities'} eq '1') {
16880:         if (ref($cathash) eq 'HASH') {
16881:             my $newitem = 'communities::0';
16882:             if ($cathash->{$newitem} eq '') {
16883:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
16884:                 $adds{$newitem} = 1;
16885:             }
16886:         } else {
16887:             my $newitem = 'communities::0';
16888:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
16889:             $adds{$newitem} = 1;
16890:         }
16891:     }
16892:     if ($env{'form.placement'} eq '1') {
16893:         if (ref($cathash) eq 'HASH') {
16894:             my $newitem = 'placement::0';
16895:             if ($cathash->{$newitem} eq '') {
16896:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
16897:                 $adds{$newitem} = 1;
16898:             }
16899:         } else {
16900:             my $newitem = 'placement::0';
16901:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
16902:             $adds{$newitem} = 1;
16903:         }
16904:     }
16905:     if ($env{'form.addcategory_name'} ne '') {
16906:         if (($env{'form.addcategory_name'} ne 'instcode') &&
16907:             ($env{'form.addcategory_name'} ne 'communities') &&
16908:             ($env{'form.addcategory_name'} ne 'placement')) {
16909:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
16910:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
16911:             $adds{$newitem} = 1;
16912:         }
16913:     }
16914:     my $putresult;
16915:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
16916:         if (keys(%deletions) > 0) {
16917:             foreach my $key (keys(%deletions)) {
16918:                 if ($predelallitems{$key} ne '') {
16919:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
16920:                 }
16921:             }
16922:         }
16923:         my (@chkcats,@chktrails,%chkallitems);
16924:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
16925:         if (ref($chkcats[0]) eq 'ARRAY') {
16926:             my $depth = 0;
16927:             my $chg = 0;
16928:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
16929:                 my $name = $chkcats[0][$i];
16930:                 my $item;
16931:                 if ($name eq '') {
16932:                     $chg ++;
16933:                 } else {
16934:                     $item = &escape($name).'::0';
16935:                     if ($chg) {
16936:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
16937:                     }
16938:                     $depth ++; 
16939:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
16940:                     $depth --;
16941:                 }
16942:             }
16943:         }
16944:     }
16945:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
16946:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
16947:         if ($putresult eq 'ok') {
16948:             my %title = (
16949:                          togglecats     => 'Show/Hide a course in catalog',
16950:                          categorize     => 'Assign a category to a course',
16951:                          togglecatscomm => 'Show/Hide a community in catalog',
16952:                          categorizecomm => 'Assign a category to a community',
16953:                         );
16954:             my %level = (
16955:                          dom  => 'set in Domain ("Modify Course/Community")',
16956:                          crs  => 'set in Course ("Course Configuration")',
16957:                          comm => 'set in Community ("Community Configuration")',
16958:                          none     => 'No catalog',
16959:                          std      => 'Standard catalog',
16960:                          domonly  => 'Domain-only catalog',
16961:                          codesrch => 'Code search form',
16962:                         );
16963:             $resulttext = &mt('Changes made:').'<ul>';
16964:             if ($changes{'togglecats'}) {
16965:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
16966:             }
16967:             if ($changes{'categorize'}) {
16968:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
16969:             }
16970:             if ($changes{'togglecatscomm'}) {
16971:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
16972:             }
16973:             if ($changes{'categorizecomm'}) {
16974:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
16975:             }
16976:             if ($changes{'unauth'}) {
16977:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
16978:             }
16979:             if ($changes{'auth'}) {
16980:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
16981:             }
16982:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
16983:                 my $cathash;
16984:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
16985:                     $cathash = $domconfig{'coursecategories'}{'cats'};
16986:                 } else {
16987:                     $cathash = {};
16988:                 } 
16989:                 my (@cats,@trails,%allitems);
16990:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
16991:                 if (keys(%deletions) > 0) {
16992:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
16993:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
16994:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
16995:                     }
16996:                     $resulttext .= '</ul></li>';
16997:                 }
16998:                 if (keys(%reorderings) > 0) {
16999:                     my %sort_by_trail;
17000:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
17001:                     foreach my $key (keys(%reorderings)) {
17002:                         if ($allitems{$key} ne '') {
17003:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
17004:                         }
17005:                     }
17006:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
17007:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
17008:                     }
17009:                     $resulttext .= '</ul></li>';
17010:                 }
17011:                 if (keys(%adds) > 0) {
17012:                     my %sort_by_trail;
17013:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
17014:                     foreach my $key (keys(%adds)) {
17015:                         if ($allitems{$key} ne '') {
17016:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
17017:                         }
17018:                     }
17019:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
17020:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
17021:                     }
17022:                     $resulttext .= '</ul></li>';
17023:                 }
17024:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
17025:                 if (ref($lastactref) eq 'HASH') {
17026:                     $lastactref->{'cats'} = 1;
17027:                 }
17028:             }
17029:             $resulttext .= '</ul>';
17030:             if ($changes{'unauth'} || $changes{'auth'}) {
17031:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
17032:                 if ($changes{'auth'}) {
17033:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
17034:                 }
17035:                 if ($changes{'unauth'}) {
17036:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
17037:                 }
17038:                 my $cachetime = 24*60*60;
17039:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17040:                 if (ref($lastactref) eq 'HASH') {
17041:                     $lastactref->{'domdefaults'} = 1;
17042:                 }
17043:             }
17044:         } else {
17045:             $resulttext = '<span class="LC_error">'.
17046:                           &mt('An error occurred: [_1]',$putresult).'</span>';
17047:         }
17048:     } else {
17049:         $resulttext = &mt('No changes made to course and community categories');
17050:     }
17051:     return $resulttext;
17052: }
17053: 
17054: sub modify_serverstatuses {
17055:     my ($dom,%domconfig) = @_;
17056:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
17057:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
17058:         %currserverstatus = %{$domconfig{'serverstatuses'}};
17059:     }
17060:     my @pages = &serverstatus_pages();
17061:     foreach my $type (@pages) {
17062:         $newserverstatus{$type}{'namedusers'} = '';
17063:         $newserverstatus{$type}{'machines'} = '';
17064:         if (defined($env{'form.'.$type.'_namedusers'})) {
17065:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
17066:             my @okusers;
17067:             foreach my $user (@users) {
17068:                 my ($uname,$udom) = split(/:/,$user);
17069:                 if (($udom =~ /^$match_domain$/) &&   
17070:                     (&Apache::lonnet::domain($udom)) &&
17071:                     ($uname =~ /^$match_username$/)) {
17072:                     if (!grep(/^\Q$user\E/,@okusers)) {
17073:                         push(@okusers,$user);
17074:                     }
17075:                 }
17076:             }
17077:             if (@okusers > 0) {
17078:                  @okusers = sort(@okusers);
17079:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
17080:             }
17081:         }
17082:         if (defined($env{'form.'.$type.'_machines'})) {
17083:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
17084:             my @okmachines;
17085:             foreach my $ip (@machines) {
17086:                 my @parts = split(/\./,$ip);
17087:                 next if (@parts < 4);
17088:                 my $badip = 0;
17089:                 for (my $i=0; $i<4; $i++) {
17090:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
17091:                         $badip = 1;
17092:                         last;
17093:                     }
17094:                 }
17095:                 if (!$badip) {
17096:                     push(@okmachines,$ip);     
17097:                 }
17098:             }
17099:             @okmachines = sort(@okmachines);
17100:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
17101:         }
17102:     }
17103:     my %serverstatushash =  (
17104:                                 serverstatuses => \%newserverstatus,
17105:                             );
17106:     foreach my $type (@pages) {
17107:         foreach my $setting ('namedusers','machines') {
17108:             my (@current,@new);
17109:             if (ref($currserverstatus{$type}) eq 'HASH') {
17110:                 if ($currserverstatus{$type}{$setting} ne '') { 
17111:                     @current = split(/,/,$currserverstatus{$type}{$setting});
17112:                 }
17113:             }
17114:             if ($newserverstatus{$type}{$setting} ne '') {
17115:                 @new = split(/,/,$newserverstatus{$type}{$setting});
17116:             }
17117:             if (@current > 0) {
17118:                 if (@new > 0) {
17119:                     foreach my $item (@current) {
17120:                         if (!grep(/^\Q$item\E$/,@new)) {
17121:                             $changes{$type}{$setting} = 1;
17122:                             last;
17123:                         }
17124:                     }
17125:                     foreach my $item (@new) {
17126:                         if (!grep(/^\Q$item\E$/,@current)) {
17127:                             $changes{$type}{$setting} = 1;
17128:                             last;
17129:                         }
17130:                     }
17131:                 } else {
17132:                     $changes{$type}{$setting} = 1;
17133:                 }
17134:             } elsif (@new > 0) {
17135:                 $changes{$type}{$setting} = 1;
17136:             }
17137:         }
17138:     }
17139:     if (keys(%changes) > 0) {
17140:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
17141:         my $putresult = &Apache::lonnet::put_dom('configuration',
17142:                                                  \%serverstatushash,$dom);
17143:         if ($putresult eq 'ok') {
17144:             $resulttext .= &mt('Changes made:').'<ul>';
17145:             foreach my $type (@pages) {
17146:                 if (ref($changes{$type}) eq 'HASH') {
17147:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
17148:                     if ($changes{$type}{'namedusers'}) {
17149:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
17150:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
17151:                         } else {
17152:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
17153:                         }
17154:                     }
17155:                     if ($changes{$type}{'machines'}) {
17156:                         if ($newserverstatus{$type}{'machines'} eq '') {
17157:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
17158:                         } else {
17159:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
17160:                         }
17161: 
17162:                     }
17163:                     $resulttext .= '</ul></li>';
17164:                 }
17165:             }
17166:             $resulttext .= '</ul>';
17167:         } else {
17168:             $resulttext = '<span class="LC_error">'.
17169:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
17170: 
17171:         }
17172:     } else {
17173:         $resulttext = &mt('No changes made to access to server status pages');
17174:     }
17175:     return $resulttext;
17176: }
17177: 
17178: sub modify_helpsettings {
17179:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
17180:     my ($resulttext,$errors,%changes,%helphash);
17181:     my %defaultchecked = ('submitbugs' => 'on');
17182:     my @offon = ('off','on');
17183:     my @toggles = ('submitbugs');
17184:     my %current = ('submitbugs' => '',
17185:                    'adhoc'      => {},
17186:                   );
17187:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
17188:         %current = %{$domconfig{'helpsettings'}};
17189:     }
17190:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
17191:     foreach my $item (@toggles) {
17192:         if ($defaultchecked{$item} eq 'on') { 
17193:             if ($current{$item} eq '') {
17194:                 if ($env{'form.'.$item} eq '0') {
17195:                     $changes{$item} = 1;
17196:                 }
17197:             } elsif ($current{$item} ne $env{'form.'.$item}) {
17198:                 $changes{$item} = 1;
17199:             }
17200:         } elsif ($defaultchecked{$item} eq 'off') {
17201:             if ($current{$item} eq '') {
17202:                 if ($env{'form.'.$item} eq '1') {
17203:                     $changes{$item} = 1;
17204:                 }
17205:             } elsif ($current{$item} ne $env{'form.'.$item}) {
17206:                 $changes{$item} = 1;
17207:             }
17208:         }
17209:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
17210:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
17211:         }
17212:     }
17213:     my $maxnum = $env{'form.helproles_maxnum'};
17214:     my $confname = $dom.'-domainconfig';
17215:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
17216:     my (@allpos,%newsettings,%changedprivs,$newrole);
17217:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
17218:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
17219:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
17220:     my %lt = &Apache::lonlocal::texthash(
17221:                     s      => 'system',
17222:                     d      => 'domain',
17223:                     order  => 'Display order',
17224:                     access => 'Role usage',
17225:                     all    => 'All with domain helpdesk or helpdesk assistant role',
17226:                     dh     => 'All with domain helpdesk role',
17227:                     da     => 'All with domain helpdesk assistant role',
17228:                     none   => 'None',
17229:                     status => 'Determined based on institutional status',
17230:                     inc    => 'Include all, but exclude specific personnel',
17231:                     exc    => 'Exclude all, but include specific personnel',
17232:     );
17233:     for (my $num=0; $num<=$maxnum; $num++) {
17234:         my ($prefix,$identifier,$rolename,%curr);
17235:         if ($num == $maxnum) {
17236:             next unless ($env{'form.newcusthelp'} == $maxnum);
17237:             $identifier = 'custhelp'.$num;
17238:             $prefix = 'helproles_'.$num;
17239:             $rolename = $env{'form.custhelpname'.$num};
17240:             $rolename=~s/[^A-Za-z0-9]//gs;
17241:             next if ($rolename eq '');
17242:             next if (exists($existing{'rolesdef_'.$rolename}));
17243:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
17244:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
17245:                                                      $newprivs{'c'},$confname,$dom);
17246:             if ($result ne 'ok') {
17247:                 $errors .= '<li><span class="LC_error">'.
17248:                            &mt('An error occurred storing the new custom role: [_1]',
17249:                            $result).'</span></li>';
17250:                 next;
17251:             } else {
17252:                 $changedprivs{$rolename} = \%newprivs;
17253:                 $newrole = $rolename;
17254:             }
17255:         } else {
17256:             $prefix = 'helproles_'.$num;
17257:             $rolename = $env{'form.'.$prefix};
17258:             next if ($rolename eq '');
17259:             next unless (exists($existing{'rolesdef_'.$rolename}));
17260:             $identifier = 'custhelp'.$num;
17261:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
17262:             my %currprivs;
17263:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
17264:                 split(/\_/,$existing{'rolesdef_'.$rolename});
17265:             foreach my $level ('c','d','s') {
17266:                 if ($newprivs{$level} ne $currprivs{$level}) {
17267:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
17268:                                                              $newprivs{'c'},$confname,$dom);
17269:                     if ($result ne 'ok') {
17270:                         $errors .= '<li><span class="LC_error">'.
17271:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
17272:                                        $rolename,$result).'</span></li>';
17273:                     } else {
17274:                         $changedprivs{$rolename} = \%newprivs;
17275:                     }
17276:                     last;
17277:                 }
17278:             }
17279:             if (ref($current{'adhoc'}) eq 'HASH') {
17280:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
17281:                     %curr = %{$current{'adhoc'}{$rolename}};
17282:                 }
17283:             }
17284:         }
17285:         my $newpos = $env{'form.'.$prefix.'_pos'};
17286:         $newpos =~ s/\D+//g;
17287:         $allpos[$newpos] = $rolename;
17288:         my $newdesc = $env{'form.'.$prefix.'_desc'};
17289:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
17290:         if ($curr{'desc'}) {
17291:             if ($curr{'desc'} ne $newdesc) {
17292:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
17293:                 $newsettings{$rolename}{'desc'} = $newdesc;
17294:             }
17295:         } elsif ($newdesc ne '') {
17296:             $changes{'customrole'}{$rolename}{'desc'} = 1;
17297:             $newsettings{$rolename}{'desc'} = $newdesc;
17298:         }
17299:         my $access = $env{'form.'.$prefix.'_access'};
17300:         if (grep(/^\Q$access\E$/,@accesstypes)) {
17301:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
17302:             if ($access eq 'status') {
17303:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
17304:                 if (scalar(@statuses) == 0) {
17305:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
17306:                 } else {
17307:                     my (@shownstatus,$numtypes);
17308:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
17309:                     if (ref($types) eq 'ARRAY') {
17310:                         $numtypes = scalar(@{$types});
17311:                         foreach my $type (sort(@statuses)) {
17312:                             if ($type eq 'default') {
17313:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
17314:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
17315:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
17316:                                 push(@shownstatus,$usertypes->{$type});
17317:                             }
17318:                         }
17319:                     }
17320:                     if (grep(/^default$/,@statuses)) {
17321:                         push(@shownstatus,$othertitle);
17322:                     }
17323:                     if (scalar(@shownstatus) == 1+$numtypes) {
17324:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
17325:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
17326:                     } else {
17327:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
17328:                         if (ref($curr{'status'}) eq 'ARRAY') {
17329:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
17330:                             if (@diffs) {
17331:                                 $changes{'customrole'}{$rolename}{$access} = 1;
17332:                             }
17333:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
17334:                             $changes{'customrole'}{$rolename}{$access} = 1;
17335:                         }
17336:                     }
17337:                 }
17338:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
17339:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
17340:                 my @newspecstaff;
17341:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
17342:                 foreach my $person (sort(@personnel)) {
17343:                     if ($domhelpdesk{$person}) {
17344:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
17345:                     }
17346:                 }
17347:                 if (ref($curr{$access}) eq 'ARRAY') {
17348:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
17349:                     if (@diffs) {
17350:                         $changes{'customrole'}{$rolename}{$access} = 1;
17351:                     }
17352:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
17353:                     $changes{'customrole'}{$rolename}{$access} = 1;
17354:                 }
17355:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
17356:                     my ($uname,$udom) = split(/:/,$person);
17357:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
17358:                 }
17359:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
17360:             }
17361:         } else {
17362:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
17363:         }
17364:         unless ($curr{'access'} eq $access) {
17365:             $changes{'customrole'}{$rolename}{'access'} = 1;
17366:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
17367:         }
17368:     }
17369:     if (@allpos > 0) {
17370:         my $idx = 0;
17371:         foreach my $rolename (@allpos) {
17372:             if ($rolename ne '') {
17373:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
17374:                 if (ref($current{'adhoc'}) eq 'HASH') {
17375:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
17376:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
17377:                             $changes{'customrole'}{$rolename}{'order'} = 1;
17378:                             $newsettings{$rolename}{'order'} = $idx+1;
17379:                         }
17380:                     }
17381:                 }
17382:                 $idx ++;
17383:             }
17384:         }
17385:     }
17386:     my $putresult;
17387:     if (keys(%changes) > 0) {
17388:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
17389:         if ($putresult eq 'ok') {
17390:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
17391:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
17392:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
17393:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
17394:                 }
17395:             }
17396:             my $cachetime = 24*60*60;
17397:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17398:             if (ref($lastactref) eq 'HASH') {
17399:                 $lastactref->{'domdefaults'} = 1;
17400:             }
17401:         } else {
17402:             $errors .= '<li><span class="LC_error">'.
17403:                        &mt('An error occurred storing the settings: [_1]',
17404:                            $putresult).'</span></li>';
17405:         }
17406:     }
17407:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
17408:         $resulttext = &mt('Changes made:').'<ul>';
17409:         my (%shownprivs,@levelorder);
17410:         @levelorder = ('c','d','s');
17411:         if ((keys(%changes)) && ($putresult eq 'ok')) {
17412:             foreach my $item (sort(keys(%changes))) {
17413:                 if ($item eq 'submitbugs') {
17414:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
17415:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
17416:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
17417:                 } elsif ($item eq 'customrole') {
17418:                     if (ref($changes{'customrole'}) eq 'HASH') {
17419:                         my @keyorder = ('order','desc','access','status','exc','inc');
17420:                         my %keytext = &Apache::lonlocal::texthash(
17421:                                                                    order  => 'Order',
17422:                                                                    desc   => 'Role description',
17423:                                                                    access => 'Role usage',
17424:                                                                    status => 'Allowed institutional types',
17425:                                                                    exc    => 'Allowed personnel',
17426:                                                                    inc    => 'Disallowed personnel',
17427:                         );
17428:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
17429:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
17430:                                 if ($role eq $newrole) {
17431:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
17432:                                                               $role).'<ul>';
17433:                                 } else {
17434:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
17435:                                                               $role).'<ul>';
17436:                                 }
17437:                                 foreach my $key (@keyorder) {
17438:                                     if ($changes{'customrole'}{$role}{$key}) {
17439:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
17440:                                                                   $keytext{$key},$newsettings{$role}{$key}).
17441:                                                        '</li>';
17442:                                     }
17443:                                 }
17444:                                 if (ref($changedprivs{$role}) eq 'HASH') {
17445:                                     $shownprivs{$role} = 1;
17446:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
17447:                                     foreach my $level (@levelorder) {
17448:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
17449:                                             next if ($item eq '');
17450:                                             my ($priv) = split(/\&/,$item,2);
17451:                                             if (&Apache::lonnet::plaintext($priv)) {
17452:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
17453:                                                 unless ($level eq 'c') {
17454:                                                     $resulttext .= ' ('.$lt{$level}.')';
17455:                                                 }
17456:                                                 $resulttext .= '</li>';
17457:                                             }
17458:                                         }
17459:                                     }
17460:                                     $resulttext .= '</ul>';
17461:                                 }
17462:                                 $resulttext .= '</ul></li>';
17463:                             }
17464:                         }
17465:                     }
17466:                 }
17467:             }
17468:         }
17469:         if (keys(%changedprivs)) {
17470:             foreach my $role (sort(keys(%changedprivs))) {
17471:                 unless ($shownprivs{$role}) {
17472:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
17473:                                               $role).'<ul>'.
17474:                                    '<li>'.&mt('Privileges set to :').'<ul>';
17475:                     foreach my $level (@levelorder) {
17476:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
17477:                             next if ($item eq '');
17478:                             my ($priv) = split(/\&/,$item,2);
17479:                             if (&Apache::lonnet::plaintext($priv)) {
17480:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
17481:                                 unless ($level eq 'c') {
17482:                                     $resulttext .= ' ('.$lt{$level}.')';
17483:                                 }
17484:                                 $resulttext .= '</li>';
17485:                             }
17486:                         }
17487:                     }
17488:                     $resulttext .= '</ul></li></ul></li>';
17489:                 }
17490:             }
17491:         }
17492:         $resulttext .= '</ul>';
17493:     } else {
17494:         $resulttext = &mt('No changes made to help settings');
17495:     }
17496:     if ($errors) {
17497:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
17498:                                     $errors.'</ul>';
17499:     }
17500:     return $resulttext;
17501: }
17502: 
17503: sub modify_coursedefaults {
17504:     my ($dom,$lastactref,%domconfig) = @_;
17505:     my ($resulttext,$errors,%changes,%defaultshash);
17506:     my %defaultchecked = (
17507:                            'canuse_pdfforms' => 'off',
17508:                            'uselcmath'       => 'on',
17509:                            'usejsme'         => 'on'
17510:                          );
17511:     my @toggles = ('canuse_pdfforms','uselcmath','usejsme');
17512:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
17513:                    'uploadquota_community','uploadquota_textbook','uploadquota_placement',
17514:                    'mysqltables_official','mysqltables_unofficial','mysqltables_community',
17515:                    'mysqltables_textbook','mysqltables_placement');
17516:     my @types = ('official','unofficial','community','textbook','placement');
17517:     my %staticdefaults = (
17518:                            anonsurvey_threshold => 10,
17519:                            uploadquota          => 500,
17520:                            postsubmit           => 60,
17521:                            mysqltables          => 172800,
17522:                          );
17523:     my %texoptions = (
17524:                         MathJax  => 'MathJax',
17525:                         mimetex  => &mt('Convert to Images'),
17526:                         tth      => &mt('TeX to HTML'),
17527:                      );
17528:     $defaultshash{'coursedefaults'} = {};
17529: 
17530:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
17531:         if ($domconfig{'coursedefaults'} eq '') {
17532:             $domconfig{'coursedefaults'} = {};
17533:         }
17534:     }
17535: 
17536:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
17537:         foreach my $item (@toggles) {
17538:             if ($defaultchecked{$item} eq 'on') {
17539:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
17540:                     ($env{'form.'.$item} eq '0')) {
17541:                     $changes{$item} = 1;
17542:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
17543:                     $changes{$item} = 1;
17544:                 }
17545:             } elsif ($defaultchecked{$item} eq 'off') {
17546:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
17547:                     ($env{'form.'.$item} eq '1')) {
17548:                     $changes{$item} = 1;
17549:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
17550:                     $changes{$item} = 1;
17551:                 }
17552:             }
17553:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
17554:         }
17555:         foreach my $item (@numbers) {
17556:             my ($currdef,$newdef);
17557:             $newdef = $env{'form.'.$item};
17558:             if ($item eq 'anonsurvey_threshold') {
17559:                 $currdef = $domconfig{'coursedefaults'}{$item};
17560:                 $newdef =~ s/\D//g;
17561:                 if ($newdef eq '' || $newdef < 1) {
17562:                     $newdef = 1;
17563:                 }
17564:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
17565:             } else {
17566:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
17567:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
17568:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
17569:                 }
17570:                 $newdef =~ s/[^\w.\-]//g;
17571:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
17572:             }
17573:             if ($currdef ne $newdef) {
17574:                 if ($item eq 'anonsurvey_threshold') {
17575:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
17576:                         $changes{$item} = 1;
17577:                     }
17578:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
17579:                     my $setting = $1;
17580:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
17581:                         $changes{$setting} = 1;
17582:                     }
17583:                 }
17584:             }
17585:         }
17586:         my $texengine;
17587:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
17588:             $texengine = $env{'form.texengine'};
17589:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
17590:             if ($currdef eq '') {
17591:                 unless ($texengine eq $Apache::lonnet::deftex) {
17592:                     $changes{'texengine'} = 1;
17593:                 }
17594:             } elsif ($currdef ne $texengine) {
17595:                 $changes{'texengine'} = 1;
17596:             }
17597:         }
17598:         if ($texengine ne '') {
17599:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
17600:         }
17601:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
17602:         my @currclonecode;
17603:         if (ref($currclone) eq 'HASH') {
17604:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
17605:                 @currclonecode = @{$currclone->{'instcode'}};
17606:             }
17607:         }
17608:         my $newclone;
17609:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
17610:             $newclone = $env{'form.canclone'};
17611:         }
17612:         if ($newclone eq 'instcode') {
17613:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
17614:             my (%codedefaults,@code_order,@clonecode);
17615:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
17616:                                                     \@code_order);
17617:             foreach my $item (@code_order) {
17618:                 if (grep(/^\Q$item\E$/,@newcodes)) {
17619:                     push(@clonecode,$item);
17620:                 }
17621:             }
17622:             if (@clonecode) {
17623:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
17624:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
17625:                 if (@diffs) {
17626:                     $changes{'canclone'} = 1;
17627:                 }
17628:             } else {
17629:                 $newclone eq '';
17630:             }
17631:         } elsif ($newclone ne '') {
17632:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
17633:         }
17634:         if ($newclone ne $currclone) {
17635:             $changes{'canclone'} = 1;
17636:         }
17637:         my %credits;
17638:         foreach my $type (@types) {
17639:             unless ($type eq 'community') {
17640:                 $credits{$type} = $env{'form.'.$type.'_credits'};
17641:                 $credits{$type} =~ s/[^\d.]+//g;
17642:             }
17643:         }
17644:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
17645:             ($env{'form.coursecredits'} eq '1')) {
17646:             $changes{'coursecredits'} = 1;
17647:             foreach my $type (keys(%credits)) {
17648:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
17649:             }
17650:         } else {
17651:             if ($env{'form.coursecredits'} eq '1') {
17652:                 foreach my $type (@types) {
17653:                     unless ($type eq 'community') {
17654:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
17655:                             $changes{'coursecredits'} = 1;
17656:                         }
17657:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
17658:                     }
17659:                 }
17660:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
17661:                 foreach my $type (@types) {
17662:                     unless ($type eq 'community') {
17663:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
17664:                             $changes{'coursecredits'} = 1;
17665:                             last;
17666:                         }
17667:                     }
17668:                 }
17669:             }
17670:         }
17671:         if ($env{'form.postsubmit'} eq '1') {
17672:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
17673:             my %currtimeout;
17674:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
17675:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
17676:                     $changes{'postsubmit'} = 1;
17677:                 }
17678:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
17679:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
17680:                 }
17681:             } else {
17682:                 $changes{'postsubmit'} = 1;
17683:             }
17684:             foreach my $type (@types) {
17685:                 my $timeout = $env{'form.'.$type.'_timeout'};
17686:                 $timeout =~ s/\D//g;
17687:                 if ($timeout == $staticdefaults{'postsubmit'}) {
17688:                     $timeout = '';
17689:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
17690:                     $timeout = '0';
17691:                 }
17692:                 unless ($timeout eq '') {
17693:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
17694:                 }
17695:                 if (exists($currtimeout{$type})) {
17696:                     if ($timeout ne $currtimeout{$type}) {
17697:                         $changes{'postsubmit'} = 1;
17698:                     }
17699:                 } elsif ($timeout ne '') {
17700:                     $changes{'postsubmit'} = 1;
17701:                 }
17702:             }
17703:         } else {
17704:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
17705:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
17706:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
17707:                     $changes{'postsubmit'} = 1;
17708:                 }
17709:             } else {
17710:                 $changes{'postsubmit'} = 1;
17711:             }
17712:         }
17713:     }
17714:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
17715:                                              $dom);
17716:     if ($putresult eq 'ok') {
17717:         if (keys(%changes) > 0) {
17718:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
17719:             if (($changes{'canuse_pdfforms'}) || ($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
17720:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
17721:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'})) {
17722:                 foreach my $item ('canuse_pdfforms','uselcmath','usejsme','texengine') {
17723:                     if ($changes{$item}) {
17724:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
17725:                     }
17726:                 }
17727:                 if ($changes{'coursecredits'}) {
17728:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
17729:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
17730:                             $domdefaults{$type.'credits'} =
17731:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
17732:                         }
17733:                     }
17734:                 }
17735:                 if ($changes{'postsubmit'}) {
17736:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
17737:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
17738:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
17739:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
17740:                                 $domdefaults{$type.'postsubtimeout'} =
17741:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
17742:                             }
17743:                         }
17744:                     }
17745:                 }
17746:                 if ($changes{'uploadquota'}) {
17747:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
17748:                         foreach my $type (@types) {
17749:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
17750:                         }
17751:                     }
17752:                 }
17753:                 if ($changes{'canclone'}) {
17754:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
17755:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
17756:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
17757:                             if (@clonecodes) {
17758:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
17759:                             }
17760:                         }
17761:                     } else {
17762:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
17763:                     }
17764:                 }
17765:                 my $cachetime = 24*60*60;
17766:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17767:                 if (ref($lastactref) eq 'HASH') {
17768:                     $lastactref->{'domdefaults'} = 1;
17769:                 }
17770:             }
17771:             $resulttext = &mt('Changes made:').'<ul>';
17772:             foreach my $item (sort(keys(%changes))) {
17773:                 if ($item eq 'canuse_pdfforms') {
17774:                     if ($env{'form.'.$item} eq '1') {
17775:                         $resulttext .= '<li>'.&mt("Course/Community users can create/upload PDF forms set to 'on'").'</li>';
17776:                     } else {
17777:                         $resulttext .= '<li>'.&mt('Course/Community users can create/upload PDF forms set to "off"').'</li>';
17778:                     }
17779:                 } elsif ($item eq 'uselcmath') {
17780:                     if ($env{'form.'.$item} eq '1') {
17781:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
17782:                     } else {
17783:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
17784:                     }
17785:                 } elsif ($item eq 'usejsme') {
17786:                     if ($env{'form.'.$item} eq '1') {
17787:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
17788:                     } else {
17789:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
17790:                     }
17791:                 } elsif ($item eq 'texengine') {
17792:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
17793:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
17794:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
17795:                     }
17796:                 } elsif ($item eq 'anonsurvey_threshold') {
17797:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
17798:                 } elsif ($item eq 'uploadquota') {
17799:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
17800:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
17801:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
17802:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
17803:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
17804:                                        '<li>'.&mt('Placement tests: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'placement'}.'</b>').'</li>'. 
17805:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
17806:                                        '</ul>'.
17807:                                        '</li>';
17808:                     } else {
17809:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
17810:                     }
17811:                 } elsif ($item eq 'mysqltables') {
17812:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
17813:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
17814:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
17815:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
17816:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
17817:                                        '<li>'.&mt('Placement tests: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'placement'}.'</b>').'</li>'.
17818:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
17819:                                        '</ul>'.
17820:                                        '</li>';
17821:                     } else {
17822:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
17823:                     }
17824:                 } elsif ($item eq 'postsubmit') {
17825:                     if ($domdefaults{'postsubmit'} eq 'off') {
17826:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
17827:                     } else {
17828:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
17829:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
17830:                             $resulttext .= &mt('durations:').'<ul>';
17831:                             foreach my $type (@types) {
17832:                                 $resulttext .= '<li>';
17833:                                 my $timeout;
17834:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
17835:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
17836:                                 }
17837:                                 my $display;
17838:                                 if ($timeout eq '0') {
17839:                                     $display = &mt('unlimited');
17840:                                 } elsif ($timeout eq '') {
17841:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
17842:                                 } else {
17843:                                     $display = &mt('[quant,_1,second]',$timeout);
17844:                                 }
17845:                                 if ($type eq 'community') {
17846:                                     $resulttext .= &mt('Communities');
17847:                                 } elsif ($type eq 'official') {
17848:                                     $resulttext .= &mt('Official courses');
17849:                                 } elsif ($type eq 'unofficial') {
17850:                                     $resulttext .= &mt('Unofficial courses');
17851:                                 } elsif ($type eq 'textbook') {
17852:                                     $resulttext .= &mt('Textbook courses');
17853:                                 } elsif ($type eq 'placement') {
17854:                                     $resulttext .= &mt('Placement tests');
17855:                                 }
17856:                                 $resulttext .= ' -- '.$display.'</li>';
17857:                             }
17858:                             $resulttext .= '</ul>';
17859:                         }
17860:                         $resulttext .= '</li>';
17861:                     }
17862:                 } elsif ($item eq 'coursecredits') {
17863:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
17864:                         if (($domdefaults{'officialcredits'} eq '') &&
17865:                             ($domdefaults{'unofficialcredits'} eq '') &&
17866:                             ($domdefaults{'textbookcredits'} eq '')) {
17867:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
17868:                         } else {
17869:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
17870:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
17871:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
17872:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
17873:                                            '</ul>'.
17874:                                            '</li>';
17875:                         }
17876:                     } else {
17877:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
17878:                     }
17879:                 } elsif ($item eq 'canclone') {
17880:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
17881:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
17882:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
17883:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
17884:                         }
17885:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
17886:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
17887:                     } else {
17888:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
17889:                     }
17890:                 }
17891:             }
17892:             $resulttext .= '</ul>';
17893:         } else {
17894:             $resulttext = &mt('No changes made to course defaults');
17895:         }
17896:     } else {
17897:         $resulttext = '<span class="LC_error">'.
17898:             &mt('An error occurred: [_1]',$putresult).'</span>';
17899:     }
17900:     return $resulttext;
17901: }
17902: 
17903: sub modify_selfenrollment {
17904:     my ($dom,$lastactref,%domconfig) = @_;
17905:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
17906:     my @types = ('official','unofficial','community','textbook','placement');
17907:     my %titles = &tool_titles();
17908:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
17909:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
17910:     $ordered{'default'} = ['types','registered','approval','limit'];
17911: 
17912:     my (%roles,%shown,%toplevel);
17913:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
17914: 
17915:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
17916:         if ($domconfig{'selfenrollment'} eq '') {
17917:             $domconfig{'selfenrollment'} = {};
17918:         }
17919:     }
17920:     %toplevel = (
17921:                   admin      => 'Configuration Rights',
17922:                   default    => 'Default settings',
17923:                   validation => 'Validation of self-enrollment requests',
17924:                 );
17925:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
17926: 
17927:     if (ref($ordered{'admin'}) eq 'ARRAY') {
17928:         foreach my $item (@{$ordered{'admin'}}) {
17929:             foreach my $type (@types) {
17930:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
17931:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
17932:                 } else {
17933:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
17934:                 }
17935:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
17936:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
17937:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
17938:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
17939:                             push(@{$changes{'admin'}{$type}},$item);
17940:                         }
17941:                     } else {
17942:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
17943:                             push(@{$changes{'admin'}{$type}},$item);
17944:                         }
17945:                     }
17946:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
17947:                     push(@{$changes{'admin'}{$type}},$item);
17948:                 }
17949:             }
17950:         }
17951:     }
17952: 
17953:     foreach my $item (@{$ordered{'default'}}) {
17954:         foreach my $type (@types) {
17955:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
17956:             if ($item eq 'types') {
17957:                 unless (($value eq 'all') || ($value eq 'dom')) {
17958:                     $value = '';
17959:                 }
17960:             } elsif ($item eq 'registered') {
17961:                 unless ($value eq '1') {
17962:                     $value = 0;
17963:                 }
17964:             } elsif ($item eq 'approval') {
17965:                 unless ($value =~ /^[012]$/) {
17966:                     $value = 0;
17967:                 }
17968:             } else {
17969:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
17970:                     $value = 'none';
17971:                 }
17972:             }
17973:             $selfenrollhash{'default'}{$type}{$item} = $value;
17974:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
17975:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
17976:                     if ($selfenrollhash{'default'}{$type}{$item} ne
17977:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
17978:                          push(@{$changes{'default'}{$type}},$item);
17979:                     }
17980:                 } else {
17981:                     push(@{$changes{'default'}{$type}},$item);
17982:                 }
17983:             } else {
17984:                 push(@{$changes{'default'}{$type}},$item);
17985:             }
17986:             if ($item eq 'limit') {
17987:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
17988:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
17989:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
17990:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
17991:                     }
17992:                 } else {
17993:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
17994:                 }
17995:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
17996:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
17997:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
17998:                          push(@{$changes{'default'}{$type}},'cap');
17999:                     }
18000:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
18001:                     push(@{$changes{'default'}{$type}},'cap');
18002:                 }
18003:             }
18004:         }
18005:     }
18006: 
18007:     foreach my $item (@{$itemsref}) {
18008:         if ($item eq 'fields') {
18009:             my @changed;
18010:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
18011:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
18012:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
18013:             }
18014:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
18015:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
18016:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
18017:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
18018:                 } else {
18019:                     @changed = @{$selfenrollhash{'validation'}{$item}};
18020:                 }
18021:             } else {
18022:                 @changed = @{$selfenrollhash{'validation'}{$item}};
18023:             }
18024:             if (@changed) {
18025:                 if ($selfenrollhash{'validation'}{$item}) { 
18026:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
18027:                 } else {
18028:                     $changes{'validation'}{$item} = &mt('None');
18029:                 }
18030:             }
18031:         } else {
18032:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
18033:             if ($item eq 'markup') {
18034:                if ($env{'form.selfenroll_validation_'.$item}) {
18035:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
18036:                }
18037:             }
18038:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
18039:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
18040:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
18041:                 }
18042:             }
18043:         }
18044:     }
18045: 
18046:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
18047:                                              $dom);
18048:     if ($putresult eq 'ok') {
18049:         if (keys(%changes) > 0) {
18050:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18051:             $resulttext = &mt('Changes made:').'<ul>';
18052:             foreach my $key ('admin','default','validation') {
18053:                 if (ref($changes{$key}) eq 'HASH') {
18054:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
18055:                     if ($key eq 'validation') {
18056:                         foreach my $item (@{$itemsref}) {
18057:                             if (exists($changes{$key}{$item})) {
18058:                                 if ($item eq 'markup') {
18059:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
18060:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
18061:                                 } else {  
18062:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
18063:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
18064:                                 }
18065:                             }
18066:                         }
18067:                     } else {
18068:                         foreach my $type (@types) {
18069:                             if ($type eq 'community') {
18070:                                 $roles{'1'} = &mt('Community personnel');
18071:                             } else {
18072:                                 $roles{'1'} = &mt('Course personnel');
18073:                             }
18074:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
18075:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
18076:                                     if ($key eq 'admin') {
18077:                                         my @mgrdc = ();
18078:                                         if (ref($ordered{$key}) eq 'ARRAY') {
18079:                                             foreach my $item (@{$ordered{'admin'}}) {
18080:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
18081:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
18082:                                                         push(@mgrdc,$item);
18083:                                                     }
18084:                                                 }
18085:                                             }
18086:                                             if (@mgrdc) {
18087:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
18088:                                             } else {
18089:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
18090:                                             }
18091:                                         }
18092:                                     } else {
18093:                                         if (ref($ordered{$key}) eq 'ARRAY') {
18094:                                             foreach my $item (@{$ordered{$key}}) {
18095:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
18096:                                                     $domdefaults{$type.'selfenroll'.$item} =
18097:                                                         $selfenrollhash{$key}{$type}{$item};
18098:                                                 }
18099:                                             }
18100:                                         }
18101:                                     }
18102:                                 }
18103:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
18104:                                 foreach my $item (@{$ordered{$key}}) {
18105:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
18106:                                         $resulttext .= '<li>';
18107:                                         if ($key eq 'admin') {
18108:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
18109:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
18110:                                         } else {
18111:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
18112:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
18113:                                         }
18114:                                         $resulttext .= '</li>';
18115:                                     }
18116:                                 }
18117:                                 $resulttext .= '</ul></li>';
18118:                             }
18119:                         }
18120:                         $resulttext .= '</ul></li>'; 
18121:                     }
18122:                 }
18123:             }
18124:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
18125:                 my $cachetime = 24*60*60;
18126:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18127:                 if (ref($lastactref) eq 'HASH') {
18128:                     $lastactref->{'domdefaults'} = 1;
18129:                 }
18130:             }
18131:             $resulttext .= '</ul>';
18132:         } else {
18133:             $resulttext = &mt('No changes made to self-enrollment settings');
18134:         }
18135:     } else {
18136:         $resulttext = '<span class="LC_error">'.
18137:             &mt('An error occurred: [_1]',$putresult).'</span>';
18138:     }
18139:     return $resulttext;
18140: }
18141: 
18142: sub modify_usersessions {
18143:     my ($dom,$lastactref,%domconfig) = @_;
18144:     my @hostingtypes = ('version','excludedomain','includedomain');
18145:     my @offloadtypes = ('primary','default');
18146:     my %types = (
18147:                   remote => \@hostingtypes,
18148:                   hosted => \@hostingtypes,
18149:                   spares => \@offloadtypes,
18150:                 );
18151:     my @prefixes = ('remote','hosted','spares');
18152:     my @lcversions = &Apache::lonnet::all_loncaparevs();
18153:     my (%by_ip,%by_location,@intdoms,@instdoms);
18154:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
18155:     my @locations = sort(keys(%by_location));
18156:     my (%defaultshash,%changes);
18157:     foreach my $prefix (@prefixes) {
18158:         $defaultshash{'usersessions'}{$prefix} = {};
18159:     }
18160:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18161:     my $resulttext;
18162:     my %iphost = &Apache::lonnet::get_iphost();
18163:     foreach my $prefix (@prefixes) {
18164:         next if ($prefix eq 'spares');
18165:         foreach my $type (@{$types{$prefix}}) {
18166:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
18167:             if ($type eq 'version') {
18168:                 my $value = $env{'form.'.$prefix.'_'.$type};
18169:                 my $okvalue;
18170:                 if ($value ne '') {
18171:                     if (grep(/^\Q$value\E$/,@lcversions)) {
18172:                         $okvalue = $value;
18173:                     }
18174:                 }
18175:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
18176:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
18177:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
18178:                             if ($inuse == 0) {
18179:                                 $changes{$prefix}{$type} = 1;
18180:                             } else {
18181:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
18182:                                     $changes{$prefix}{$type} = 1;
18183:                                 }
18184:                                 if ($okvalue ne '') {
18185:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
18186:                                 } 
18187:                             }
18188:                         } else {
18189:                             if (($inuse == 1) && ($okvalue ne '')) {
18190:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
18191:                                 $changes{$prefix}{$type} = 1;
18192:                             }
18193:                         }
18194:                     } else {
18195:                         if (($inuse == 1) && ($okvalue ne '')) {
18196:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
18197:                             $changes{$prefix}{$type} = 1;
18198:                         }
18199:                     }
18200:                 } else {
18201:                     if (($inuse == 1) && ($okvalue ne '')) {
18202:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
18203:                         $changes{$prefix}{$type} = 1;
18204:                     }
18205:                 }
18206:             } else {
18207:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
18208:                 my @okvals;
18209:                 foreach my $val (@vals) {
18210:                     if ($val =~ /:/) {
18211:                         my @items = split(/:/,$val);
18212:                         foreach my $item (@items) {
18213:                             if (ref($by_location{$item}) eq 'ARRAY') {
18214:                                 push(@okvals,$item);
18215:                             }
18216:                         }
18217:                     } else {
18218:                         if (ref($by_location{$val}) eq 'ARRAY') {
18219:                             push(@okvals,$val);
18220:                         }
18221:                     }
18222:                 }
18223:                 @okvals = sort(@okvals);
18224:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
18225:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
18226:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
18227:                             if ($inuse == 0) {
18228:                                 $changes{$prefix}{$type} = 1; 
18229:                             } else {
18230:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
18231:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
18232:                                 if (@changed > 0) {
18233:                                     $changes{$prefix}{$type} = 1;
18234:                                 }
18235:                             }
18236:                         } else {
18237:                             if ($inuse == 1) {
18238:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
18239:                                 $changes{$prefix}{$type} = 1;
18240:                             }
18241:                         } 
18242:                     } else {
18243:                         if ($inuse == 1) {
18244:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
18245:                             $changes{$prefix}{$type} = 1;
18246:                         }
18247:                     }
18248:                 } else {
18249:                     if ($inuse == 1) {
18250:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
18251:                         $changes{$prefix}{$type} = 1;
18252:                     }
18253:                 }
18254:             }
18255:         }
18256:     }
18257: 
18258:     my @alldoms = &Apache::lonnet::all_domains();
18259:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
18260:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
18261:     my $savespares;
18262: 
18263:     foreach my $lonhost (sort(keys(%servers))) {
18264:         my $serverhomeID =
18265:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
18266:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
18267:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
18268:         my %spareschg;
18269:         foreach my $type (@{$types{'spares'}}) {
18270:             my @okspares;
18271:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
18272:             foreach my $server (@checked) {
18273:                 if (&Apache::lonnet::hostname($server) ne '') {
18274:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
18275:                         unless (grep(/^\Q$server\E$/,@okspares)) {
18276:                             push(@okspares,$server);
18277:                         }
18278:                     }
18279:                 }
18280:             }
18281:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
18282:             my $newspare;
18283:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
18284:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
18285:                     $newspare = $new;
18286:                 }
18287:             }
18288:             my @spares;
18289:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
18290:                 @spares = sort(@okspares,$newspare);
18291:             } else {
18292:                 @spares = sort(@okspares);
18293:             }
18294:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
18295:             if (ref($spareid{$lonhost}) eq 'HASH') {
18296:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
18297:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
18298:                     if (@diffs > 0) {
18299:                         $spareschg{$type} = 1;
18300:                     }
18301:                 }
18302:             }
18303:         }
18304:         if (keys(%spareschg) > 0) {
18305:             $changes{'spares'}{$lonhost} = \%spareschg;
18306:         }
18307:     }
18308:     $defaultshash{'usersessions'}{'offloadnow'} = {};
18309:     $defaultshash{'usersessions'}{'offloadoth'} = {};
18310:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
18311:     my @okoffload;
18312:     if (@offloadnow) {
18313:         foreach my $server (@offloadnow) {
18314:             if (&Apache::lonnet::hostname($server) ne '') {
18315:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
18316:                     push(@okoffload,$server);
18317:                 }
18318:             }
18319:         }
18320:         if (@okoffload) {
18321:             foreach my $lonhost (@okoffload) {
18322:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
18323:             }
18324:         }
18325:     }
18326:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
18327:     my @okoffloadoth;
18328:     if (@offloadoth) {
18329:         foreach my $server (@offloadoth) {
18330:             if (&Apache::lonnet::hostname($server) ne '') {
18331:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
18332:                     push(@okoffloadoth,$server);
18333:                 }
18334:             }
18335:         }
18336:         if (@okoffloadoth) {
18337:             foreach my $lonhost (@okoffloadoth) {
18338:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
18339:             }
18340:         }
18341:     }
18342:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
18343:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
18344:             if (ref($changes{'spares'}) eq 'HASH') {
18345:                 if (keys(%{$changes{'spares'}}) > 0) {
18346:                     $savespares = 1;
18347:                 }
18348:             }
18349:         } else {
18350:             $savespares = 1;
18351:         }
18352:         foreach my $offload ('offloadnow','offloadoth') {
18353:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
18354:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
18355:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
18356:                         $changes{$offload} = 1;
18357:                         last;
18358:                     }
18359:                 }
18360:                 unless ($changes{$offload}) {
18361:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
18362:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
18363:                             $changes{$offload} = 1;
18364:                             last;
18365:                         }
18366:                     }
18367:                 }
18368:             } else {
18369:                 if (($offload eq 'offloadnow') && (@okoffload)) {
18370:                      $changes{'offloadnow'} = 1;
18371:                 }
18372:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
18373:                     $changes{'offloadoth'} = 1;
18374:                 }
18375:             } 
18376:         }
18377:     } else {
18378:         if (@okoffload) {
18379:             $changes{'offloadnow'} = 1;
18380:         }
18381:         if (@okoffloadoth) {
18382:             $changes{'offloadoth'} = 1;
18383:         }
18384:     }
18385:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
18386:     if ((keys(%changes) > 0) || ($savespares)) {
18387:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
18388:                                                  $dom);
18389:         if ($putresult eq 'ok') {
18390:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
18391:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
18392:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
18393:                 }
18394:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
18395:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
18396:                 }
18397:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
18398:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
18399:                 }
18400:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
18401:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
18402:                 }
18403:             }
18404:             my $cachetime = 24*60*60;
18405:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18406:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
18407:             if (ref($lastactref) eq 'HASH') {
18408:                 $lastactref->{'domdefaults'} = 1;
18409:                 $lastactref->{'usersessions'} = 1;
18410:             }
18411:             if (keys(%changes) > 0) {
18412:                 my %lt = &usersession_titles();
18413:                 $resulttext = &mt('Changes made:').'<ul>';
18414:                 foreach my $prefix (@prefixes) {
18415:                     if (ref($changes{$prefix}) eq 'HASH') {
18416:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
18417:                         if ($prefix eq 'spares') {
18418:                             if (ref($changes{$prefix}) eq 'HASH') {
18419:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
18420:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
18421:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
18422:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
18423:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
18424:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
18425:                                         foreach my $type (@{$types{$prefix}}) {
18426:                                             if ($changes{$prefix}{$lonhost}{$type}) {
18427:                                                 my $offloadto = &mt('None');
18428:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
18429:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
18430:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
18431:                                                     }
18432:                                                 }
18433:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
18434:                                             }
18435:                                         }
18436:                                     }
18437:                                     $resulttext .= '</li>';
18438:                                 }
18439:                             }
18440:                         } else {
18441:                             foreach my $type (@{$types{$prefix}}) {
18442:                                 if (defined($changes{$prefix}{$type})) {
18443:                                     my ($newvalue,$notinuse);
18444:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
18445:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
18446:                                             if ($type eq 'version') {
18447:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
18448:                                             } else {
18449:                                                 if (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
18450:                                                     if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
18451:                                                         $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
18452:                                                     }
18453:                                                 } else {
18454:                                                     $notinuse = 1;
18455:                                                 }
18456:                                             }
18457:                                         }
18458:                                     }
18459:                                     if ($newvalue eq '') {
18460:                                         if ($type eq 'version') {
18461:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
18462:                                         } elsif ($notinuse) {
18463:                                             $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
18464:                                         } else {
18465:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
18466:                                         }
18467:                                     } else {
18468:                                         if ($type eq 'version') {
18469:                                             $newvalue .= ' '.&mt('(or later)');
18470:                                         }
18471:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
18472:                                     }
18473:                                 }
18474:                             }
18475:                         }
18476:                         $resulttext .= '</ul>';
18477:                     }
18478:                 }
18479:                 if ($changes{'offloadnow'}) {
18480:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
18481:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
18482:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
18483:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
18484:                                 $resulttext .= '<li>'.$lonhost.'</li>';
18485:                             }
18486:                             $resulttext .= '</ul>';
18487:                         } else {
18488:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
18489:                         }
18490:                     } else {
18491:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
18492:                     }
18493:                 }
18494:                 if ($changes{'offloadoth'}) {
18495:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
18496:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
18497:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
18498:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
18499:                                 $resulttext .= '<li>'.$lonhost.'</li>';
18500:                             }
18501:                             $resulttext .= '</ul>';
18502:                         } else {
18503:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
18504:                         }
18505:                     } else {
18506:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
18507:                     }
18508:                 }
18509:                 $resulttext .= '</ul>';
18510:             } else {
18511:                 $resulttext = $nochgmsg;
18512:             }
18513:         } else {
18514:             $resulttext = '<span class="LC_error">'.
18515:                           &mt('An error occurred: [_1]',$putresult).'</span>';
18516:         }
18517:     } else {
18518:         $resulttext = $nochgmsg;
18519:     }
18520:     return $resulttext;
18521: }
18522: 
18523: sub modify_ssl {
18524:     my ($dom,$lastactref,%domconfig) = @_;
18525:     my (%by_ip,%by_location,@intdoms,@instdoms);
18526:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
18527:     my @locations = sort(keys(%by_location));
18528:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
18529:     my (%defaultshash,%changes);
18530:     my $action = 'ssl';
18531:     my @prefixes = ('connto','connfrom','replication');
18532:     foreach my $prefix (@prefixes) {
18533:         $defaultshash{$action}{$prefix} = {};
18534:     }
18535:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18536:     my $resulttext;
18537:     my %iphost = &Apache::lonnet::get_iphost();
18538:     my @reptypes = ('certreq','nocertreq');
18539:     my @connecttypes = ('dom','intdom','other');
18540:     my %types = (
18541:                   connto      => \@connecttypes,
18542:                   connfrom    => \@connecttypes,
18543:                   replication => \@reptypes,
18544:                 );
18545:     foreach my $prefix (sort(keys(%types))) {
18546:         foreach my $type (@{$types{$prefix}}) {
18547:             if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
18548:                 my $value = 'yes';
18549:                 if ($env{'form.'.$prefix.'_'.$type} =~ /^(no|req)$/) {
18550:                     $value = $env{'form.'.$prefix.'_'.$type};
18551:                 }
18552:                 if (ref($domconfig{$action}) eq 'HASH') {
18553:                     if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
18554:                         if ($domconfig{$action}{$prefix}{$type} ne '') {
18555:                             if ($value ne $domconfig{$action}{$prefix}{$type}) {
18556:                                 $changes{$prefix}{$type} = 1;
18557:                             }
18558:                             $defaultshash{$action}{$prefix}{$type} = $value;
18559:                         } else {
18560:                             $defaultshash{$action}{$prefix}{$type} = $value;
18561:                             $changes{$prefix}{$type} = 1;
18562:                         }
18563:                     } else {
18564:                         $defaultshash{$action}{$prefix}{$type} = $value;
18565:                         $changes{$prefix}{$type} = 1;
18566:                     }
18567:                 } else {
18568:                     $defaultshash{$action}{$prefix}{$type} = $value;
18569:                     $changes{$prefix}{$type} = 1;
18570:                 }
18571:                 if (($type eq 'dom') && (keys(%servers) == 1)) {
18572:                     delete($changes{$prefix}{$type});
18573:                 } elsif (($type eq 'intdom') && (@instdoms == 1)) {
18574:                     delete($changes{$prefix}{$type});
18575:                 } elsif (($type eq 'other') && (keys(%by_location) == 0)) { 
18576:                     delete($changes{$prefix}{$type});
18577:                 }
18578:             } elsif ($prefix eq 'replication') {
18579:                 if (@locations > 0) {
18580:                     my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
18581:                     my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
18582:                     my @okvals;
18583:                     foreach my $val (@vals) {
18584:                         if ($val =~ /:/) {
18585:                             my @items = split(/:/,$val);
18586:                             foreach my $item (@items) {
18587:                                 if (ref($by_location{$item}) eq 'ARRAY') {
18588:                                     push(@okvals,$item);
18589:                                 }
18590:                             }
18591:                         } else {
18592:                             if (ref($by_location{$val}) eq 'ARRAY') {
18593:                                 push(@okvals,$val);
18594:                             }
18595:                         }
18596:                     }
18597:                     @okvals = sort(@okvals);
18598:                     if (ref($domconfig{$action}) eq 'HASH') {
18599:                         if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
18600:                             if (ref($domconfig{$action}{$prefix}{$type}) eq 'ARRAY') {
18601:                                 if ($inuse == 0) {
18602:                                     $changes{$prefix}{$type} = 1;
18603:                                 } else {
18604:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
18605:                                     my @changed = &Apache::loncommon::compare_arrays($domconfig{$action}{$prefix}{$type},$defaultshash{$action}{$prefix}{$type});
18606:                                     if (@changed > 0) {
18607:                                         $changes{$prefix}{$type} = 1;
18608:                                     }
18609:                                 }
18610:                             } else {
18611:                                 if ($inuse == 1) {
18612:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
18613:                                     $changes{$prefix}{$type} = 1;
18614:                                 }
18615:                             }
18616:                         } else {
18617:                             if ($inuse == 1) {
18618:                                 $defaultshash{$action}{$prefix}{$type} = \@okvals;
18619:                                 $changes{$prefix}{$type} = 1;
18620:                             }
18621:                         }
18622:                     } else {
18623:                         if ($inuse == 1) {
18624:                             $defaultshash{$action}{$prefix}{$type} = \@okvals;
18625:                             $changes{$prefix}{$type} = 1;
18626:                         }
18627:                     }
18628:                 }
18629:             }
18630:         }
18631:     }
18632:     if (keys(%changes)) {
18633:         foreach my $prefix (keys(%changes)) {
18634:             if (ref($changes{$prefix}) eq 'HASH') {
18635:                 if (scalar(keys(%{$changes{$prefix}})) == 0) {
18636:                     delete($changes{$prefix});
18637:                 }
18638:             } else {
18639:                 delete($changes{$prefix});
18640:             }
18641:         }
18642:     }
18643:     my $nochgmsg = &mt('No changes made to LON-CAPA SSL settings');
18644:     if (keys(%changes) > 0) {
18645:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
18646:                                                  $dom);
18647:         if ($putresult eq 'ok') {
18648:             if (ref($defaultshash{$action}) eq 'HASH') {
18649:                 if (ref($defaultshash{$action}{'replication'}) eq 'HASH') {
18650:                     $domdefaults{'replication'} = $defaultshash{$action}{'replication'};
18651:                 }
18652:                 if (ref($defaultshash{$action}{'connto'}) eq 'HASH') {
18653:                     $domdefaults{'connto'} = $defaultshash{$action}{'connto'};
18654:                 }
18655:                 if (ref($defaultshash{$action}{'connfrom'}) eq 'HASH') {
18656:                     $domdefaults{'connfrom'} = $defaultshash{$action}{'connfrom'};
18657:                 }
18658:             }
18659:             my $cachetime = 24*60*60;
18660:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18661:             if (ref($lastactref) eq 'HASH') {
18662:                 $lastactref->{'domdefaults'} = 1;
18663:             }
18664:             if (keys(%changes) > 0) {
18665:                 my %titles = &ssl_titles();
18666:                 $resulttext = &mt('Changes made:').'<ul>';
18667:                 foreach my $prefix (@prefixes) {
18668:                     if (ref($changes{$prefix}) eq 'HASH') {
18669:                         $resulttext .= '<li>'.$titles{$prefix}.'<ul>';
18670:                         foreach my $type (@{$types{$prefix}}) {
18671:                             if (defined($changes{$prefix}{$type})) {
18672:                                 my ($newvalue,$notinuse);
18673:                                 if (ref($defaultshash{$action}) eq 'HASH') {
18674:                                     if (ref($defaultshash{$action}{$prefix})) {
18675:                                         if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
18676:                                             $newvalue = $titles{$defaultshash{$action}{$prefix}{$type}};
18677:                                         } else {
18678:                                             if (ref($defaultshash{$action}{$prefix}{$type}) eq 'ARRAY') {
18679:                                                 if (@{$defaultshash{$action}{$prefix}{$type}} > 0) {
18680:                                                     $newvalue = join(', ',@{$defaultshash{$action}{$prefix}{$type}});
18681:                                                 }
18682:                                             } else {
18683:                                                 $notinuse = 1;
18684:                                             }
18685:                                         }
18686:                                     }
18687:                                     if ($notinuse) {
18688:                                         $resulttext .= '<li>'.&mt('[_1] set to: not in use',$titles{$type}).'</li>';
18689:                                     } elsif ($newvalue eq '') {
18690:                                         $resulttext .= '<li>'.&mt('[_1] set to: none',$titles{$type}).'</li>';
18691:                                     } else {
18692:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$titles{$type},$newvalue).'</li>';
18693:                                     }
18694:                                 }
18695:                             }
18696:                         }
18697:                         $resulttext .= '</ul>';
18698:                     }
18699:                 }
18700:             } else {
18701:                 $resulttext = $nochgmsg;
18702:             }
18703:         } else {
18704:             $resulttext = '<span class="LC_error">'.
18705:                           &mt('An error occurred: [_1]',$putresult).'</span>';
18706:         }
18707:     } else {
18708:         $resulttext = $nochgmsg;
18709:     }
18710:     return $resulttext;
18711: }
18712: 
18713: sub modify_trust {
18714:     my ($dom,$lastactref,%domconfig) = @_;
18715:     my (%by_ip,%by_location,@intdoms,@instdoms);
18716:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
18717:     my @locations = sort(keys(%by_location));
18718:     my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
18719:     my @types = ('exc','inc');
18720:     my (%defaultshash,%changes);
18721:     foreach my $prefix (@prefixes) {
18722:         $defaultshash{'trust'}{$prefix} = {};
18723:     }
18724:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18725:     my $resulttext;
18726:     foreach my $prefix (@prefixes) {
18727:         foreach my $type (@types) {
18728:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
18729:             my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
18730:             my @okvals;
18731:             foreach my $val (@vals) {
18732:                 if ($val =~ /:/) {
18733:                     my @items = split(/:/,$val);
18734:                     foreach my $item (@items) {
18735:                         if (ref($by_location{$item}) eq 'ARRAY') {
18736:                             push(@okvals,$item);
18737:                         }
18738:                     }
18739:                 } else {
18740:                     if (ref($by_location{$val}) eq 'ARRAY') {
18741:                         push(@okvals,$val);
18742:                     }
18743:                 }
18744:             }
18745:             @okvals = sort(@okvals);
18746:             if (ref($domconfig{'trust'}) eq 'HASH') {
18747:                 if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
18748:                     if (ref($domconfig{'trust'}{$prefix}{$type}) eq 'ARRAY') {
18749:                         if ($inuse == 0) {
18750:                             $changes{$prefix}{$type} = 1;
18751:                         } else {
18752:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
18753:                             my @changed = &Apache::loncommon::compare_arrays($domconfig{'trust'}{$prefix}{$type},$defaultshash{'trust'}{$prefix}{$type});
18754:                             if (@changed > 0) {
18755:                                 $changes{$prefix}{$type} = 1;
18756:                             }
18757:                         }
18758:                     } else {
18759:                         if ($inuse == 1) {
18760:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
18761:                             $changes{$prefix}{$type} = 1;
18762:                         }
18763:                     }
18764:                 } else {
18765:                     if ($inuse == 1) {
18766:                         $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
18767:                         $changes{$prefix}{$type} = 1;
18768:                     }
18769:                 }
18770:             } else {
18771:                 if ($inuse == 1) {
18772:                     $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
18773:                     $changes{$prefix}{$type} = 1;
18774:                 }
18775:             }
18776:         }
18777:     }
18778:     my $nochgmsg = &mt('No changes made to trust settings.');
18779:     if (keys(%changes) > 0) {
18780:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
18781:                                                  $dom);
18782:         if ($putresult eq 'ok') {
18783:             if (ref($defaultshash{'trust'}) eq 'HASH') {
18784:                 foreach my $prefix (@prefixes) {
18785:                     if (ref($defaultshash{'trust'}{$prefix}) eq 'HASH') {
18786:                         $domdefaults{'trust'.$prefix} = $defaultshash{'trust'}{$prefix};
18787:                     }
18788:                 }
18789:             }
18790:             my $cachetime = 24*60*60;
18791:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18792:             if (ref($lastactref) eq 'HASH') {
18793:                 $lastactref->{'domdefaults'} = 1;
18794:             }
18795:             if (keys(%changes) > 0) {
18796:                 my %lt = &trust_titles();
18797:                 $resulttext = &mt('Changes made:').'<ul>';
18798:                 foreach my $prefix (@prefixes) {
18799:                     if (ref($changes{$prefix}) eq 'HASH') {
18800:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
18801:                         foreach my $type (@types) {
18802:                             if (defined($changes{$prefix}{$type})) {
18803:                                 my ($newvalue,$notinuse);
18804:                                 if (ref($defaultshash{'trust'}) eq 'HASH') {
18805:                                     if (ref($defaultshash{'trust'}{$prefix})) {
18806:                                         if (ref($defaultshash{'trust'}{$prefix}{$type}) eq 'ARRAY') {
18807:                                             if (@{$defaultshash{'trust'}{$prefix}{$type}} > 0) {
18808:                                                 $newvalue = join(', ',@{$defaultshash{'trust'}{$prefix}{$type}});
18809:                                             }
18810:                                         } else {
18811:                                             $notinuse = 1;
18812:                                         }
18813:                                     }
18814:                                 }
18815:                                 if ($notinuse) {
18816:                                     $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
18817:                                 } elsif ($newvalue eq '') {
18818:                                     $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
18819:                                 } else {
18820:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
18821:                                 }
18822:                             }
18823:                         }
18824:                         $resulttext .= '</ul>';
18825:                     }
18826:                 }
18827:                 $resulttext .= '</ul>';
18828:             } else {
18829:                 $resulttext = $nochgmsg;
18830:             }
18831:         } else {
18832:             $resulttext = '<span class="LC_error">'.
18833:                           &mt('An error occurred: [_1]',$putresult).'</span>';
18834:         }
18835:     } else {
18836:         $resulttext = $nochgmsg;
18837:     }
18838:     return $resulttext;
18839: }
18840: 
18841: sub modify_loadbalancing {
18842:     my ($dom,%domconfig) = @_;
18843:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
18844:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
18845:     my ($othertitle,$usertypes,$types) =
18846:         &Apache::loncommon::sorted_inst_types($dom);
18847:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
18848:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
18849:     my @sparestypes = ('primary','default');
18850:     my %typetitles = &sparestype_titles();
18851:     my $resulttext;
18852:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
18853:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
18854:         %existing = %{$domconfig{'loadbalancing'}};
18855:     }
18856:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
18857:                               \%currtargets,\%currrules,\%currcookies);
18858:     my ($saveloadbalancing,%defaultshash,%changes);
18859:     my ($alltypes,$othertypes,$titles) =
18860:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
18861:     my %ruletitles = &offloadtype_text();
18862:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
18863:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
18864:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
18865:         if ($balancer eq '') {
18866:             next;
18867:         }
18868:         if (!exists($servers{$balancer})) {
18869:             if (exists($currbalancer{$balancer})) {
18870:                 push(@{$changes{'delete'}},$balancer);
18871:             }
18872:             next;
18873:         }
18874:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
18875:             push(@{$changes{'delete'}},$balancer);
18876:             next;
18877:         }
18878:         if (!exists($currbalancer{$balancer})) {
18879:             push(@{$changes{'add'}},$balancer);
18880:         }
18881:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
18882:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
18883:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
18884:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
18885:             $saveloadbalancing = 1;
18886:         }
18887:         foreach my $sparetype (@sparestypes) {
18888:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
18889:             my @offloadto;
18890:             foreach my $target (@targets) {
18891:                 if (($servers{$target}) && ($target ne $balancer)) {
18892:                     if ($sparetype eq 'default') {
18893:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
18894:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
18895:                         }
18896:                     }
18897:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
18898:                         push(@offloadto,$target);
18899:                     }
18900:                 }
18901:             }
18902:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
18903:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
18904:                     push(@offloadto,$balancer);
18905:                 }
18906:             }
18907:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
18908:         }
18909:         if ($env{'form.loadbalancing_cookie_'.$i}) {
18910:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
18911:             if (exists($currbalancer{$balancer})) { 
18912:                 unless ($currcookies{$balancer}) {
18913:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
18914:                 }
18915:             }
18916:         } elsif (exists($currbalancer{$balancer})) {
18917:             if ($currcookies{$balancer}) {
18918:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
18919:             }
18920:         }
18921:         if (ref($currtargets{$balancer}) eq 'HASH') {
18922:             foreach my $sparetype (@sparestypes) {
18923:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
18924:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
18925:                     if (@targetdiffs > 0) {
18926:                         $changes{'curr'}{$balancer}{'targets'} = 1;
18927:                     }
18928:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
18929:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
18930:                         $changes{'curr'}{$balancer}{'targets'} = 1;
18931:                     }
18932:                 }
18933:             }
18934:         } else {
18935:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
18936:                 foreach my $sparetype (@sparestypes) {
18937:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
18938:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
18939:                             $changes{'curr'}{$balancer}{'targets'} = 1;
18940:                         }
18941:                     }
18942:                 }
18943:             }
18944:         }
18945:         my $ishomedom;
18946:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
18947:             $ishomedom = 1;
18948:         }
18949:         if (ref($alltypes) eq 'ARRAY') {
18950:             foreach my $type (@{$alltypes}) {
18951:                 my $rule;
18952:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
18953:                          (!$ishomedom)) {
18954:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
18955:                 }
18956:                 if ($rule eq 'specific') {
18957:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
18958:                     if (exists($servers{$specifiedhost})) {
18959:                         $rule = $specifiedhost;
18960:                     }
18961:                 }
18962:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
18963:                 if (ref($currrules{$balancer}) eq 'HASH') {
18964:                     if ($rule ne $currrules{$balancer}{$type}) {
18965:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
18966:                     }
18967:                 } elsif ($rule ne '') {
18968:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
18969:                 }
18970:             }
18971:         }
18972:     }
18973:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
18974:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
18975:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
18976:             $defaultshash{'loadbalancing'} = {};
18977:         }
18978:         my $putresult = &Apache::lonnet::put_dom('configuration',
18979:                                                  \%defaultshash,$dom);
18980:         if ($putresult eq 'ok') {
18981:             if (keys(%changes) > 0) {
18982:                 my %toupdate;
18983:                 if (ref($changes{'delete'}) eq 'ARRAY') {
18984:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
18985:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
18986:                         $toupdate{$balancer} = 1;
18987:                     }
18988:                 }
18989:                 if (ref($changes{'add'}) eq 'ARRAY') {
18990:                     foreach my $balancer (sort(@{$changes{'add'}})) {
18991:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
18992:                         $toupdate{$balancer} = 1;
18993:                     }
18994:                 }
18995:                 if (ref($changes{'curr'}) eq 'HASH') {
18996:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
18997:                         $toupdate{$balancer} = 1;
18998:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
18999:                             if ($changes{'curr'}{$balancer}{'targets'}) {
19000:                                 my %offloadstr;
19001:                                 foreach my $sparetype (@sparestypes) {
19002:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
19003:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
19004:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
19005:                                         }
19006:                                     }
19007:                                 }
19008:                                 if (keys(%offloadstr) == 0) {
19009:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
19010:                                 } else {
19011:                                     my $showoffload;
19012:                                     foreach my $sparetype (@sparestypes) {
19013:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
19014:                                         if (defined($offloadstr{$sparetype})) {
19015:                                             $showoffload .= $offloadstr{$sparetype};
19016:                                         } else {
19017:                                             $showoffload .= &mt('None');
19018:                                         }
19019:                                         $showoffload .= ('&nbsp;'x3);
19020:                                     }
19021:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
19022:                                 }
19023:                             }
19024:                         }
19025:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
19026:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
19027:                                 foreach my $type (@{$alltypes}) {
19028:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
19029:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
19030:                                         my $balancetext;
19031:                                         if ($rule eq '') {
19032:                                             $balancetext =  $ruletitles{'default'};
19033:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
19034:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
19035:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
19036:                                                 foreach my $sparetype (@sparestypes) {
19037:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
19038:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
19039:                                                     }
19040:                                                 }
19041:                                                 foreach my $item (@{$alltypes}) {
19042:                                                     next if ($item =~  /^_LC_ipchange/);
19043:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
19044:                                                     if ($hasrule eq 'homeserver') {
19045:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
19046:                                                     } else {
19047:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
19048:                                                             if ($servers{$hasrule}) {
19049:                                                                 $toupdate{$hasrule} = 1;
19050:                                                             }
19051:                                                         }
19052:                                                     }
19053:                                                 }
19054:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
19055:                                                     $balancetext =  $ruletitles{$rule};
19056:                                                 } else {
19057:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
19058:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
19059:                                                     if ($receiver) {
19060:                                                         $toupdate{$receiver};
19061:                                                     }
19062:                                                 }
19063:                                             } else {
19064:                                                 $balancetext =  $ruletitles{$rule};
19065:                                             }
19066:                                         } else {
19067:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
19068:                                         }
19069:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
19070:                                     }
19071:                                 }
19072:                             }
19073:                         }
19074:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
19075:                             $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
19076:                                                       $balancer).'</li>'; 
19077:                         }
19078:                         if (keys(%toupdate)) {
19079:                             my %thismachine;
19080:                             my $updatedhere;
19081:                             my $cachetime = 60*60*24;
19082:                             map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
19083:                             foreach my $lonhost (keys(%toupdate)) {
19084:                                 if ($thismachine{$lonhost}) {
19085:                                     unless ($updatedhere) {
19086:                                         &Apache::lonnet::do_cache_new('loadbalancing',$dom,
19087:                                                                       $defaultshash{'loadbalancing'},
19088:                                                                       $cachetime);
19089:                                         $updatedhere = 1;
19090:                                     }
19091:                                 } else {
19092:                                     my $cachekey = &escape('loadbalancing').':'.&escape($dom);
19093:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
19094:                                 }
19095:                             }
19096:                         }
19097:                     }
19098:                 }
19099:                 if ($resulttext ne '') {
19100:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
19101:                 } else {
19102:                     $resulttext = $nochgmsg;
19103:                 }
19104:             } else {
19105:                 $resulttext = $nochgmsg;
19106:             }
19107:         } else {
19108:             $resulttext = '<span class="LC_error">'.
19109:                           &mt('An error occurred: [_1]',$putresult).'</span>';
19110:         }
19111:     } else {
19112:         $resulttext = $nochgmsg;
19113:     }
19114:     return $resulttext;
19115: }
19116: 
19117: sub recurse_check {
19118:     my ($chkcats,$categories,$depth,$name) = @_;
19119:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
19120:         my $chg = 0;
19121:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
19122:             my $category = $chkcats->[$depth]{$name}[$j];
19123:             my $item;
19124:             if ($category eq '') {
19125:                 $chg ++;
19126:             } else {
19127:                 my $deeper = $depth + 1;
19128:                 $item = &escape($category).':'.&escape($name).':'.$depth;
19129:                 if ($chg) {
19130:                     $categories->{$item} -= $chg;
19131:                 }
19132:                 &recurse_check($chkcats,$categories,$deeper,$category);
19133:                 $deeper --;
19134:             }
19135:         }
19136:     }
19137:     return;
19138: }
19139: 
19140: sub recurse_cat_deletes {
19141:     my ($item,$coursecategories,$deletions) = @_;
19142:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
19143:     my $subdepth = $depth + 1;
19144:     if (ref($coursecategories) eq 'HASH') {
19145:         foreach my $subitem (keys(%{$coursecategories})) {
19146:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
19147:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
19148:                 delete($coursecategories->{$subitem});
19149:                 $deletions->{$subitem} = 1;
19150:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
19151:             }
19152:         }
19153:     }
19154:     return;
19155: }
19156: 
19157: sub active_dc_picker {
19158:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
19159:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
19160:     my @domcoord = keys(%domcoords);
19161:     if (keys(%currhash)) {
19162:         foreach my $dc (keys(%currhash)) {
19163:             unless (exists($domcoords{$dc})) {
19164:                 push(@domcoord,$dc);
19165:             }
19166:         }
19167:     }
19168:     @domcoord = sort(@domcoord);
19169:     my $numdcs = scalar(@domcoord);
19170:     my $rows = 0;
19171:     my $table;
19172:     if ($numdcs > 1) {
19173:         $table = '<table>';
19174:         for (my $i=0; $i<@domcoord; $i++) {
19175:             my $rem = $i%($numinrow);
19176:             if ($rem == 0) {
19177:                 if ($i > 0) {
19178:                     $table .= '</tr>';
19179:                 }
19180:                 $table .= '<tr>';
19181:                 $rows ++;
19182:             }
19183:             my $check = '';
19184:             if ($inputtype eq 'radio') {
19185:                 if (keys(%currhash) == 0) {
19186:                     if (!$i) {
19187:                         $check = ' checked="checked"';
19188:                     }
19189:                 } elsif (exists($currhash{$domcoord[$i]})) {
19190:                     $check = ' checked="checked"';
19191:                 }
19192:             } else {
19193:                 if (exists($currhash{$domcoord[$i]})) {
19194:                     $check = ' checked="checked"';
19195:                 }
19196:             }
19197:             if ($i == @domcoord - 1) {
19198:                 my $colsleft = $numinrow - $rem;
19199:                 if ($colsleft > 1) {
19200:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
19201:                 } else {
19202:                     $table .= '<td class="LC_left_item">';
19203:                 }
19204:             } else {
19205:                 $table .= '<td class="LC_left_item">';
19206:             }
19207:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
19208:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
19209:             $table .= '<span class="LC_nobreak"><label>'.
19210:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
19211:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
19212:             if ($user ne $dcname.':'.$dcdom) {
19213:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
19214:             }
19215:             $table .= '</label></span></td>';
19216:         }
19217:         $table .= '</tr></table>';
19218:     } elsif ($numdcs == 1) {
19219:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
19220:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
19221:         if ($inputtype eq 'radio') {
19222:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
19223:             if ($user ne $dcname.':'.$dcdom) {
19224:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
19225:             }
19226:         } else {
19227:             my $check;
19228:             if (exists($currhash{$domcoord[0]})) {
19229:                 $check = ' checked="checked"';
19230:             }
19231:             $table = '<span class="LC_nobreak"><label>'.
19232:                      '<input type="checkbox" name="'.$name.'" '.
19233:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
19234:             if ($user ne $dcname.':'.$dcdom) {
19235:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
19236:             }
19237:             $table .= '</label></span>';
19238:             $rows ++;
19239:         }
19240:     }
19241:     return ($numdcs,$table,$rows);
19242: }
19243: 
19244: sub usersession_titles {
19245:     return &Apache::lonlocal::texthash(
19246:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
19247:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
19248:                spares => 'Servers offloaded to, when busy',
19249:                version => 'LON-CAPA version requirement',
19250:                excludedomain => 'Allow all, but exclude specific domains',
19251:                includedomain => 'Deny all, but include specific domains',
19252:                primary => 'Primary (checked first)',
19253:                default => 'Default',
19254:            );
19255: }
19256: 
19257: sub id_for_thisdom {
19258:     my (%servers) = @_;
19259:     my %altids;
19260:     foreach my $server (keys(%servers)) {
19261:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
19262:         if ($serverhome ne $server) {
19263:             $altids{$serverhome} = $server;
19264:         }
19265:     }
19266:     return %altids;
19267: }
19268: 
19269: sub count_servers {
19270:     my ($currbalancer,%servers) = @_;
19271:     my (@spares,$numspares);
19272:     foreach my $lonhost (sort(keys(%servers))) {
19273:         next if ($currbalancer eq $lonhost);
19274:         push(@spares,$lonhost);
19275:     }
19276:     if ($currbalancer) {
19277:         $numspares = scalar(@spares);
19278:     } else {
19279:         $numspares = scalar(@spares) - 1;
19280:     }
19281:     return ($numspares,@spares);
19282: }
19283: 
19284: sub lonbalance_targets_js {
19285:     my ($dom,$types,$servers,$settings) = @_;
19286:     my $select = &mt('Select');
19287:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
19288:     if (ref($servers) eq 'HASH') {
19289:         $alltargets = join("','",sort(keys(%{$servers})));
19290:         my @homedoms;
19291:         foreach my $server (sort(keys(%{$servers}))) {
19292:             if (&Apache::lonnet::host_domain($server) eq $dom) {
19293:                 push(@homedoms,'1');
19294:             } else {
19295:                 push(@homedoms,'0');
19296:             }
19297:         }
19298:         $allishome = join("','",@homedoms);
19299:     }
19300:     if (ref($types) eq 'ARRAY') {
19301:         if (@{$types} > 0) {
19302:             @alltypes = @{$types};
19303:         }
19304:     }
19305:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
19306:     $allinsttypes = join("','",@alltypes);
19307:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
19308:     if (ref($settings) eq 'HASH') {
19309:         %existing = %{$settings};
19310:     }
19311:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
19312:                               \%currtargets,\%currrules,\%currcookies);
19313:     my $balancers = join("','",sort(keys(%currbalancer)));
19314:     return <<"END";
19315: 
19316: <script type="text/javascript">
19317: // <![CDATA[
19318: 
19319: currBalancers = new Array('$balancers');
19320: 
19321: function toggleTargets(balnum) {
19322:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
19323:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
19324:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
19325:     var prevbalancer = prevhostitem.value;
19326:     var baltotal = document.getElementById('loadbalancing_total').value;
19327:     prevhostitem.value = balancer;
19328:     if (prevbalancer != '') {
19329:         var prevIdx = currBalancers.indexOf(prevbalancer);
19330:         if (prevIdx != -1) {
19331:             currBalancers.splice(prevIdx,1);
19332:         }
19333:     }
19334:     if (balancer == '') {
19335:         hideSpares(balnum);
19336:     } else {
19337:         var currIdx = currBalancers.indexOf(balancer);
19338:         if (currIdx == -1) {
19339:             currBalancers.push(balancer);
19340:         }
19341:         var homedoms = new Array('$allishome');
19342:         var ishomedom = homedoms[lonhostitem.selectedIndex];
19343:         showSpares(balancer,ishomedom,balnum);
19344:     }
19345:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
19346:     return;
19347: }
19348: 
19349: function showSpares(balancer,ishomedom,balnum) {
19350:     var alltargets = new Array('$alltargets');
19351:     var insttypes = new Array('$allinsttypes');
19352:     var offloadtypes = new Array('primary','default');
19353: 
19354:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
19355:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
19356:  
19357:     for (var i=0; i<offloadtypes.length; i++) {
19358:         var count = 0;
19359:         for (var j=0; j<alltargets.length; j++) {
19360:             if (alltargets[j] != balancer) {
19361:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
19362:                 item.value = alltargets[j];
19363:                 item.style.textAlign='left';
19364:                 item.style.textFace='normal';
19365:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
19366:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
19367:                     item.disabled = '';
19368:                 } else {
19369:                     item.disabled = 'disabled';
19370:                     item.checked = false;
19371:                 }
19372:                 count ++;
19373:             }
19374:         }
19375:     }
19376:     for (var k=0; k<insttypes.length; k++) {
19377:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
19378:             if (ishomedom == 1) {
19379:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
19380:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
19381:             } else {
19382:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
19383:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
19384:             }
19385:         } else {
19386:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
19387:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
19388:         }
19389:         if ((insttypes[k] != '_LC_external') && 
19390:             ((insttypes[k] != '_LC_internetdom') ||
19391:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
19392:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
19393:             item.options.length = 0;
19394:             item.options[0] = new Option("","",true,true);
19395:             var idx = 0;
19396:             for (var m=0; m<alltargets.length; m++) {
19397:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
19398:                     idx ++;
19399:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
19400:                 }
19401:             }
19402:         }
19403:     }
19404:     return;
19405: }
19406: 
19407: function hideSpares(balnum) {
19408:     var alltargets = new Array('$alltargets');
19409:     var insttypes = new Array('$allinsttypes');
19410:     var offloadtypes = new Array('primary','default');
19411: 
19412:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
19413:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
19414: 
19415:     var total = alltargets.length - 1;
19416:     for (var i=0; i<offloadtypes; i++) {
19417:         for (var j=0; j<total; j++) {
19418:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
19419:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
19420:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
19421:         }
19422:     }
19423:     for (var k=0; k<insttypes.length; k++) {
19424:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
19425:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
19426:         if (insttypes[k] != '_LC_external') {
19427:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
19428:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
19429:         }
19430:     }
19431:     return;
19432: }
19433: 
19434: function checkOffloads(item,balnum,type) {
19435:     var alltargets = new Array('$alltargets');
19436:     var offloadtypes = new Array('primary','default');
19437:     if (item.checked) {
19438:         var total = alltargets.length - 1;
19439:         var other;
19440:         if (type == offloadtypes[0]) {
19441:             other = offloadtypes[1];
19442:         } else {
19443:             other = offloadtypes[0];
19444:         }
19445:         for (var i=0; i<total; i++) {
19446:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
19447:             if (server == item.value) {
19448:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
19449:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
19450:                 }
19451:             }
19452:         }
19453:     }
19454:     return;
19455: }
19456: 
19457: function singleServerToggle(balnum,type) {
19458:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
19459:     if (offloadtoSelIdx == 0) {
19460:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
19461:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
19462: 
19463:     } else {
19464:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
19465:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
19466:     }
19467:     return;
19468: }
19469: 
19470: function balanceruleChange(formname,balnum,type) {
19471:     if (type == '_LC_external') {
19472:         return;
19473:     }
19474:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
19475:     for (var i=0; i<typesRules.length; i++) {
19476:         if (formname.elements[typesRules[i]].checked) {
19477:             if (formname.elements[typesRules[i]].value != 'specific') {
19478:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
19479:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
19480:             } else {
19481:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
19482:             }
19483:         }
19484:     }
19485:     return;
19486: }
19487: 
19488: function balancerDeleteChange(balnum) {
19489:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
19490:     var baltotal = document.getElementById('loadbalancing_total').value;
19491:     var addtarget;
19492:     var removetarget;
19493:     var action = 'delete';
19494:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
19495:         var lonhost = hostitem.value;
19496:         var currIdx = currBalancers.indexOf(lonhost);
19497:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
19498:             if (currIdx != -1) {
19499:                 currBalancers.splice(currIdx,1);
19500:             }
19501:             addtarget = lonhost;
19502:         } else {
19503:             if (currIdx == -1) {
19504:                 currBalancers.push(lonhost);
19505:             }
19506:             removetarget = lonhost;
19507:             action = 'undelete';
19508:         }
19509:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
19510:     }
19511:     return;
19512: }
19513: 
19514: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
19515:     if (baltotal > 1) {
19516:         var offloadtypes = new Array('primary','default');
19517:         var alltargets = new Array('$alltargets');
19518:         var insttypes = new Array('$allinsttypes');
19519:         for (var i=0; i<baltotal; i++) {
19520:             if (i != balnum) {
19521:                 for (var j=0; j<offloadtypes.length; j++) {
19522:                     var total = alltargets.length - 1;
19523:                     for (var k=0; k<total; k++) {
19524:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
19525:                         var server = serveritem.value;
19526:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
19527:                             if (server == addtarget) {
19528:                                 serveritem.disabled = '';
19529:                             }
19530:                         }
19531:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
19532:                             if (server == removetarget) {
19533:                                 serveritem.disabled = 'disabled';
19534:                                 serveritem.checked = false;
19535:                             }
19536:                         }
19537:                     }
19538:                 }
19539:                 for (var j=0; j<insttypes.length; j++) {
19540:                     if (insttypes[j] != '_LC_external') {
19541:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
19542:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
19543:                             var currSel = singleserver.selectedIndex;
19544:                             var currVal = singleserver.options[currSel].value;
19545:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
19546:                                 var numoptions = singleserver.options.length;
19547:                                 var needsnew = 1;
19548:                                 for (var k=0; k<numoptions; k++) {
19549:                                     if (singleserver.options[k] == addtarget) {
19550:                                         needsnew = 0;
19551:                                         break;
19552:                                     }
19553:                                 }
19554:                                 if (needsnew == 1) {
19555:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
19556:                                 }
19557:                             }
19558:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
19559:                                 singleserver.options.length = 0;
19560:                                 if ((currVal) && (currVal != removetarget)) {
19561:                                     singleserver.options[0] = new Option("","",false,false);
19562:                                 } else {
19563:                                     singleserver.options[0] = new Option("","",true,true);
19564:                                 }
19565:                                 var idx = 0;
19566:                                 for (var m=0; m<alltargets.length; m++) {
19567:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
19568:                                         idx ++;
19569:                                         if (currVal == alltargets[m]) {
19570:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
19571:                                         } else {
19572:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
19573:                                         }
19574:                                     }
19575:                                 }
19576:                             }
19577:                         }
19578:                     }
19579:                 }
19580:             }
19581:         }
19582:     }
19583:     return;
19584: }
19585: 
19586: // ]]>
19587: </script>
19588: 
19589: END
19590: }
19591: 
19592: sub new_spares_js {
19593:     my @sparestypes = ('primary','default');
19594:     my $types = join("','",@sparestypes);
19595:     my $select = &mt('Select');
19596:     return <<"END";
19597: 
19598: <script type="text/javascript">
19599: // <![CDATA[
19600: 
19601: function updateNewSpares(formname,lonhost) {
19602:     var types = new Array('$types');
19603:     var include = new Array();
19604:     var exclude = new Array();
19605:     for (var i=0; i<types.length; i++) {
19606:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
19607:         for (var j=0; j<spareboxes.length; j++) {
19608:             if (formname.elements[spareboxes[j]].checked) {
19609:                 exclude.push(formname.elements[spareboxes[j]].value);
19610:             } else {
19611:                 include.push(formname.elements[spareboxes[j]].value);
19612:             }
19613:         }
19614:     }
19615:     for (var i=0; i<types.length; i++) {
19616:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
19617:         var selIdx = newSpare.selectedIndex;
19618:         var currnew = newSpare.options[selIdx].value;
19619:         var okSpares = new Array();
19620:         for (var j=0; j<newSpare.options.length; j++) {
19621:             var possible = newSpare.options[j].value;
19622:             if (possible != '') {
19623:                 if (exclude.indexOf(possible) == -1) {
19624:                     okSpares.push(possible);
19625:                 } else {
19626:                     if (currnew == possible) {
19627:                         selIdx = 0;
19628:                     }
19629:                 }
19630:             }
19631:         }
19632:         for (var k=0; k<include.length; k++) {
19633:             if (okSpares.indexOf(include[k]) == -1) {
19634:                 okSpares.push(include[k]);
19635:             }
19636:         }
19637:         okSpares.sort();
19638:         newSpare.options.length = 0;
19639:         if (selIdx == 0) {
19640:             newSpare.options[0] = new Option("$select","",true,true);
19641:         } else {
19642:             newSpare.options[0] = new Option("$select","",false,false);
19643:         }
19644:         for (var m=0; m<okSpares.length; m++) {
19645:             var idx = m+1;
19646:             var selThis = 0;
19647:             if (selIdx != 0) {
19648:                 if (okSpares[m] == currnew) {
19649:                     selThis = 1;
19650:                 }
19651:             }
19652:             if (selThis == 1) {
19653:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
19654:             } else {
19655:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
19656:             }
19657:         }
19658:     }
19659:     return;
19660: }
19661: 
19662: function checkNewSpares(lonhost,type) {
19663:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
19664:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
19665:     if (chosen != '') { 
19666:         var othertype;
19667:         var othernewSpare;
19668:         if (type == 'primary') {
19669:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
19670:         }
19671:         if (type == 'default') {
19672:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
19673:         }
19674:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
19675:             othernewSpare.selectedIndex = 0;
19676:         }
19677:     }
19678:     return;
19679: }
19680: 
19681: // ]]>
19682: </script>
19683: 
19684: END
19685: 
19686: }
19687: 
19688: sub common_domprefs_js {
19689:     return <<"END";
19690: 
19691: <script type="text/javascript">
19692: // <![CDATA[
19693: 
19694: function getIndicesByName(formname,item) {
19695:     var group = new Array();
19696:     for (var i=0;i<formname.elements.length;i++) {
19697:         if (formname.elements[i].name == item) {
19698:             group.push(formname.elements[i].id);
19699:         }
19700:     }
19701:     return group;
19702: }
19703: 
19704: // ]]>
19705: </script>
19706: 
19707: END
19708: 
19709: }
19710: 
19711: sub recaptcha_js {
19712:     my %lt = &captcha_phrases();
19713:     return <<"END";
19714: 
19715: <script type="text/javascript">
19716: // <![CDATA[
19717: 
19718: function updateCaptcha(caller,context) {
19719:     var privitem;
19720:     var pubitem;
19721:     var privtext;
19722:     var pubtext;
19723:     var versionitem;
19724:     var versiontext;
19725:     if (document.getElementById(context+'_recaptchapub')) {
19726:         pubitem = document.getElementById(context+'_recaptchapub');
19727:     } else {
19728:         return;
19729:     }
19730:     if (document.getElementById(context+'_recaptchapriv')) {
19731:         privitem = document.getElementById(context+'_recaptchapriv');
19732:     } else {
19733:         return;
19734:     }
19735:     if (document.getElementById(context+'_recaptchapubtxt')) {
19736:         pubtext = document.getElementById(context+'_recaptchapubtxt');
19737:     } else {
19738:         return;
19739:     }
19740:     if (document.getElementById(context+'_recaptchaprivtxt')) {
19741:         privtext = document.getElementById(context+'_recaptchaprivtxt');
19742:     } else {
19743:         return;
19744:     }
19745:     if (document.getElementById(context+'_recaptchaversion')) {
19746:         versionitem = document.getElementById(context+'_recaptchaversion');
19747:     } else {
19748:         return;
19749:     }
19750:     if (document.getElementById(context+'_recaptchavertxt')) {
19751:         versiontext = document.getElementById(context+'_recaptchavertxt');
19752:     } else {
19753:         return;
19754:     }
19755:     if (caller.checked) {
19756:         if (caller.value == 'recaptcha') {
19757:             pubitem.type = 'text';
19758:             privitem.type = 'text';
19759:             pubitem.size = '40';
19760:             privitem.size = '40';
19761:             pubtext.innerHTML = "$lt{'pub'}";
19762:             privtext.innerHTML = "$lt{'priv'}";
19763:             versionitem.type = 'text';
19764:             versionitem.size = '3';
19765:             versiontext.innerHTML = "$lt{'ver'}";
19766:         } else {
19767:             pubitem.type = 'hidden';
19768:             privitem.type = 'hidden';
19769:             versionitem.type = 'hidden';
19770:             pubtext.innerHTML = '';
19771:             privtext.innerHTML = '';
19772:             versiontext.innerHTML = '';
19773:         }
19774:     }
19775:     return;
19776: }
19777: 
19778: // ]]>
19779: </script>
19780: 
19781: END
19782: 
19783: }
19784: 
19785: sub toggle_display_js {
19786:     return <<"END";
19787: 
19788: <script type="text/javascript">
19789: // <![CDATA[
19790: 
19791: function toggleDisplay(domForm,caller) {
19792:     if (document.getElementById(caller)) {
19793:         var divitem = document.getElementById(caller);
19794:         var optionsElement = domForm.coursecredits;
19795:         var checkval = 1;
19796:         var dispval = 'block';
19797:         var selfcreateRegExp = /^cancreate_emailverified/;
19798:         if (caller == 'emailoptions') {
19799:             optionsElement = domForm.cancreate_email; 
19800:         }
19801:         if (caller == 'studentsubmission') {
19802:             optionsElement = domForm.postsubmit;
19803:         }
19804:         if (caller == 'cloneinstcode') {
19805:             optionsElement = domForm.canclone;
19806:             checkval = 'instcode';
19807:         }
19808:         if (selfcreateRegExp.test(caller)) {
19809:             optionsElement = domForm.elements[caller];
19810:             checkval = 'other';
19811:             dispval = 'inline'
19812:         }
19813:         if (optionsElement.length) {
19814:             var currval;
19815:             for (var i=0; i<optionsElement.length; i++) {
19816:                 if (optionsElement[i].checked) {
19817:                    currval = optionsElement[i].value;
19818:                 }
19819:             }
19820:             if (currval == checkval) {
19821:                 divitem.style.display = dispval;
19822:             } else {
19823:                 divitem.style.display = 'none';
19824:             }
19825:         }
19826:     }
19827:     return;
19828: }
19829: 
19830: // ]]>
19831: </script>
19832: 
19833: END
19834: 
19835: }
19836: 
19837: sub captcha_phrases {
19838:     return &Apache::lonlocal::texthash (
19839:                  priv => 'Private key',
19840:                  pub  => 'Public key',
19841:                  original  => 'original (CAPTCHA)',
19842:                  recaptcha => 'successor (ReCAPTCHA)',
19843:                  notused   => 'unused',
19844:                  ver => 'ReCAPTCHA version (1 or 2)',
19845:     );
19846: }
19847: 
19848: sub devalidate_remote_domconfs {
19849:     my ($dom,$cachekeys) = @_;
19850:     return unless (ref($cachekeys) eq 'HASH');
19851:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
19852:     my %thismachine;
19853:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
19854:     my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
19855:                       'directorysrch','passwdconf','cats');
19856:     if (keys(%servers)) {
19857:         foreach my $server (keys(%servers)) {
19858:             next if ($thismachine{$server});
19859:             my @cached;
19860:             foreach my $name (@posscached) {
19861:                 if ($cachekeys->{$name}) {
19862:                     push(@cached,&escape($name).':'.&escape($dom));
19863:                 }
19864:             }
19865:             if (@cached) {
19866:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
19867:             }
19868:         }
19869:     }
19870:     return;
19871: }
19872: 
19873: 1;

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