Diff for /loncom/interface/domainprefs.pm between versions 1.160.6.112 and 1.160.6.118.2.5

version 1.160.6.112, 2021/03/07 01:13:14 version 1.160.6.118.2.5, 2022/02/21 05:31:41
Line 174  use File::Copy; Line 174  use File::Copy;
 use Locale::Language;  use Locale::Language;
 use DateTime::TimeZone;  use DateTime::TimeZone;
 use DateTime::Locale;  use DateTime::Locale;
   use Net::CIDR;
   
 my $registered_cleanup;  my $registered_cleanup;
 my $modified_urls;  my $modified_urls;
Line 216  sub handler { Line 217  sub handler {
                 'contacts','defaults','scantron','coursecategories',                  'contacts','defaults','scantron','coursecategories',
                 'serverstatuses','requestcourses','helpsettings',                  'serverstatuses','requestcourses','helpsettings',
                 'coursedefaults','usersessions','loadbalancing',                  'coursedefaults','usersessions','loadbalancing',
                 'requestauthor','selfenrollment','inststatus','passwords'],$dom);                  'requestauthor','selfenrollment','inststatus',
     my @prefs_order = ('rolecolors','login','defaults','passwords','quotas','autoenroll',                  'passwords','ltitools','ltisec','wafproxy','ipaccess'],$dom);
                        'autoupdate','autocreate','directorysrch','contacts',      if (ref($domconfig{'ltitools'}) eq 'HASH') {
                        'usercreation','selfcreation','usermodification','scantron',          my %encconfig =
                        'requestcourses','requestauthor','coursecategories',              &Apache::lonnet::get_dom('encconfig',['ltitools','linkprot'],$dom,undef,1);
           if (ref($encconfig{'ltitools'}) eq 'HASH') {
               foreach my $id (keys(%{$domconfig{'ltitools'}})) {
                   if (ref($domconfig{'ltitools'}{$id}) eq 'HASH') {
                       foreach my $item ('key','secret') {
                           $domconfig{'ltitools'}{$id}{$item} = $encconfig{'ltitools'}{$id}{$item};
                       }
                   }
               }
           }
       }
       if (ref($domconfig{'ltisec'}) eq 'HASH') {
           if (ref($domconfig{'ltisec'}{'linkprot'}) eq 'HASH') {
               if (ref($encconfig{'linkprot'}) eq 'HASH') {
                   foreach my $id (keys(%{$domconfig{'ltisec'}{'linkprot'}})) {
                       unless ($id =~ /^\d+$/) {
                           delete($domconfig{'ltisec'}{'linkprot'}{$id});
                       }
                       if ((ref($domconfig{'ltisec'}{'linkprot'}{$id}) eq 'HASH') &&
                           (ref($encconfig{'linkprot'}{$id}) eq 'HASH')) {
                           foreach my $item ('key','secret') {
                               $domconfig{'ltisec'}{'linkprot'}{$id}{$item} = $encconfig{'linkprot'}{$id}{$item};
                           }
                       }
                   }
               }
           }
       }
       my @prefs_order = ('rolecolors','login','ipaccess','defaults','wafproxy','passwords',
                          'quotas','autoenroll','autoupdate','autocreate','directorysrch',
                          'contacts','usercreation','selfcreation','usermodification',
                          'scantron','requestcourses','requestauthor','coursecategories',
                        'serverstatuses','helpsettings','coursedefaults',                         'serverstatuses','helpsettings','coursedefaults',
                        'selfenrollment','usersessions');                         'ltitools','selfenrollment','usersessions','lti');
     my %existing;      my %existing;
     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {      if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
         %existing = %{$domconfig{'loadbalancing'}};          %existing = %{$domconfig{'loadbalancing'}};
Line 253  sub handler { Line 285  sub handler {
                                  {col1 => 'Log-in Help',                                   {col1 => 'Log-in Help',
                                   col2 => 'Value'},                                    col2 => 'Value'},
                                  {col1 => 'Custom HTML in document head',                                   {col1 => 'Custom HTML in document head',
                                   col2 => 'Value'}],                                    col2 => 'Value'},
                                    {col1 => 'SSO',
                                     col2 => 'Dual login: SSO and non-SSO options'},
                                   ],
                       print => \&print_login,                        print => \&print_login,
                       modify => \&modify_login,                        modify => \&modify_login,
                     },                      },
Line 267  sub handler { Line 302  sub handler {
                       print => \&print_defaults,                        print => \&print_defaults,
                       modify => \&modify_defaults,                        modify => \&modify_defaults,
                     },                      },
           'wafproxy' =>
                       { text => 'Web Application Firewall/Reverse Proxy',
                         help => 'Domain_Configuration_WAF_Proxy',
                         header => [{col1 => 'Domain(s)',
                                     col2 => 'Servers and WAF/Reverse Proxy alias(es)',
                                    },
                                    {col1 => 'Domain(s)',
                                     col2 => 'WAF Configuration',}],
                         print => \&print_wafproxy,
                         modify => \&modify_wafproxy,
                       },
         'passwords' =>          'passwords' =>
                     { text => 'Passwords (Internal authentication)',                      { text => 'Passwords (Internal authentication)',
                       help => 'Domain_Configuration_Passwords',                        help => 'Domain_Configuration_Passwords',
Line 490  sub handler { Line 536  sub handler {
                   print => \&print_loadbalancing,                    print => \&print_loadbalancing,
                   modify => \&modify_loadbalancing,                    modify => \&modify_loadbalancing,
                  },                   },
           'ltitools' =>
                    {text => 'External Tools (LTI)',
                     help => 'Domain_Configuration_LTI_Tools',
                     header => [{col1 => 'Setting',
                                 col2 => 'Value',}],
                     print => \&print_ltitools,
                     modify => \&modify_ltitools,
                    },
             'lti' =>
                    {text => 'LTI Link Protection and LTI Consumers',
                     help => 'Domain_Configuration_LTI_Provider',
                     header => [{col1 => 'Encryption of shared secrets',
                                 col2 => 'Settings'},
                                {col1 => 'Rules for shared secrets',
                                 col2 => 'Settings'},
                                {col1 => 'Link Protectors',
                                 col2 => 'Settings'},],
                     print => \&print_lti,
                     modify => \&modify_lti,
                    },
            'ipaccess' =>
                          {text => 'IP-based access control',
                           help => 'Domain_Configuration_IP_Access',
                           header => [{col1 => 'Setting',
                                       col2 => 'Value'},],
                           print  => \&print_ipaccess,
                           modify => \&modify_ipaccess,
                          },
     );      );
     if (keys(%servers) > 1) {      if (keys(%servers) > 1) {
         $prefs{'login'}  = { text   => 'Log-in page options',          $prefs{'login'}  = { text   => 'Log-in page options',
Line 497  sub handler { Line 571  sub handler {
                             header => [{col1 => 'Log-in Service',                              header => [{col1 => 'Log-in Service',
                                         col2 => 'Server Setting',},                                          col2 => 'Server Setting',},
                                        {col1 => 'Log-in Page Items',                                         {col1 => 'Log-in Page Items',
                                         col2 => ''},                                          col2 => 'Settings'},
                                        {col1 => 'Log-in Help',                                         {col1 => 'Log-in Help',
                                         col2 => 'Value'},                                          col2 => 'Value'},
                                        {col1 => 'Custom HTML in document head',                                         {col1 => 'Custom HTML in document head',
                                         col2 => 'Value'}],                                          col2 => 'Value'},
                                          {col1 => 'SSO',
                                           col2 => 'Dual login: SSO and non-SSO options'},
                                         ],
                             print => \&print_login,                              print => \&print_login,
                             modify => \&modify_login,                              modify => \&modify_login,
                            };                             };
Line 542  $javascript_validations Line 619  $javascript_validations
 </script>  </script>
 $coursebrowserjs  $coursebrowserjs
 END  END
           } elsif (grep(/^ipaccess$/,@actions)) {
               $js .= &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
         }          }
         if (grep(/^selfcreation$/,@actions)) {          if (grep(/^selfcreation$/,@actions)) {
             $js .= &selfcreate_javascript();              $js .= &selfcreate_javascript();
Line 672  sub process_changes { Line 751  sub process_changes {
         $output = &modify_usersessions($dom,$lastactref,%domconfig);          $output = &modify_usersessions($dom,$lastactref,%domconfig);
     } elsif ($action eq 'loadbalancing') {      } elsif ($action eq 'loadbalancing') {
         $output = &modify_loadbalancing($dom,%domconfig);          $output = &modify_loadbalancing($dom,%domconfig);
       } elsif ($action eq 'lti') {
           $output = &modify_lti($r,$dom,$action,$lastactref,%domconfig);
     } elsif ($action eq 'passwords') {      } elsif ($action eq 'passwords') {
         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);          $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
       } elsif ($action eq 'ltitools') {
           $output = &modify_ltitools($r,$dom,$action,$lastactref,%domconfig);
       } elsif ($action eq 'wafproxy') {
           $output = &modify_wafproxy($dom,$action,$lastactref,%domconfig);
       } elsif ($action eq 'ipaccess') {
           $output = &modify_ipaccess($dom,$lastactref,%domconfig);
     }      }
     return $output;      return $output;
 }  }
Line 687  sub print_config_box { Line 774  sub print_config_box {
     } elsif ($action eq 'defaults') {      } elsif ($action eq 'defaults') {
         $output = &defaults_javascript($settings);           $output = &defaults_javascript($settings); 
     } elsif ($action eq 'passwords') {      } elsif ($action eq 'passwords') {
         $output = &passwords_javascript();          $output = &passwords_javascript($action);
     } elsif ($action eq 'helpsettings') {      } elsif ($action eq 'helpsettings') {
         my (%privs,%levelscurrent);          my (%privs,%levelscurrent);
         my %full=();          my %full=();
Line 704  sub print_config_box { Line 791  sub print_config_box {
         $output =          $output =
             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full,              &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full,
                                                       \@templateroles);                                                        \@templateroles);
       } elsif ($action eq 'ltitools') {
           $output .= &ltitools_javascript($settings);
       } elsif ($action eq 'lti') {
           $output .= &passwords_javascript('secrets')."\n".
                      &lti_javascript($dom,$settings);
       } elsif ($action eq 'wafproxy') {
           $output .= &wafproxy_javascript($dom);
       } elsif ($action eq 'autoupdate') {
           $output .= &autoupdate_javascript();
       } elsif ($action eq 'autoenroll') {
           $output .= &autoenroll_javascript();
       } elsif ($action eq 'login') {
           $output .= &saml_javascript();
       } elsif ($action eq 'ipaccess') {
           $output .= &ipaccess_javascript($settings);
     }      }
     $output .=      $output .=
          '<table class="LC_nested_outer">           '<table class="LC_nested_outer">
           <tr>            <tr>
            <th align="left" valign="middle"><span class="LC_nobreak">'.             <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
            &mt($item->{text}).'&nbsp;'.             &mt($item->{text}).'&nbsp;'.
            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".             &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
           '</tr>';            '</tr>';
Line 723  sub print_config_box { Line 825  sub print_config_box {
         my $leftnobr = '';            my $leftnobr = '';  
         if (($action eq 'rolecolors') || ($action eq 'defaults') ||          if (($action eq 'rolecolors') || ($action eq 'defaults') ||
             ($action eq 'directorysrch') ||              ($action eq 'directorysrch') ||
             (($action eq 'login') && ($numheaders < 4))) {              (($action eq 'login') && ($numheaders < 5))) {
             $colspan = ' colspan="2"';              $colspan = ' colspan="2"';
         }          }
         if ($action eq 'usersessions') {          if ($action eq 'usersessions') {
Line 744  sub print_config_box { Line 846  sub print_config_box {
         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||          if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||              ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'directorysrch') ||              ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'directorysrch') ||
             ($action eq 'helpsettings') || ($action eq 'contacts')) {              ($action eq 'helpsettings') || ($action eq 'contacts') || ($action eq 'wafproxy') || ($action eq 'lti')) {
             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);              $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
         } elsif ($action eq 'passwords') {          } elsif ($action eq 'passwords') {
             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);              $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
Line 753  sub print_config_box { Line 855  sub print_config_box {
         } elsif ($action eq 'scantron') {          } elsif ($action eq 'scantron') {
             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);              $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
         } elsif ($action eq 'login') {          } elsif ($action eq 'login') {
             if ($numheaders == 4) {              if ($numheaders == 5) {
                 $colspan = ' colspan="2"';                  $colspan = ' colspan="2"';
                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);                  $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
             } else {              } else {
Line 779  sub print_config_box { Line 881  sub print_config_box {
         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||          if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||              ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
             ($action eq 'usersessions') || ($action eq 'coursecategories') ||              ($action eq 'usersessions') || ($action eq 'coursecategories') ||
             ($action eq 'contacts') || ($action eq 'passwords')) {              ($action eq 'contacts') || ($action eq 'passwords') || ($action eq 'lti')) {
             if ($action eq 'coursecategories') {              if ($action eq 'coursecategories') {
                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);                  $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
                 $colspan = ' colspan="2"';                  $colspan = ' colspan="2"';
Line 796  sub print_config_box { Line 898  sub print_config_box {
            <td>             <td>
             <table class="LC_nested">              <table class="LC_nested">
              <tr class="LC_info_row">               <tr class="LC_info_row">
               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>                <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>                <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
              </tr>'."\n";               </tr>'."\n";
             if ($action eq 'coursecategories') {              if ($action eq 'coursecategories') {
Line 816  sub print_config_box { Line 918  sub print_config_box {
            <td>             <td>
             <table class="LC_nested">              <table class="LC_nested">
              <tr class="LC_info_row">               <tr class="LC_info_row">
               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>                <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";                <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
                 if ($action eq 'passwords') {                  if ($action eq 'passwords') {
                     $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);                      $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
Line 834  sub print_config_box { Line 936  sub print_config_box {
             $rowtotal ++;              $rowtotal ++;
         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||          } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
                  ($action eq 'defaults') || ($action eq 'directorysrch') ||                   ($action eq 'defaults') || ($action eq 'directorysrch') ||
                  ($action eq 'helpsettings')) {                   ($action eq 'helpsettings') || ($action eq 'wafproxy')) {
             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);              $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
         } elsif ($action eq 'scantron') {          } elsif ($action eq 'scantron') {
             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);              $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
         } elsif ($action eq 'login') {          } elsif ($action eq 'login') {
             if ($numheaders == 4) {              if ($numheaders == 5) {
                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'                  $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
            </table>             </table>
           </td>            </td>
Line 863  sub print_config_box { Line 965  sub print_config_box {
            <td>             <td>
             <table class="LC_nested">              <table class="LC_nested">
              <tr class="LC_info_row">';               <tr class="LC_info_row">';
             if ($numheaders == 4) {              if ($numheaders == 5) {
                 $output .= '                  $output .= '
               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>                <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>                <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
Line 875  sub print_config_box { Line 977  sub print_config_box {
              </tr>';               </tr>';
             }              }
             $rowtotal ++;              $rowtotal ++;
             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal);              $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal).'
              </table>
             </td>
            </tr>
            <tr>
              <td>
               <table class="LC_nested">
                <tr class="LC_info_row">';
               if ($numheaders == 5) {
                   $output .= '
                 <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
                 <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
                </tr>';
               } else {
                   $output .= '
                 <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
                 <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
                </tr>';
               }
               $rowtotal ++;
               $output .= &print_login('saml',$dom,$confname,$phase,$settings,\$rowtotal);
         } elsif ($action eq 'requestcourses') {          } elsif ($action eq 'requestcourses') {
             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);              $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
             $rowtotal ++;              $rowtotal ++;
Line 994  sub print_config_box { Line 1116  sub print_config_box {
         if ($action eq 'quotas') {          if ($action eq 'quotas') {
             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);              $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') ||           } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing')) {                   ($action eq 'serverstatuses') || ($action eq 'loadbalancing') ||
                    ($action eq 'ltitools') || ($action eq 'ipaccess')) {
             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);              $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
         }          }
     }      }
Line 1008  sub print_config_box { Line 1131  sub print_config_box {
   
 sub print_login {  sub print_login {
     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;      my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
     my ($css_class,$datatable);      my ($css_class,$datatable,$switchserver,%lt);
     my %choices = &login_choices();      my %choices = &login_choices();
       if (($caller eq 'help') || ($caller eq 'headtag') || ($caller eq 'saml')) {
           %lt = &login_file_options();
           $switchserver = &check_switchserver($dom,$confname);
       }
   
     if ($caller eq 'service') {      if ($caller eq 'service') {
         my %servers = &Apache::lonnet::internet_dom_servers($dom);          my %servers = &Apache::lonnet::internet_dom_servers($dom);
Line 1097  sub print_login { Line 1224  sub print_login {
             }              }
         }          }
         my @images = ('img','logo','domlogo','login');          my @images = ('img','logo','domlogo','login');
           my @alttext = ('img','logo','domlogo');
         my @logintext = ('textcol','bgcol');          my @logintext = ('textcol','bgcol');
         my @bgs = ('pgbg','mainbg','sidebg');          my @bgs = ('pgbg','mainbg','sidebg');
         my @links = ('link','alink','vlink');          my @links = ('link','alink','vlink');
Line 1138  sub print_login { Line 1266  sub print_login {
                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};                      $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
                 }                  }
             }              }
               foreach my $item (@alttext) {
                   if (ref($settings->{'alttext'}) eq 'HASH') {
                       if ($settings->{'alttext'}->{$item} ne '') {
                           $designs{'alttext'}{$item} = $settings->{'alttext'}{$item};
                       }
                   }
               }
             foreach my $item (@logintext) {              foreach my $item (@logintext) {
                 if ($settings->{$item} ne '') {                  if ($settings->{$item} ne '') {
                     $designs{'logintext'}{$item} = $settings->{$item};                      $designs{'logintext'}{$item} = $settings->{$item};
Line 1204  sub print_login { Line 1339  sub print_login {
         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);          $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
         $datatable .= '</tr></table></td></tr>';          $datatable .= '</tr></table></td></tr>';
     } elsif ($caller eq 'help') {      } elsif ($caller eq 'help') {
         my ($defaulturl,$defaulttype,%url,%type,%lt,%langchoices);          my ($defaulturl,$defaulttype,%url,%type,%langchoices);
         my $switchserver = &check_switchserver($dom,$confname);  
         my $itemcount = 1;          my $itemcount = 1;
         $defaulturl = '/adm/loginproblems.html';          $defaulturl = '/adm/loginproblems.html';
         $defaulttype = 'default';          $defaulttype = 'default';
         %lt = &Apache::lonlocal::texthash (  
                      del     => 'Delete?',  
                      rep     => 'Replace:',  
                      upl     => 'Upload:',  
                      default => 'Default',  
                      custom  => 'Custom',  
                                              );  
         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());          %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
         my @currlangs;          my @currlangs;
         if (ref($settings) eq 'HASH') {          if (ref($settings) eq 'HASH') {
Line 1312  sub print_login { Line 1439  sub print_login {
                 }                  }
             }              }
         }          }
         my %lt = &Apache::lonlocal::texthash(  
                                                del  => 'Delete?',  
                                                rep  => 'Replace:',  
                                                upl  => 'Upload:',  
                                                curr => 'View contents',  
                                                none => 'None',  
         );  
         my $switchserver = &check_switchserver($dom,$confname);  
         foreach my $lonhost (sort(keys(%domservers))) {          foreach my $lonhost (sort(keys(%domservers))) {
             my $exempt = &check_exempt_addresses($currexempt{$lonhost});              my $exempt = &check_exempt_addresses($currexempt{$lonhost});
             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';              $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
Line 1343  sub print_login { Line 1462  sub print_login {
             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';              $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
         }          }
         $datatable .= '</table></td></tr>';          $datatable .= '</table></td></tr>';
       } elsif ($caller eq 'saml') {
           my %domservers = &Apache::lonnet::get_servers($dom);
           $datatable .= '<tr><td colspan="3" style="text-align: left">'.
                         '<table><tr><th>'.$choices{'hostid'}.'</th>'.
                         '<th>'.$choices{'samllanding'}.'</th>'.
                         '<th>'.$choices{'samloptions'}.'</th></tr>'."\n";
           my (%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso,%styleon,%styleoff);
           foreach my $lonhost (keys(%domservers)) {
               $samlurl{$lonhost} = '/adm/sso';
               $styleon{$lonhost} = 'display:none';
               $styleoff{$lonhost} = '';
           }
           if (ref($settings->{'saml'}) eq 'HASH') {
               foreach my $lonhost (keys(%{$settings->{'saml'}})) {
                   if (ref($settings->{'saml'}{$lonhost}) eq 'HASH') {
                       $saml{$lonhost} = 1;
                       $samltext{$lonhost} = $settings->{'saml'}{$lonhost}{'text'};
                       $samlimg{$lonhost} = $settings->{'saml'}{$lonhost}{'img'};
                       $samlalt{$lonhost} = $settings->{'saml'}{$lonhost}{'alt'};
                       $samlurl{$lonhost} = $settings->{'saml'}{$lonhost}{'url'};
                       $samltitle{$lonhost} = $settings->{'saml'}{$lonhost}{'title'};
                       $samlnotsso{$lonhost} = $settings->{'saml'}{$lonhost}{'notsso'};
                       $styleon{$lonhost} = '';
                       $styleoff{$lonhost} = 'display:none';
                   } else {
                       $styleon{$lonhost} = 'display:none';
                       $styleoff{$lonhost} = '';
                   }
               }
           }
           my $itemcount = 1;
           foreach my $lonhost (sort(keys(%domservers))) {
               my $samlon = ' ';
               my $samloff = ' checked="checked" ';
               if ($saml{$lonhost}) {
                   $samlon = $samloff;
                   $samloff = ' ';
               }
               my $css_class = $itemcount%2?' class="LC_odd_row"':'';
               $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.$domservers{$lonhost}.'</span></td>'.
                             '<td><span class="LC_nobreak"><label><input type="radio" name="saml_'.$lonhost.'"'.$samloff.
                             'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="0" />'.
                             &mt('No').'</label>'.('&nbsp;'x2).
                             '<label><input type="radio" name="saml_'.$lonhost.'"'.$samlon.
                             'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="1" />'.
                             &mt('Yes').'</label></span></td>'.
                             '<td id="samloptionson_'.$lonhost.'" style="'.$styleon{$lonhost}.'" width="100%">'.
                             '<table><tr><th colspan="5" align="center">'.&mt('SSO').'</th><th align="center">'.
                             '<span class="LC_nobreak">'.&mt('Non-SSO').'</span></th></tr>'.
                             '<tr><th>'.&mt('Text').'</th><th>'.&mt('Image').'</th>'.
                             '<th>'.&mt('Alt Text').'</th><th>'.&mt('URL').'</th>'.
                             '<th>'.&mt('Tool Tip').'</th><th>'.&mt('Text').'</th></tr>'.
                             '<tr'.$css_class.'><td><input type="text" name="saml_text_'.$lonhost.'" size="8" value="'.
                             $samltext{$lonhost}.'" /></td><td>';
               if ($samlimg{$lonhost}) {
                   $datatable .= '<img src="'.$samlimg{$lonhost}.'" /><br />'.
                                 '<span class="LC_nobreak"><label>'.
                                 '<input type="checkbox" name="saml_img_del" value="'.$lonhost.'" />'.
                                 $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
               } else {
                   $datatable .= $lt{'upl'};
               }
               $datatable .='<br />';
               if ($switchserver) {
                   $datatable .= &mt('Upload to library server: [_1]',$switchserver);
               } else {
                   $datatable .= '<input type="file" name="saml_img_'.$lonhost.'" />';
               }
               $datatable .= '</td>'.
                             '<td><input type="text" name="saml_alt_'.$lonhost.'" size="20" '.
                             'value="'.$samlalt{$lonhost}.'" /></td>'.
                             '<td><input type="text" name="saml_url_'.$lonhost.'" size="8" '.
                             'value="'.$samlurl{$lonhost}.'" /></td>'.
                             '<td><textarea name="saml_title_'.$lonhost.'" rows="3" cols="15">'.
                             $samltitle{$lonhost}.'</textarea></td>'.
                             '<td><input type="text" name="saml_notsso_'.$lonhost.'" size="8" '.
                             'value="'.$samlnotsso{$lonhost}.'" /></td></tr>'.
                             '</table></td>'.
                             '<td id="samloptionsoff_'.$lonhost.'" style="'.$styleoff{$lonhost}.'" width="100%">&nbsp;</td></tr>';
              $itemcount ++;
           }
           $datatable .= '</table></td></tr>';
     }      }
     return $datatable;      return $datatable;
 }  }
Line 1379  sub login_choices { Line 1580  sub login_choices {
             headtag       => "Custom markup",              headtag       => "Custom markup",
             action        => "Action",              action        => "Action",
             current       => "Current",              current       => "Current",
               samllanding   => "Dual login?",
               samloptions   => "Options",
               alttext       => "Alt text",
         );          );
     return %choices;      return %choices;
 }  }
   
   sub login_file_options {
         return &Apache::lonlocal::texthash(
                                              del     => 'Delete?',
                                              rep     => 'Replace:',
                                              upl     => 'Upload:',
                                              curr    => 'View contents',
                                              default => 'Default',
                                              custom  => 'Custom',
                                              none    => 'None',
         );
   }
   
   sub print_ipaccess {
       my ($dom,$settings,$rowtotal) = @_;
       my $css_class;
       my $itemcount = 0;
       my $datatable;
       my %ordered;
       if (ref($settings) eq 'HASH') {
           foreach my $item (keys(%{$settings})) {
               if (ref($settings->{$item}) eq 'HASH') {
                   my $num = $settings->{$item}{'order'};
                   if ($num eq '') {
                       $num = scalar(keys(%{$settings}));
                   }
                   $ordered{$num} = $item;
               }
           }
       }
       my $maxnum = scalar(keys(%ordered));
       if (keys(%ordered)) {
           my @items = sort { $a <=> $b } keys(%ordered);
           for (my $i=0; $i<@items; $i++) {
               $css_class = $itemcount%2?' class="LC_odd_row"':'';
               my $item = $ordered{$items[$i]};
               my ($name,$ipranges,%commblocks,%courses);
               if (ref($settings->{$item}) eq 'HASH') {
                   $name = $settings->{$item}->{'name'};
                   $ipranges = $settings->{$item}->{'ip'};
                   if (ref($settings->{$item}->{'commblocks'}) eq 'HASH') {
                       %commblocks = %{$settings->{$item}->{'commblocks'}};
                   }
                   if (ref($settings->{$item}->{'courses'}) eq 'HASH') {
                       %courses = %{$settings->{$item}->{'courses'}};
                   }
               }
               my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_".$item."'".');"';
               $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
                            .'<select name="ipaccess_pos_'.$item.'"'.$chgstr.'>';
               for (my $k=0; $k<=$maxnum; $k++) {
                   my $vpos = $k+1;
                   my $selstr;
                   if ($k == $i) {
                       $selstr = ' selected="selected" ';
                   }
                   $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
               }
               $datatable .= '</select>'.('&nbsp;'x2).
                   '<label><input type="checkbox" name="ipaccess_del" value="'.$item.'" />'.
                   &mt('Delete?').'</label></span></td>'.
                   '<td colspan="2"><input type="hidden" name="ipaccess_id_'.$i.'" value="'.$item.'" />'.
                   &ipaccess_options($i,$itemcount,$dom,$name,$ipranges,\%commblocks,\%courses).
                   '</td></tr>';
               $itemcount ++;
           }
       }
       $css_class = $itemcount%2?' class="LC_odd_row"':'';
       my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_add'".');"';
       $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
                     '<input type="hidden" name="ipaccess_maxnum" value="'.$maxnum.'" />'."\n".
                     '<select name="ipaccess_pos_add"'.$chgstr.'>';
       for (my $k=0; $k<$maxnum+1; $k++) {
           my $vpos = $k+1;
           my $selstr;
           if ($k == $maxnum) {
               $selstr = ' selected="selected" ';
           }
           $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
       }
       $datatable .= '</select>&nbsp;'."\n".
                     '<input type="checkbox" name="ipaccess_add" value="1" />'.&mt('Add').'</span></td>'."\n".
                     '<td colspan="2">'.
                     &ipaccess_options('add',$itemcount,$dom).
                     '</td>'."\n".
                     '</tr>'."\n";
       $$rowtotal ++;
       return $datatable;
   }
   
   sub ipaccess_options {
       my ($num,$itemcount,$dom,$name,$ipranges,$blocksref,$coursesref) = @_;
       my (%currblocks,%currcourses,$output);
       if (ref($blocksref) eq 'HASH') {
           %currblocks = %{$blocksref};
       }
       if (ref($coursesref) eq 'HASH') {
           %currcourses = %{$coursesref};
       }
       $output = '<fieldset><legend>'.&mt('Location(s)').'</legend>'.
                 '<span class="LC_nobreak">'.&mt('Name').':&nbsp;'.
                 '<input type="text" name="ipaccess_name_'.$num.'" value="'.$name.'" />'.
                 '</span></fieldset>'.
                 '<fieldset><legend>'.&mt('IP Range(s)').'</legend>'.
                 &mt('Format for each IP range').': '.&mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
                 &mt('Range(s) will be stored as IP netblock(s) in CIDR notation (comma separated)').'<br />'.
                 '<textarea name="ipaccess_range_'.$num.'" rows="3" cols="80">'.
                 $ipranges.'</textarea></fieldset>'.
                 '<fieldset><legend>'.&mt('Functionality Blocked?').'</legend>'.
                 &blocker_checkboxes($num,$blocksref).'</fieldset>'.
                 '<fieldset><legend>'.&mt('Courses/Communities allowed').'</legend>'.
                 '<table>';
       foreach my $cid (sort(keys(%currcourses))) {
           my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
           $output .= '<tr><td><span class="LC_nobreak">'.
                      '<label><input type="checkbox" name="ipaccess_course_delete_'.$num.'" value="'.$cid.'" />'.
                      &mt('Delete?').'&nbsp;<span class="LC_cusr_emph">'.$courseinfo{'description'}.'</span></label></span>'.
                      ' <span class="LC_fontsize_medium">('.$cid.')</span></td></tr>';
       }
       $output .= '<tr><td><span class="LC_nobreak">'.&mt('Add').':&nbsp;'.
                  '<input type="text" name="ipaccess_cdesc_'.$num.'" value="" onfocus="this.blur();opencrsbrowser('."'display','ipaccess_cnum_$num','ipaccess_cdom_$num','ipaccess_cdesc_$num'".');" />'.
                   &Apache::loncommon::selectcourse_link('display','ipaccess_cnum_'.$num,'ipaccess_cdom_'.$num,'ipaccess_cdesc_'.$num,$dom,undef,'Course/Community').
                  '<input type="hidden" name="ipaccess_cnum_'.$num.'" value="" />'.
                  '<input type="hidden" name="ipaccess_cdom_'.$num.'" value="" />'.
                  '</span></td></tr></table>'."\n".
                  '</fieldset>';
       return $output;
   }
   
   sub blocker_checkboxes {
       my ($num,$blocks) = @_;
       my ($typeorder,$types) = &commblocktype_text();
       my $numinrow = 6;
       my $output = '<table>';
       for (my $i=0; $i<@{$typeorder}; $i++) {
           my $block = $typeorder->[$i];
           my $blockstatus;
           if (ref($blocks) eq 'HASH') {
               if ($blocks->{$block} eq 'on') {
                   $blockstatus = 'checked="checked"';
               }
           }
           my $rem = $i%($numinrow);
           if ($rem == 0) {
               if ($i > 0) {
                   $output .= '</tr>';
               }
               $output .= '<tr>';
           }
           if ($i == scalar(@{$typeorder})-1) {
               my $colsleft = $numinrow-$rem;
               if ($colsleft > 1) {
                   $output .= '<td colspan="'.$colsleft.'">';
               } else {
                   $output .= '<td>';
               }
           } else {
               $output .= '<td>';
           }
           my $item = 'ipaccess_block_'.$num;
           if ($blockstatus) {
               $blockstatus = ' '.$blockstatus;
           }
           $output .= '<span class="LC_nobreak"><label>'."\n".
                      '<input type="checkbox" name="'.$item.'"'.
                      $blockstatus.' value="'.$block.'"'.' />'.
                      $types->{$block}.'</label></span>'."\n".
                      '<br /></td>';
       }
       $output .= '</tr></table>';
       return $output;
   }
   
   sub commblocktype_text {
       my %types = &Apache::lonlocal::texthash(
           'com' => 'Messaging',
           'chat' => 'Chat Room',
           'boards' => 'Discussion',
           'port' => 'Portfolio',
           'groups' => 'Groups',
           'blogs' => 'Blogs',
           'about' => 'User Information',
           'printout' => 'Printouts',
           'passwd' => 'Change Password',
           'grades' => 'Gradebook',
           'search' => 'Course search',
           'wishlist' => 'Stored links',
           'annotate' => 'Annotations',
       );
       my $typeorder = ['com','chat','boards','port','groups','blogs','about','wishlist','printout','grades','search','annotate','passwd'];
       return ($typeorder,\%types);
   }
   
 sub print_rolecolors {  sub print_rolecolors {
     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;      my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
     my %choices = &color_font_choices();      my %choices = &color_font_choices();
Line 1532  sub display_color_options { Line 1928  sub display_color_options {
         $css_class = $itemcount%2?' class="LC_odd_row"':'';          $css_class = $itemcount%2?' class="LC_odd_row"':'';
         $datatable .= '<tr'.$css_class.'>'.          $datatable .= '<tr'.$css_class.'>'.
                       '<td>'.$choices->{$img};                        '<td>'.$choices->{$img};
         my ($imgfile,$img_import,$login_hdr_pick,$logincolors);          my ($imgfile,$img_import,$login_hdr_pick,$logincolors,$alttext);
         if ($role eq 'login') {          if ($role eq 'login') {
             if ($img eq 'login') {              if ($img eq 'login') {
                 $login_hdr_pick =                  $login_hdr_pick =
Line 1540  sub display_color_options { Line 1936  sub display_color_options {
                 $logincolors =                  $logincolors =
                     &login_text_colors($img,$role,$logintext,$phase,$choices,                      &login_text_colors($img,$role,$logintext,$phase,$choices,
                                        $designs,$defaults);                                         $designs,$defaults);
             } elsif ($img ne 'domlogo') {              } else {
                 $datatable.= &logo_display_options($img,$defaults,$designs);                  if ($img ne 'domlogo') {
                       $datatable.= &logo_display_options($img,$defaults,$designs);
                   }
                   if (ref($designs->{'alttext'}) eq 'HASH') {
                       $alttext = $designs->{'alttext'}{$img};
                   }
             }              }
         }          }
         $datatable .= '</td>';          $datatable .= '</td>';
Line 1633  sub display_color_options { Line 2034  sub display_color_options {
                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';                  $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
             }              }
         }          }
           if (($role eq 'login') && ($img ne 'login')) {
               $datatable .= ('&nbsp;' x2).' <span class="LC_nobreak"><label>'.$choices->{'alttext'}.':'.
                             '<input type="text" name="'.$role.'_alt_'.$img.'" size="10" value="'.$alttext.'" />'.
                             '</label></span>';
           }
         $datatable .= '</td></tr>';          $datatable .= '</td></tr>';
     }      }
     $itemcount ++;      $itemcount ++;
Line 2355  sub print_textbookcourses { Line 2761  sub print_textbookcourses {
                               ('&nbsp;'x2).                                ('&nbsp;'x2).
                               '<span class="LC_nobreak">'.&mt('Thumbnail:');                                '<span class="LC_nobreak">'.&mt('Thumbnail:');
                 if ($image) {                  if ($image) {
                     $datatable .= '<span class="LC_nobreak">'.                      $datatable .= $imgsrc.
                                   $imgsrc.  
                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.                                    '<label><input type="checkbox" name="'.$type.'_image_del"'.
                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.                                    ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';                                    '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
Line 2510  $jstext{'templates'}; Line 2915  $jstext{'templates'};
 ENDSCRIPT  ENDSCRIPT
 }  }
   
   sub ltitools_javascript {
       my ($settings) = @_;
       my $togglejs = &ltitools_toggle_js();
       unless (ref($settings) eq 'HASH') {
           return $togglejs;
       }
       my (%ordered,$total,%jstext);
       $total = 0;
       foreach my $item (keys(%{$settings})) {
           if (ref($settings->{$item}) eq 'HASH') {
               my $num = $settings->{$item}{'order'};
               $ordered{$num} = $item;
           }
       }
       $total = scalar(keys(%{$settings}));
       my @jsarray = ();
       foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
           push(@jsarray,$ordered{$item});
       }
       my $jstext = '    var ltitools = Array('."'".join("','",@jsarray)."'".');'."\n";
       return <<"ENDSCRIPT";
   <script type="text/javascript">
   // <![CDATA[
   function reorderLTITools(form,item) {
       var changedVal;
   $jstext
       var newpos = 'ltitools_add_pos';
       var maxh = 1 + $total;
       var current = new Array;
       var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
       if (item == newpos) {
           changedVal = newitemVal;
       } else {
           changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
           current[newitemVal] = newpos;
       }
       for (var i=0; i<ltitools.length; i++) {
           var elementName = 'ltitools_'+ltitools[i];
           if (elementName != item) {
               if (form.elements[elementName]) {
                   var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
                   current[currVal] = elementName;
               }
           }
       }
       var oldVal;
       for (var j=0; j<maxh; j++) {
           if (current[j] == undefined) {
               oldVal = j;
           }
       }
       if (oldVal < changedVal) {
           for (var k=oldVal+1; k<=changedVal ; k++) {
              var elementName = current[k];
              form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
           }
       } else {
           for (var k=changedVal; k<oldVal; k++) {
               var elementName = current[k];
               form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
           }
       }
       return;
   }
   
   // ]]>
   </script>
   
   $togglejs
   
   ENDSCRIPT
   }
   
   sub ltitools_toggle_js {
       return <<"ENDSCRIPT";
   <script type="text/javascript">
   // <![CDATA[
   
   function toggleLTITools(form,setting,item) {
       var radioname = '';
       var divid = '';
       if (setting == 'user') {
           divid = 'ltitools_'+setting+'_div_'+item;
           var checkid = 'ltitools_'+setting+'_field_'+item;
           if (document.getElementById(divid)) {
               if (document.getElementById(checkid)) {
                   if (document.getElementById(checkid).checked) {
                       document.getElementById(divid).style.display = 'inline-block';
                   } else {
                       document.getElementById(divid).style.display = 'none';
                   }
               }
           }
       }
       return;
   }
   // ]]>
   </script>
   
   ENDSCRIPT
   }
   
   sub wafproxy_javascript {
       my ($dom) = @_;
       return <<"ENDSCRIPT";
   <script type="text/javascript">
   // <![CDATA[
   function updateWAF() {
       if (document.getElementById('wafproxy_remoteip')) {
           var wafremote = 0;
           if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value == 'h') {
               wafremote = 1;
           }
           var fields = new Array('header','trust');
           for (var i=0; i<fields.length; i++) {
               if (document.getElementById('wafproxy_'+fields[i])) {
                   if (wafremote == 1) {
                       document.getElementById('wafproxy_'+fields[i]).style.display = 'table-row';
                   }
                   else {
                       document.getElementById('wafproxy_'+fields[i]).style.display = 'none';
                   }
               }
           }
           if (document.getElementById('wafproxyranges_$dom')) {
               if (wafremote == 1) {
                   document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
               } else {
                   for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
                       if (document.display.wafproxy_vpnaccess[i].checked) {
                           if (document.display.wafproxy_vpnaccess[i].value == 0) {
                               document.getElementById('wafproxyranges_$dom').style.display = 'none';
                           }
                       }
                   }
               }
           }
       }
       return;
   }
   
   function checkWAF() {
       if (document.getElementById('wafproxy_remoteip')) {
           var wafvpn = 0;
           for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
               if (document.display.wafproxy_vpnaccess[i].checked) {
                   if (document.display.wafproxy_vpnaccess[i].value == 1) {
                       wafvpn = 1;
                   }
                   break;
               }
           }
           var vpn = new Array('vpnint','vpnext');
           for (var i=0; i<vpn.length; i++) {
               if (document.getElementById('wafproxy_show_'+vpn[i])) {
                   if (wafvpn == 1) {
                       document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'table-row';
                   }
                   else {
                       document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'none';
                   }
               }
           }
           if (document.getElementById('wafproxyranges_$dom')) {
               if (wafvpn == 1) {
                   document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
               }
               else if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value != 'h') {
                   document.getElementById('wafproxyranges_$dom').style.display = 'none';
               }
           }
       }
       return;
   }
   
   function toggleWAF() {
       if (document.getElementById('wafproxy_table')) {
           var wafproxy = 0;
           for (var i=0; i<document.display.wafproxy_${dom}.length; i++) {
                if (document.display.wafproxy_${dom}[i].checked) {
                    if (document.display.wafproxy_${dom}[i].value == 1) {
                        wafproxy = 1;
                        break;
                   }
               }
           }
           if (wafproxy == 1) {
               document.getElementById('wafproxy_table').style.display='inline';
           }
           else {
              document.getElementById('wafproxy_table').style.display='none';
           }
           if (document.getElementById('wafproxyrow_${dom}')) {
               if (wafproxy == 1) {
                   document.getElementById('wafproxyrow_${dom}').style.display = 'table-row';
               }
               else {
                   document.getElementById('wafproxyrow_${dom}').style.display = 'none';
               }
           }
           if (document.getElementById('nowafproxyrow_$dom')) {
               if (wafproxy == 1) {
                   document.getElementById('nowafproxyrow_${dom}').style.display = 'none';
               }
               else {
                   document.getElementById('nowafproxyrow_${dom}').style.display = 'table-row';
               }
           }
       }
       return;
   }
   // ]]>
   </script>
   
   ENDSCRIPT
   }
   
   sub lti_javascript {
       my ($dom,$settings) = @_;
       my $togglejs = &lti_toggle_js($dom);
       my $linkprot_js = &Apache::courseprefs::linkprot_javascript();
       return <<"ENDSCRIPT";
   <script type="text/javascript">
   // <![CDATA[
   
   $linkprot_js
   
   // ]]>
   </script>
   
   $togglejs
   
   ENDSCRIPT
   }
   
   sub lti_toggle_js {
       my ($dom) = @_;
       my %servers = &Apache::lonnet::get_servers($dom,'library');
       my $primary = &Apache::lonnet::domain($dom,'primary');
       my $course_servers = "'".join("','",keys(%servers))."'";
   function toggleLTIEncKey(form) {
       var shownhosts = new Array();
       var hiddenhosts = new Array();
       var forcourse = new Array($course_servers);
       var fromdomain = '$primary';
       var crsradio = form.elements['ltisec_crslinkprot'];
       if (crsradio.length) {
           for (var i=0; i<crsradio.length; i++) {
               if (crsradio[i].checked) {
                   if (crsradio[i].value == 1) {
                       if (forcourse.length > 0) {
                           for (var j=0; j<forcourse.length; j++) {
                               if (!shownhosts.includes(forcourse[j])) {
                                   shownhosts.push(forcourse[j]);
                               }
                           }
                       }
                   } else {
                       if (forcourse.length > 0) {
                           for (var j=0; j<forcourse.length; j++) {
                               if (!hiddenhosts.includes(forcourse[j])) {
                                   hiddenhosts.push(forcourse[j]);
                               }
                           }
                       }
                   }
               }
           }
       }
       var domradio = form.elements['ltisec_domlinkprot'];
       if (domradio.length) {
           for (var i=0; i<domradio.length; i++) {
               if (domradio[i].checked) {
                   if (domradio[i].value == 1) {
                       if (!shownhosts.includes(fromdomain)) {
                           shownhosts.push(fromdomain);
                       }
                   } else {
                       if (!hiddenhosts.includes(fromdomain)) {
                           hiddenhosts.push(fromdomain);
                       }
                   }
               }
           }
       }
       if (shownhosts.length > 0) {
           for (var i=0; i<shownhosts.length; i++) {
               if (document.getElementById('ltisec_info_'+shownhosts[i])) {
                   document.getElementById('ltisec_info_'+shownhosts[i]).style.display = 'block';
               }
           }
           if (document.getElementById('ltisec_noprivkey')) {
               document.getElementById('ltisec_noprivkey').style.display = 'none';
           }
       } else {
           if (document.getElementById('ltisec_noprivkey')) {
               document.getElementById('ltisec_noprivkey').style.display = 'inline-block';
           }
       }
       if (hiddenhosts.length > 0) {
           for (var i=0; i<hiddenhosts.length; i++) {
               if (!shownhosts.includes(hiddenhosts[i])) {
                   if (document.getElementById('ltisec_info_'+hiddenhosts[i])) {
                       document.getElementById('ltisec_info_'+hiddenhosts[i]).style.display = 'none';
                   }
               }
           }
       }
       return;
   }
   
   function togglePrivKey(form,hostid) {
       var radioname = '';
       var currdivid = '';
       var newdivid = '';
       if ((document.getElementById('ltisec_divcurrprivkey_'+hostid)) &&
           (document.getElementById('ltisec_divchgprivkey_'+hostid))) {
           currdivid = document.getElementById('ltisec_divcurrprivkey_'+hostid);
           newdivid = document.getElementById('ltisec_divchgprivkey_'+hostid);
           radioname = form.elements['ltisec_changeprivkey_'+hostid];
           if (radioname) {
               if (radioname.length > 0) {
                   var setvis;
                   for (var i=0; i<radioname.length; i++) {
                       if (radioname[i].checked == true) {
                           if (radioname[i].value == 1) {
                               newdivid.style.display = 'inline-block';
                               currdivid.style.display = 'none';
                               setvis = 1;
                           }
                           break;
                       }
                   }
                   if (!setvis) {
                       newdivid.style.display = 'none';
                       currdivid.style.display = 'inline-block';
                   }
               }
           }
       }
   }
   
   // ]]>
   </script>
   
   ENDSCRIPT
   }
   
   sub autoupdate_javascript {
       return <<"ENDSCRIPT";
   <script type="text/javascript">
   // <![CDATA[
   function toggleLastActiveDays(form) {
       var radioname = 'lastactive';
       var divid = 'lastactive_div';
       var num = form.elements[radioname].length;
       if (num) {
           var setvis = '';
           for (var i=0; i<num; i++) {
               if (form.elements[radioname][i].checked) {
                   if (form.elements[radioname][i].value == '1') {
                       if (document.getElementById(divid)) {
                           document.getElementById(divid).style.display = 'inline-block';
                       }
                       setvis = 1;
                   }
                   break;
               }
           }
           if (!setvis) {
               if (document.getElementById(divid)) {
                   document.getElementById(divid).style.display = 'none';
               }
           }
       }
       return;
   }
   // ]]>
   </script>
   
   ENDSCRIPT
   }
   
   sub autoenroll_javascript {
       return <<"ENDSCRIPT";
   <script type="text/javascript">
   // <![CDATA[
   function toggleFailsafe(form) {
       var radioname = 'autoenroll_failsafe';
       var divid = 'autoenroll_failsafe_div';
       var num = form.elements[radioname].length;
       if (num) {
           var setvis = '';
           for (var i=0; i<num; i++) {
               if (form.elements[radioname][i].checked) {
                   if ((form.elements[radioname][i].value == 'zero') || (form.elements[radioname][i].value == 'any')) {
                       if (document.getElementById(divid)) {
                           document.getElementById(divid).style.display = 'inline-block';
                       }
                       setvis = 1;
                   }
                   break;
               }
           }
           if (!setvis) {
               if (document.getElementById(divid)) {
                   document.getElementById(divid).style.display = 'none';
               }
           }
       }
       return;
   }
   // ]]>
   </script>
   
   ENDSCRIPT
   }
   
   sub saml_javascript {
       return <<"ENDSCRIPT";
   <script type="text/javascript">
   // <![CDATA[
   function toggleSamlOptions(form,hostid) {
       var radioname = 'saml_'+hostid;
       var tablecellon = 'samloptionson_'+hostid;
       var tablecelloff = 'samloptionsoff_'+hostid;
       var num = form.elements[radioname].length;
       if (num) {
           var setvis = '';
           for (var i=0; i<num; i++) {
               if (form.elements[radioname][i].checked) {
                   if (form.elements[radioname][i].value == '1') {
                       if (document.getElementById(tablecellon)) {
                           document.getElementById(tablecellon).style.display='';
                       }
                       if (document.getElementById(tablecelloff)) {
                           document.getElementById(tablecelloff).style.display='none';
                       }
                       setvis = 1;
                   }
                   break;
               }
           }
           if (!setvis) {
               if (document.getElementById(tablecellon)) {
                   document.getElementById(tablecellon).style.display='none';
               }
               if (document.getElementById(tablecelloff)) {
                   document.getElementById(tablecelloff).style.display='';
               }
           }
       }
       return;
   }
   // ]]>
   </script>
   
   ENDSCRIPT
   }
   
   sub ipaccess_javascript {
       my ($settings) = @_;
       my (%ordered,$total,%jstext);
       $total = 0;
       if (ref($settings) eq 'HASH') {
           foreach my $item (keys(%{$settings})) {
               if (ref($settings->{$item}) eq 'HASH') {
                   my $num = $settings->{$item}{'order'};
                   $ordered{$num} = $item;
               }
           }
           $total = scalar(keys(%{$settings}));
       }
       my @jsarray = ();
       foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
           push(@jsarray,$ordered{$item});
       }
       my $jstext = '    var ipaccess = Array('."'".join("','",@jsarray)."'".');'."\n";
       return <<"ENDSCRIPT";
   <script type="text/javascript">
   // <![CDATA[
   function reorderIPaccess(form,item) {
       var changedVal;
   $jstext
       var newpos = 'ipaccess_pos_add';
       var maxh = 1 + $total;
       var current = new Array;
       var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
       if (item == newpos) {
           changedVal = newitemVal;
       } else {
           changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
           current[newitemVal] = newpos;
       }
       for (var i=0; i<ipaccess.length; i++) {
           var elementName = 'ipaccess_pos_'+ipaccess[i];
           if (elementName != item) {
               if (form.elements[elementName]) {
                   var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
                   current[currVal] = elementName;
               }
           }
       }
       var oldVal;
       for (var j=0; j<maxh; j++) {
           if (current[j] == undefined) {
               oldVal = j;
           }
       }
       if (oldVal < changedVal) {
           for (var k=oldVal+1; k<=changedVal ; k++) {
              var elementName = current[k];
              form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
           }
       } else {
           for (var k=changedVal; k<oldVal; k++) {
               var elementName = current[k];
               form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
           }
       }
       return;
   }
   // ]]>
   </script>
   
   ENDSCRIPT
   }
   
 sub print_autoenroll {  sub print_autoenroll {
     my ($dom,$settings,$rowtotal) = @_;      my ($dom,$settings,$rowtotal) = @_;
     my $autorun = &Apache::lonnet::auto_run(undef,$dom),      my $autorun = &Apache::lonnet::auto_run(undef,$dom),
     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,$failsafe);      my ($defdom,$runon,$runoff,$coownerson,$coownersoff,
           $failsafe,$autofailsafe,$failsafesty,%failsafechecked);
       $failsafesty = 'none';
       %failsafechecked = (
           off => ' checked="checked"',
       );
     if (ref($settings) eq 'HASH') {      if (ref($settings) eq 'HASH') {
         if (exists($settings->{'run'})) {          if (exists($settings->{'run'})) {
             if ($settings->{'run'} eq '0') {              if ($settings->{'run'} eq '0') {
Line 2547  sub print_autoenroll { Line 3485  sub print_autoenroll {
         if (exists($settings->{'sender_domain'})) {          if (exists($settings->{'sender_domain'})) {
             $defdom = $settings->{'sender_domain'};              $defdom = $settings->{'sender_domain'};
         }          }
         if (exists($settings->{'autofailsafe'})) {          if (exists($settings->{'failsafe'})) {
             $failsafe = $settings->{'autofailsafe'};              $failsafe = $settings->{'failsafe'};
               if ($failsafe eq 'zero') {
                   $failsafechecked{'zero'} = ' checked="checked"';
                   $failsafechecked{'off'} = '';
                   $failsafesty = 'inline-block';
               } elsif ($failsafe eq 'any') {
                   $failsafechecked{'any'} = ' checked="checked"';
                   $failsafechecked{'off'} = '';
               }
               $autofailsafe = $settings->{'autofailsafe'};
           } elsif (exists($settings->{'autofailsafe'})) {
               $autofailsafe = $settings->{'autofailsafe'};
               if ($autofailsafe ne '') {
                   $failsafechecked{'zero'} = ' checked="checked"';
                   $failsafe = 'zero';
                   $failsafechecked{'off'} = '';
               }
         }          }
     } else {      } else {
         if ($autorun) {          if ($autorun) {
Line 2587  sub print_autoenroll { Line 3541  sub print_autoenroll {
                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.                    $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
                   '</tr><tr>'.                    '</tr><tr>'.
                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.                    '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
                   '<td class="LC_right_item"><span class="LC_nobreak">'.                    '<td class="LC_left_item"><span class="LC_nobreak">'.
                   '<input type="text" name="autoenroll_failsafe"'.                    '<span class="LC_nobreak"><label><input type="radio" name="autoenroll_failsafe" value="off" onclick="toggleFailsafe(this.form)"'.$failsafechecked{'off'}.' />'.&mt('Not in use').'</label></span>&nbsp;&nbsp;&nbsp; '.
                   ' value="'.$failsafe.'" size="4" /></span></td></tr>';                    '<span class="LC_nobreak"><label><input type="radio" name="autoenroll_failsafe" value="zero" onclick="toggleFailsafe(this.form)"'.$failsafechecked{'zero'}.' />'.&mt('Retrieved section enrollment is zero').'</label></span><br />'.
                     '<span class="LC_nobreak"><label><input type="radio" name="autoenroll_failsafe" value="any" onclick="toggleFailsafe(this.form)"'.$failsafechecked{'any'}.' />'.&mt('Retrieved section enrollment is zero or greater').'</label></span>'.
                     '<div class="LC_floatleft" style="display:'.$failsafesty.';" id="autoenroll_failsafe_div">'.
                     '<span class="LC_nobreak">'.
                     &mt('Threshold for number of students in section to drop: [_1]',
                         '<input type="text" name="autoenroll_autofailsafe" value="'.$autofailsafe.'" size="4" />').
                     '</span></div></td></tr>';
     $$rowtotal += 4;      $$rowtotal += 4;
     return $datatable;      return $datatable;
 }  }
   
 sub print_autoupdate {  sub print_autoupdate {
     my ($position,$dom,$settings,$rowtotal) = @_;      my ($position,$dom,$settings,$rowtotal) = @_;
     my $datatable;      my ($enable,$datatable);
     if ($position eq 'top') {      if ($position eq 'top') {
           my %choices = &Apache::lonlocal::texthash (
                             run        => 'Auto-update active?',
                             classlists => 'Update information in classlists?',
                             unexpired  => 'Skip updates for users without active or future roles?',
                             lastactive => 'Skip updates for inactive users?',
           );
           my $itemcount = 0;
         my $updateon = ' ';          my $updateon = ' ';
         my $updateoff = ' checked="checked" ';          my $updateoff = ' checked="checked" ';
         my $classlistson = ' ';  
         my $classlistsoff = ' checked="checked" ';  
         if (ref($settings) eq 'HASH') {          if (ref($settings) eq 'HASH') {
             if ($settings->{'run'} eq '1') {              if ($settings->{'run'} eq '1') {
                 $updateon = $updateoff;                  $updateon = $updateoff;
                 $updateoff = ' ';                  $updateoff = ' ';
             }              }
             if ($settings->{'classlists'} eq '1') {  
                 $classlistson = $classlistsoff;  
                 $classlistsoff = ' ';  
             }  
         }          }
         my %title = (          $enable = '<tr class="LC_odd_row">'. 
                    run => 'Auto-update active?',                    '<td>'.&mt($choices{'run'}).'</td>'.
                    classlists => 'Update information in classlists?',                    '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
                     );  
         $datatable = '<tr class="LC_odd_row">'.   
                   '<td>'.&mt($title{'run'}).'</td>'.  
                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.  
                   '<input type="radio" name="autoupdate_run"'.                    '<input type="radio" name="autoupdate_run"'.
                   $updateon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.                    $updateoff.'value="0" />'.&mt('No').'</label>&nbsp;'.
                   '<label><input type="radio" name="autoupdate_run"'.                    '<label><input type="radio" name="autoupdate_run"'.
                   $updateoff.'value="0" />'.&mt('No').'</label></span></td>'.                    $updateon.'value="1" />'.&mt('Yes').'</label></span></td>'.
                   '</tr><tr>'.  
                   '<td>'.&mt($title{'classlists'}).'</td>'.  
                   '<td class="LC_right_item"><span class="LC_nobreak">'.  
                   '<label><input type="radio" name="classlists"'.  
                   $classlistson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.  
                   '<label><input type="radio" name="classlists"'.  
                   $classlistsoff.'value="0" />'.&mt('No').'</label></span></td>'.  
                   '</tr>';                    '</tr>';
         $$rowtotal += 2;          my @toggles = ('classlists','unexpired');
           my %defaultchecked = ('classlists' => 'off',
                                 'unexpired'  => 'off'
                                 );
           $$rowtotal ++;
           ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
                                                        \%choices,$itemcount,'','','left','no');
           $datatable = $enable.$datatable;
           $$rowtotal += $itemcount;
           my $lastactiveon = ' ';
           my $lastactiveoff = ' checked="checked" ';
           my $lastactivestyle = 'none';
           my $lastactivedays;
           my $onclick = ' onclick="javascript:toggleLastActiveDays(this.form);"';
           if (ref($settings) eq 'HASH') {
               if ($settings->{'lastactive'} =~ /^\d+$/) {
                   $lastactiveon = $lastactiveoff;
                   $lastactiveoff = ' ';
                   $lastactivestyle = 'inline-block';
                   $lastactivedays = $settings->{'lastactive'};
               }
           }
           my $css_class = $itemcount%2?' class="LC_odd_row"':'';
           $datatable .= '<tr'.$css_class.'>'.
                         '<td>'.$choices{'lastactive'}.'</td>'.
                         '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
                         '<input type="radio" name="lastactive"'.
                         $lastactiveoff.'value="0"'.$onclick.' />'.&mt('No').'</label>'.
                         '&nbsp;<label>'.
                         '<input type="radio" name="lastactive"'.
                         $lastactiveon.' value="1"'.$onclick.' />'.&mt('Yes').'</label>'.
                         '<div id="lastactive_div" style="display:'.$lastactivestyle.';">'.
                         ':&nbsp;'.&mt('inactive = no activity in last [_1] days',
                             '<input type="text" size="5" name="lastactivedays" value="'.
                             $lastactivedays.'" />').
                         '</span></td>'.
                         '</tr>';
           $$rowtotal ++;
     } elsif ($position eq 'middle') {      } elsif ($position eq 'middle') {
         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);          my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
         my $numinrow = 3;          my $numinrow = 3;
Line 3760  sub helpdeskroles_access { Line 4747  sub helpdeskroles_access {
   
 sub radiobutton_prefs {  sub radiobutton_prefs {
     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,      my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
         $additional,$align) = @_;          $additional,$align,$firstval) = @_;
     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&      return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
                    (ref($choices) eq 'HASH'));                     (ref($choices) eq 'HASH'));
   
Line 3800  sub radiobutton_prefs { Line 4787  sub radiobutton_prefs {
         } else {          } else {
             $datatable .= '<td class="LC_right_item">';              $datatable .= '<td class="LC_right_item">';
         }          }
         $datatable .=          $datatable .= '<span class="LC_nobreak">';
             '<span class="LC_nobreak">'.          if ($firstval eq 'no') {
               $datatable .=
                   '<label><input type="radio" name="'.
                   $item.'" '.$checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').
                   '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
                   $checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').'</label>';
           } else {
               $datatable .=
             '<label><input type="radio" name="'.              '<label><input type="radio" name="'.
             $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').              $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
             '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.              '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
             $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>'.              $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>';
             '</span>'.$additional.          }
             '</td>'.          $datatable .= '</span>'.$additional.'</td></tr>';
             '</tr>';  
         $itemcount ++;          $itemcount ++;
     }      }
     return ($datatable,$itemcount);      return ($datatable,$itemcount);
 }  }
   
   sub print_ltitools {
       my ($dom,$settings,$rowtotal) = @_;
       my $rownum = 0;
       my $css_class;
       my $itemcount = 1;
       my $maxnum = 0;
       my %ordered;
       if (ref($settings) eq 'HASH') {
           foreach my $item (keys(%{$settings})) {
               if (ref($settings->{$item}) eq 'HASH') {
                   my $num = $settings->{$item}{'order'};
                   $ordered{$num} = $item;
               }
           }
       }
       my $confname = $dom.'-domainconfig';
       my $switchserver = &check_switchserver($dom,$confname);
       my $maxnum = scalar(keys(%ordered));
       my $datatable;
       my %lt = &ltitools_names();
       my @courseroles = ('cc','in','ta','ep','st');
       my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
       my @fields = ('fullname','firstname','lastname','email','roles','user');
       if (keys(%ordered)) {
           my @items = sort { $a <=> $b } keys(%ordered);
           for (my $i=0; $i<@items; $i++) {
               $css_class = $itemcount%2?' class="LC_odd_row"':'';
               my $item = $ordered{$items[$i]};
               my ($title,$key,$secret,$url,$lifetime,$imgsrc,%sigsel);
               if (ref($settings->{$item}) eq 'HASH') {
                   $title = $settings->{$item}->{'title'};
                   $url = $settings->{$item}->{'url'};
                   $key = $settings->{$item}->{'key'};
                   $secret = $settings->{$item}->{'secret'};
                   $lifetime = $settings->{$item}->{'lifetime'};
                   my $image = $settings->{$item}->{'image'};
                   if ($image ne '') {
                       $imgsrc = '<img src="'.$image.'" alt="'.&mt('Tool Provider icon').'" />';
                   }
                   if ($settings->{$item}->{'sigmethod'} eq 'HMAC-256') {
                       $sigsel{'HMAC-256'} = ' selected="selected"';
                   } else {
                       $sigsel{'HMAC-SHA1'} = ' selected="selected"';
                   }
               }
               my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_".$item."'".');"';
               $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
                            .'<select name="ltitools_'.$item.'"'.$chgstr.'>';
               for (my $k=0; $k<=$maxnum; $k++) {
                   my $vpos = $k+1;
                   my $selstr;
                   if ($k == $i) {
                       $selstr = ' selected="selected" ';
                   }
                   $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
               }
               $datatable .= '</select>'.('&nbsp;'x2).
                   '<label><input type="checkbox" name="ltitools_del" value="'.$item.'" />'.
                   &mt('Delete?').'</label></span></td>'.
                   '<td colspan="2">'.
                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
                   '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_title_'.$i.'" value="'.$title.'" /></span> '.
                   ('&nbsp;'x2).
                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_version_'.$i.'">'.
                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
                   ('&nbsp;'x2).
                   '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_msgtype_'.$i.'">'.
                   '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
                   ('&nbsp;'x2).
                   '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_sigmethod_'.$i.'">'.
                   '<option value="HMAC-SHA1"'.$sigsel{'HMAC-SHA1'}.'>HMAC-SHA1</option>'.
                   '<option value="HMAC-SHA256"'.$sigsel{'HMAC-SHA256'}.'>HMAC-SHA256</option></select></span>'.
                   '<br /><br />'.
                   '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_url_'.$i.'"'.
                   ' value="'.$url.'" /></span>'.
                   ('&nbsp;'x2).
                   '<span class="LC_nobreak">'.$lt{'key'}.':'.
                   '<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" /></span> '.
                   ('&nbsp;'x2).
                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':'.
                   '<input type="text" size="5" name="ltitools_lifetime_'.$i.'" value="'.$lifetime.'" /></span> '.
                   ('&nbsp;'x2).
                   '<span class="LC_nobreak">'.$lt{'secret'}.':'.
                   '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="'.$secret.'" />'.
                   '<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>'.
                   '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span>'.
                   '</fieldset>'.
                   '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
                   '<span class="LC_nobreak">'.&mt('Display target:');
               my %currdisp;
               if (ref($settings->{$item}->{'display'}) eq 'HASH') {
                   if ($settings->{$item}->{'display'}->{'target'} eq 'window') {
                       $currdisp{'window'} = ' checked="checked"';
                   } elsif ($settings->{$item}->{'display'}->{'target'} eq 'tab') {
                       $currdisp{'tab'} = ' checked="checked"';
                   } else {
                       $currdisp{'iframe'} = ' checked="checked"';
                   }
                   if ($settings->{$item}->{'display'}->{'width'} =~ /^(\d+)$/) {
                       $currdisp{'width'} = $1;
                   }
                   if ($settings->{$item}->{'display'}->{'height'} =~ /^(\d+)$/) {
                        $currdisp{'height'} = $1;
                   }
                   $currdisp{'linktext'} = $settings->{$item}->{'display'}->{'linktext'};
                   $currdisp{'explanation'} = $settings->{$item}->{'display'}->{'explanation'};
               } else {
                   $currdisp{'iframe'} = ' checked="checked"';
               }
               foreach my $disp ('iframe','tab','window') {
                   $datatable .= '<label><input type="radio" name="ltitools_target_'.$i.'" value="'.$disp.'"'.$currdisp{$disp}.' />'.
                                 $lt{$disp}.'</label>'.('&nbsp;'x2);
               }
               $datatable .= ('&nbsp;'x4);
               foreach my $dimen ('width','height') {
                   $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
                                 '<input type="text" name="ltitools_'.$dimen.'_'.$i.'" size="5" value="'.$currdisp{$dimen}.'" /></label>'.
                                 ('&nbsp;'x2);
               }
               $datatable .= '</span><br />'.
                             '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
                             '<input type="text" name="ltitools_linktext_'.$i.'" size="25" value="'.$currdisp{'linktext'}.'" /></div>'.
                             '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
                             '<textarea name="ltitools_explanation_'.$i.'" rows="5" cols="40">'.$currdisp{'explanation'}.
                             '</textarea></div><div style=""></div>'.
                             '<div style="padding:0;clear:both;margin:0;border:0"></div>';
               $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
               if ($imgsrc) {
                   $datatable .= $imgsrc.
                                 '<label><input type="checkbox" name="ltitools_image_del"'.
                                 ' value="'.$item.'" />'.&mt('Delete?').'</label></span> '.
                                 '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
               } else {
                   $datatable .= '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
               }
               if ($switchserver) {
                   $datatable .= &mt('Upload to library server: [_1]',$switchserver);
               } else {
                   $datatable .= '<input type="file" name="ltitools_image_'.$i.'" value="" />';
               }
               $datatable .= '</span></fieldset>';
               my (%checkedfields,%rolemaps,$userincdom);
               if (ref($settings->{$item}) eq 'HASH') {
                   if (ref($settings->{$item}->{'fields'}) eq 'HASH') {
                       %checkedfields = %{$settings->{$item}->{'fields'}};
                   }
                   $userincdom = $settings->{$item}->{'incdom'};
                   if (ref($settings->{$item}->{'roles'}) eq 'HASH') {
                       %rolemaps = %{$settings->{$item}->{'roles'}};
                       $checkedfields{'roles'} = 1;
                   }
               }
               $datatable .= '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
                             '<span class="LC_nobreak">';
               my $userfieldstyle = 'display:none;';
               my $seluserdom = '';
               my $unseluserdom = ' selected="selected"';
               foreach my $field (@fields) {
                   my ($checked,$onclick,$id,$spacer);
                   if ($checkedfields{$field}) {
                       $checked = ' checked="checked"';
                   }
                   if ($field eq 'user') {
                       $id = ' id="ltitools_user_field_'.$i.'"';
                       $onclick = ' onclick="toggleLTITools(this.form,'."'$field','$i'".')"';
                       if ($checked) {
                           $userfieldstyle = 'display:inline-block';
                           if ($userincdom) {
                               $seluserdom = $unseluserdom;
                               $unseluserdom = '';
                           }
                       }
                   } else {
                       $spacer = ('&nbsp;' x2);
                   }
                   $datatable .= '<label>'.
                                 '<input type="checkbox" name="ltitools_fields_'.$i.'" value="'.$field.'"'.$id.$checked.$onclick.' />'.
                                 $lt{$field}.'</label>'.$spacer;
               }
               $datatable .= '</span>';
               $datatable .= '<div style="'.$userfieldstyle.'" id="ltitools_user_div_'.$i.'">'.
                             '<span class="LC_nobreak"> : '.
                             '<select name="ltitools_userincdom_'.$i.'">'.
                             '<option value="">'.&mt('Select').'</option>'.
                             '<option value="0"'.$unseluserdom.'>'.&mt('username').'</option>'.
                             '<option value="1"'.$seluserdom.'>'.&mt('username:domain').'</option>'.
                             '</select></span></div>';
               $datatable .= '</fieldset>'.
                             '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
               foreach my $role (@courseroles) {
                   my ($selected,$selectnone);
                   if (!$rolemaps{$role}) {
                       $selectnone = ' selected="selected"';
                   }
                   $datatable .= '<td align="center">'.
                                 &Apache::lonnet::plaintext($role,'Course').'<br />'.
                                 '<select name="ltitools_roles_'.$role.'_'.$i.'">'.
                                 '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
                   foreach my $ltirole (@ltiroles) {
                       unless ($selectnone) {
                           if ($rolemaps{$role} eq $ltirole) {
                               $selected = ' selected="selected"';
                           } else {
                               $selected = '';
                           }
                       }
                       $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
                   }
                   $datatable .= '</select></td>';
               }
               $datatable .= '</tr></table></fieldset>';
               my %courseconfig;
               if (ref($settings->{$item}) eq 'HASH') {
                   if (ref($settings->{$item}->{'crsconf'}) eq 'HASH') {
                       %courseconfig = %{$settings->{$item}->{'crsconf'}};
                   }
               }
               $datatable .= '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
               foreach my $item ('label','title','target','linktext','explanation','append') {
                   my $checked;
                   if ($courseconfig{$item}) {
                       $checked = ' checked="checked"';
                   }
                   $datatable .= '<label>'.
                          '<input type="checkbox" name="ltitools_courseconfig_'.$i.'" value="'.$item.'"'.$checked.' />'.
                          $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
               }
               $datatable .= '</span></fieldset>'.
                             '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
                             '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>';
               if (ref($settings->{$item}->{'custom'}) eq 'HASH') {
                   my %custom = %{$settings->{$item}->{'custom'}};
                   if (keys(%custom) > 0) {
                       foreach my $key (sort(keys(%custom))) {
                           $datatable .= '<tr><td><span class="LC_nobreak">'.
                                         '<label><input type="checkbox" name="ltitools_customdel_'.$i.'" value="'.
                                         $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
                                         '<td><input type="text" name="ltitools_customval_'.$key.'_'.$i.'"'.
                                         ' value="'.$custom{$key}.'" /></td></tr>';
                       }
                   }
               }
               $datatable .= '<tr><td><span class="LC_nobreak">'.
                             '<label><input type="checkbox" name="ltitools_customadd" value="'.$i.'" />'.
                             &mt('Add').'</label></span></td><td><input type="text" name="ltitools_custom_name_'.$i.'" />'.
                             '</td><td><input type="text" name="ltitools_custom_value_'.$i.'" /></td></tr>';
               $datatable .= '</table></fieldset></td></tr>'."\n";
               $itemcount ++;
           }
       }
       $css_class = $itemcount%2?' class="LC_odd_row"':'';
       my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_add_pos'".');"';
       $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
                     '<input type="hidden" name="ltitools_maxnum" value="'.$maxnum.'" />'."\n".
                     '<select name="ltitools_add_pos"'.$chgstr.'>';
       for (my $k=0; $k<$maxnum+1; $k++) {
           my $vpos = $k+1;
           my $selstr;
           if ($k == $maxnum) {
               $selstr = ' selected="selected" ';
           }
           $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
       }
       $datatable .= '</select>&nbsp;'."\n".
                     '<input type="checkbox" name="ltitools_add" value="1" />'.&mt('Add').'</span></td>'."\n".
                     '<td colspan="2">'.
                     '<fieldset><legend>'.&mt('Required settings').'</legend>'.
                     '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_add_title" value="" /></span> '."\n".
                     ('&nbsp;'x2).
                     '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_add_version">'.
                     '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
                     ('&nbsp;'x2).
                     '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_add_msgtype">'.
                     '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
                     '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_add_sigmethod">'.
                     '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
                     '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
                     '<br />'.
                     '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_add_url" value="" /></span> '."\n".
                     ('&nbsp;'x2).
                     '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="ltitools_add_key" value="" /></span> '."\n".
                     ('&nbsp;'x2).
                     '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="ltitools_add_lifetime" value="300" /></span> '."\n".
                     ('&nbsp;'x2).
                     '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="ltitools_add_secret" value="" />'.
                     '<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".
                     '</fieldset>'.
                     '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
                     '<span class="LC_nobreak">'.&mt('Display target:');
       my %defaultdisp;
       $defaultdisp{'iframe'} = ' checked="checked"';
       foreach my $disp ('iframe','tab','window') {
           $datatable .= '<label><input type="radio" name="ltitools_add_target" value="'.$disp.'"'.$defaultdisp{$disp}.' />'.
                         $lt{$disp}.'</label>'.('&nbsp;'x2);
       }
       $datatable .= ('&nbsp;'x4);
       foreach my $dimen ('width','height') {
           $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
                         '<input type="text" name="ltitools_add_'.$dimen.'" size="5" /></label>'.
                         ('&nbsp;'x2);
       }
       $datatable .= '</span><br />'.
                     '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
                     '<input type="text" name="ltitools_add_linktext" size="5" /></div>'.
                     '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
                     '<textarea name="ltitools_add_explanation" rows="5" cols="40"></textarea>'.
                     '</div><div style=""></div>'.
                     '<div style="padding:0;clear:both;margin:0;border:0"></div>';
       $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;'.
                     '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
       if ($switchserver) {
           $datatable .= &mt('Upload to library server: [_1]',$switchserver);
       } else {
           $datatable .= '<input type="file" name="ltitools_add_image" value="" />';
       }
       $datatable .= '</span></fieldset>'.
                     '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
                     '<span class="LC_nobreak">';
       foreach my $field (@fields) {
           my ($id,$onclick,$spacer);
           if ($field eq 'user') {
               $id = ' id="ltitools_user_field_add"';
               $onclick = ' onclick="toggleLTITools(this.form,'."'$field','add'".')"';
           } else {
               $spacer = ('&nbsp;' x2);
           }
           $datatable .= '<label>'.
                         '<input type="checkbox" name="ltitools_add_fields" value="'.$field.'"'.$id.$onclick.' />'.
                         $lt{$field}.'</label>'.$spacer;
       }
       $datatable .= '</span>'.
                     '<div style="display:none;" id="ltitools_user_div_add">'.
                     '<span class="LC_nobreak"> : '.
                     '<select name="ltitools_userincdom_add">'.
                     '<option value="" selected="selected">'.&mt('Select').'</option>'.
                     '<option value="0">'.&mt('username').'</option>'.
                     '<option value="1">'.&mt('username:domain').'</option>'.
                     '</select></span></div></fieldset>';
       $datatable .= '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
       foreach my $role (@courseroles) {
           my ($checked,$checkednone);
           $datatable .= '<td align="center">'.
                         &Apache::lonnet::plaintext($role,'Course').'<br />'.
                         '<select name="ltitools_add_roles_'.$role.'">'.
                         '<option value="" selected="selected">'.&mt('Select').'</option>';
           foreach my $ltirole (@ltiroles) {
               $datatable .= '<option value="'.$ltirole.'">'.$ltirole.'</option>';
           }
           $datatable .= '</select></td>';
       }
       $datatable .= '</tr></table></fieldset>'.
                     '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
       foreach my $item ('label','title','target','linktext','explanation','append') {
           $datatable .= '<label>'.
                         '<input type="checkbox" name="ltitools_courseconfig" value="'.$item.'" checked="checked" />'.
                         $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
       }
       $datatable .= '</span></fieldset>'.
                     '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
                     '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
                     '<tr><td><span class="LC_nobreak">'.
                     '<label><input type="checkbox" name="ltitools_add_custom" value="1" />'.
                     &mt('Add').'</label></span></td><td><input type="text" name="ltitools_add_custom_name" />'.
                     '</td><td><input type="text" name="ltitools_add_custom_value" /></td></tr>'.
                     '</table></fieldset>'."\n".
                     '</td>'."\n".
                     '</tr>'."\n";
       $itemcount ++;
       return $datatable;
   }
   
   sub ltitools_names {
       my %lt = &Apache::lonlocal::texthash(
                                             'title'          => 'Title',
                                             'version'        => 'Version',
                                             'msgtype'        => 'Message Type',
                                             'sigmethod'      => 'Signature Method',
                                             'url'            => 'URL',
                                             'key'            => 'Key',
                                             'lifetime'       => 'Nonce lifetime (s)',
                                             'secret'         => 'Secret',
                                             'icon'           => 'Icon',
                                             'user'           => 'User',
                                             'fullname'       => 'Full Name',
                                             'firstname'      => 'First Name',
                                             'lastname'       => 'Last Name',
                                             'email'          => 'E-mail',
                                             'roles'          => 'Role',
                                             'window'         => 'Window',
                                             'tab'            => 'Tab',
                                             'iframe'         => 'iFrame',
                                             'height'         => 'Height',
                                             'width'          => 'Width',
                                             'linktext'       => 'Default Link Text',
                                             'explanation'    => 'Default Explanation',
                                             'crstarget'      => 'Display target',
                                             'crslabel'       => 'Course label',
                                             'crstitle'       => 'Course title',
                                             'crslinktext'    => 'Link Text',
                                             'crsexplanation' => 'Explanation',
                                             'crsappend'      => 'Provider URL',
                                           );
   
       return %lt;
   }
   
   sub print_lti {
       my ($position,$dom,$settings,$rowtotal) = @_;
       my $itemcount = 1;
       my ($datatable,$css_class);
       my (%rules,%encrypt,%privkeys,%linkprot);
       if (ref($settings) eq 'HASH') {
           if ($position eq 'top') {
               if (exists($settings->{'encrypt'})) {
                   if (ref($settings->{'encrypt'}) eq 'HASH') {
                       foreach my $key (keys(%{$settings->{'encrypt'}})) {
                           $encrypt{'ltisec_'.$key.'linkprot'} = $settings->{'encrypt'}{$key};
                       }
                   }
               }
               if (exists($settings->{'private'})) {
                   if (ref($settings->{'private'}) eq 'HASH') {
                       if (ref($settings->{'private'}) eq 'HASH') {
                           if (ref($settings->{'private'}{'keys'}) eq 'ARRAY') {
                               map { $privkeys{$_} = 1; } (@{$settings->{'private'}{'keys'}});
                           }
                       }
                   }
               }
           } elsif ($position eq 'middle') {
               if (exists($settings->{'rules'})) {
                   if (ref($settings->{'rules'}) eq 'HASH') {
                       %rules = %{$settings->{'rules'}};
                   }
               }
           } elsif ($position eq 'bottom') {
               if (exists($settings->{'linkprot'})) {
                   if (ref($settings->{'linkprot'}) eq 'HASH') {
                       %linkprot = %{$settings->{'linkprot'}};
                       if ($linkprot{'lock'}) {
                           delete($linkprot{'lock'});
                       }
                   }
               }
           }
       }
       if ($position eq 'top') {
           my @ids=&Apache::lonnet::current_machine_ids();
           my %servers = &Apache::lonnet::get_servers($dom,'library');
           my $primary = &Apache::lonnet::domain($dom,'primary');
           my ($extra,$numshown);
           foreach my $hostid (sort(keys(%servers))) {
               my ($showextra,$divsty,$switch);
               if ($hostid eq $primary) {
                   if ($encrypt{'ltisec_domlinkprot'}) {
                       $showextra = 1;
                   }
               }
               if ($encrypt{'ltisec_crslinkprot'}) {
                   $showextra = 1;
               }
               unless (grep(/^\Q$hostid\E$/,@ids)) {
                   $switch = 1;
               }
               if ($showextra) {
                   $numshown ++;
                   $divsty = 'display:inline-block';
               } else {
                   $divsty = 'display:none';
               }
               $extra .= '<fieldset id="ltisec_info_'.$hostid.'" style="'.$divsty.'">'.
                         '<legend>'.$hostid.'</legend>';
               if ($switch) {
                   my $switchserver = '<a href="/adm/switchserver?otherserver='.$hostid.'&amp;role='.
                                      &HTML::Entities::encode($env{'request.role'},'\'<>"&').
                                      '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
                   if (exists($privkeys{$hostid})) {
                       $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" />'.
                                 '<span class="LC_nobreak">'.
                                 &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
                                 '<span class="LC_nobreak">'.&mt('Change?').
                                 '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
                                 ('&nbsp;'x2).
                                 '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
                                 '</label>&nbsp;&nbsp;</span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
                                 '<span class="LC_nobreak"> - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
                                 '</span></div>';
                   } else {
                       $extra .= '<span class="LC_nobreak">'.
                                 &mt('Key required').' - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
                                 '</span>'."\n";
                   }
               } elsif (exists($privkeys{$hostid})) {
                   $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" /><span class="LC_nobreak">'.
                             &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
                             '<span class="LC_nobreak">'.&mt('Change?').
                             '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
                             ('&nbsp;'x2).
                             '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
                             '</label>&nbsp;&nbsp;</span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
                             '<span class="LC_nobreak">'.&mt('New Key').':'.
                             '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="off" />'.
                             '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltisec_privkey_'.$hostid.'.type='."'text'".' } else { this.form.ltisec_privkey_'.$hostid.'.type='."'password'".' }" />'.&mt('Visible input').'</label>'.
                             '</span></div>';
               } else {
                   $extra .= '<span class="LC_nobreak">'.&mt('Encryption Key').':'.
                             '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="off" />'.
                             '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltisec_privkey_'.$hostid.'.type='."'text'".' } else { this.form.ltisec_privkey_'.$hostid.'.type='."'password'".' }" />'.&mt('Visible input').'</label>';
               }
               $extra .= '</fieldset>';
           }
           my %choices = &Apache::lonlocal::texthash (
                                                         ltisec_crslinkprot => 'Encrypt stored link protection secrets defined in courses',
                                                         ltisec_domlinkprot => 'Encrypt stored link protection secrets defined in domain',
                                                     );
           my @toggles = qw(ltisec_crslinkprot ltisec_domlinkprot);
           my %defaultchecked = (
                                  'ltisec_crslinkprot' => 'off',
                                  'ltisec_domlinkprot' => 'off',
                                );
           my ($onclick,$itemcount);
           $onclick = 'javascript:toggleLTIEncKey(this.form);';
           ($datatable,$itemcount) = &radiobutton_prefs(\%encrypt,\@toggles,\%defaultchecked,
                                                        \%choices,$itemcount,$onclick,'','left','no');
   
           $css_class = $itemcount%2?' class="LC_odd_row"':'';
           my $noprivkeysty = 'display:inline-block';
           if ($numshown) {
               $noprivkeysty = 'display:none';
           }
           $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.&mt('Encryption Key(s)').'</td>'.
                         '<td><div id="ltisec_noprivkey" style="'.$noprivkeysty.'" >'.
                         '<span class="LC_nobreak">'.&mt('Not in use').'</span></div>'.
                         $extra.
                         '</td></tr>';
           $itemcount ++;
           $$rowtotal += $itemcount;
       } elsif ($position eq 'middle') {
           $datatable = &password_rules('secrets',\$itemcount,\%rules);
           $$rowtotal += $itemcount;
       } elsif ($position eq 'bottom') {
            $datatable .= &Apache::courseprefs::print_linkprotection($dom,'',$settings,$rowtotal,'','','domain');
       }
       return $datatable;
   }
   
 sub print_coursedefaults {  sub print_coursedefaults {
     my ($position,$dom,$settings,$rowtotal) = @_;      my ($position,$dom,$settings,$rowtotal) = @_;
     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);      my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
Line 3824  sub print_coursedefaults { Line 5363  sub print_coursedefaults {
         coursecredits        => 'Credits can be specified for courses',          coursecredits        => 'Credits can be specified for courses',
         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',          uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',          usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
           inline_chem          => 'Use inline previewer for chemical reaction response in place of pop-up',
         texengine            => 'Default method to display mathematics',          texengine            => 'Default method to display mathematics',
         postsubmit           => 'Disable submit button/keypress following student submission',          postsubmit           => 'Disable submit button/keypress following student submission',
         canclone             => "People who may clone a course (besides course's owner and coordinators)",          canclone             => "People who may clone a course (besides course's owner and coordinators)",
         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',          mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
     );      );
           ltiauth              => 'Student username in LTI launch of deep-linked URL can be accepted without re-authentication',
     my %staticdefaults = (      my %staticdefaults = (
                            anonsurvey_threshold => 10,                             anonsurvey_threshold => 10,
                            uploadquota          => 500,                             uploadquota          => 500,
Line 3839  sub print_coursedefaults { Line 5380  sub print_coursedefaults {
         %defaultchecked = (          %defaultchecked = (
                             'uselcmath'       => 'on',                              'uselcmath'       => 'on',
                             'usejsme'         => 'on',                              'usejsme'         => 'on',
                               'inline_chem'     => 'on',
                             'canclone'        => 'none',                              'canclone'        => 'none',
                           );                            );
         @toggles = ('uselcmath','usejsme');          @toggles = ('uselcmath','usejsme','inline_chem');
         my $deftex = $Apache::lonnet::deftex;          my $deftex = $Apache::lonnet::deftex;
         if (ref($settings) eq 'HASH') {          if (ref($settings) eq 'HASH') {
             if ($settings->{'texengine'}) {              if ($settings->{'texengine'}) {
Line 3948  sub print_coursedefaults { Line 5490  sub print_coursedefaults {
         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);          my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
         my $currusecredits = 0;          my $currusecredits = 0;
         my $postsubmitclient = 1;          my $postsubmitclient = 1;
           my $ltiauth = 0;
         my @types = ('official','unofficial','community','textbook');          my @types = ('official','unofficial','community','textbook');
         if (ref($settings) eq 'HASH') {          if (ref($settings) eq 'HASH') {
               if ($settings->{'ltiauth'}) {
                   $ltiauth = 1;
               }
             $currdefresponder = $settings->{'anonsurvey_threshold'};              $currdefresponder = $settings->{'anonsurvey_threshold'};
             if (ref($settings->{'uploadquota'}) eq 'HASH') {              if (ref($settings->{'uploadquota'}) eq 'HASH') {
                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {                  foreach my $type (keys(%{$settings->{'uploadquota'}})) {
Line 4095  sub print_coursedefaults { Line 5641  sub print_coursedefaults {
         }          }
         $datatable .= '</tr></table></td></tr>'."\n";          $datatable .= '</tr></table></td></tr>'."\n";
         $itemcount ++;          $itemcount ++;
           %defaultchecked = ('ltiauth' => 'off');
           @toggles = ('ltiauth');
           $current = {
                          'ltiauth' => $ltiauth,
                      };
           ($table,$itemcount) =
               &radiobutton_prefs($current,\@toggles,\%defaultchecked,
                                  \%choices,$itemcount,undef,undef,'left');
           $datatable .= $table;
           $itemcount ++;
     }      }
     $$rowtotal += $itemcount;      $$rowtotal += $itemcount;
     return $datatable;      return $datatable;
Line 4611  sub print_passwords { Line 6166  sub print_passwords {
             $itemcount ++;              $itemcount ++;
         }          }
     } elsif ($position eq 'lower') {      } elsif ($position eq 'lower') {
         my ($min,$max,%chars,$numsaved);          $datatable .= &password_rules('passwords',\$itemcount,$settings);
         $min = $Apache::lonnet::passwdmin;  
         if (ref($settings) eq 'HASH') {  
             if ($settings->{min}) {  
                 $min = $settings->{min};  
             }  
             if ($settings->{max}) {  
                 $max = $settings->{max};  
             }  
             if (ref($settings->{chars}) eq 'ARRAY') {  
                 map { $chars{$_} = 1; } (@{$settings->{chars}});  
             }  
             if ($settings->{numsaved}) {  
                 $numsaved = $settings->{numsaved};  
             }  
         }  
         my %rulenames = &Apache::lonlocal::texthash(  
                                                      uc => 'At least one upper case letter',  
                                                      lc => 'At least one lower case letter',  
                                                      num => 'At least one number',  
                                                      spec => 'At least one non-alphanumeric',  
                                                    );  
         $css_class = $itemcount%2?' class="LC_odd_row"':'';  
         $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.  
                       '<td class="LC_left_item"><span class="LC_nobreak">'.  
                       '<input type="text" name="passwords_min" value="'.$min.'" size="3" '.  
                       'onblur="javascript:warnIntPass(this);" />'.  
                       '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.  
                       '</span></td></tr>';  
         $itemcount ++;  
         $css_class = $itemcount%2?' class="LC_odd_row"':'';  
         $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.  
                       '<td class="LC_left_item"><span class="LC_nobreak">'.  
                       '<input type="text" name="passwords_max" value="'.$max.'" size="3" '.  
                       'onblur="javascript:warnIntPass(this);" />'.  
                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.  
                       '</span></td></tr>';  
         $itemcount ++;  
         $css_class = $itemcount%2?' class="LC_odd_row"':'';  
         $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.  
                       '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').  
                       '</span></td>';  
         my $numinrow = 2;  
         my @possrules = ('uc','lc','num','spec');  
         $datatable .= '<td class="LC_left_item"><table>';  
         for (my $i=0; $i<@possrules; $i++) {  
             my ($rem,$checked);  
             if ($chars{$possrules[$i]}) {  
                 $checked = ' checked="checked"';  
             }  
             $rem = $i%($numinrow);  
             if ($rem == 0) {  
                 if ($i > 0) {  
                     $datatable .= '</tr>';  
                 }  
                 $datatable .= '<tr>';  
             }  
             $datatable .= '<td><span class="LC_nobreak"><label>'.  
                           '<input type="checkbox" name="passwords_chars" value="'.$possrules[$i].'"'.$checked.' />'.  
                           $rulenames{$possrules[$i]}.'</label></span></td>';  
         }  
         my $rem = @possrules%($numinrow);  
         my $colsleft = $numinrow - $rem;  
         if ($colsleft > 1 ) {  
             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.  
                           '&nbsp;</td>';  
         } elsif ($colsleft == 1) {  
             $datatable .= '<td class="LC_left_item">&nbsp;</td>';  
         }  
         $datatable .='</table></td></tr>';  
         $itemcount ++;  
         $css_class = $itemcount%2?' class="LC_odd_row"':'';  
         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.  
                       '<td class="LC_left_item"><span class="LC_nobreak">'.  
                       '<input type="text" name="passwords_numsaved" value="'.$numsaved.'" size="3" '.  
                       'onblur="javascript:warnIntPass(this);" />'.  
                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.  
                       '</span></td></tr>';  
     } else {      } else {
         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);          my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
         my %ownerchg = (          my %ownerchg = (
Line 4748  sub print_passwords { Line 6226  sub print_passwords {
     return $datatable;      return $datatable;
 }  }
   
   sub password_rules {
       my ($prefix,$itemcountref,$settings) = @_;
       my ($min,$max,%chars,$numsaved,$numinrow);
       my %titles;
       if ($prefix eq 'passwords') {
           %titles = &Apache::lonlocal::texthash (
               min            => 'Minimum password length',
               max            => 'Maximum password length',
               chars          => 'Required characters',
           );
       } elsif ($prefix eq 'secrets') {
           %titles = &Apache::lonlocal::texthash (
               min            => 'Minimum secret length',
               max            => 'Maximum secret length',
               chars          => 'Required characters',
           );
       }
       $min = $Apache::lonnet::passwdmin;
       my $datatable;
       my $itemcount;
       if (ref($itemcountref)) {
           $itemcount = $$itemcountref;
       }
       if (ref($settings) eq 'HASH') {
           if ($settings->{min}) {
               $min = $settings->{min};
           }
           if ($settings->{max}) {
               $max = $settings->{max};
           }
           if (ref($settings->{chars}) eq 'ARRAY') {
               map { $chars{$_} = 1; } (@{$settings->{chars}});
           }
           if ($prefix eq 'passwords') {
               if ($settings->{numsaved}) {
                   $numsaved = $settings->{numsaved};
               }
           }
       }
       my %rulenames = &Apache::lonlocal::texthash(
                                                    uc => 'At least one upper case letter',
                                                    lc => 'At least one lower case letter',
                                                    num => 'At least one number',
                                                    spec => 'At least one non-alphanumeric',
                                                  );
       my $css_class = $itemcount%2?' class="LC_odd_row"':'';
       $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
                     '<td class="LC_left_item"><span class="LC_nobreak">'.
                     '<input type="text" name="'.$prefix.'_min" value="'.$min.'" size="3" '.
                     'onblur="javascript:warnInt'.$prefix.'(this);" />'.
                     '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
                     '</span></td></tr>';
       $itemcount ++;
       $css_class = $itemcount%2?' class="LC_odd_row"':'';
       $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
                     '<td class="LC_left_item"><span class="LC_nobreak">'.
                     '<input type="text" name="'.$prefix.'_max" value="'.$max.'" size="3" '.
                     'onblur="javascript:warnInt'.$prefix.'(this);" />'.
                     '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
                     '</span></td></tr>';
       $itemcount ++;
       $css_class = $itemcount%2?' class="LC_odd_row"':'';
       $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
                     '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
                     '</span></td>';
       my $numinrow = 2;
       my @possrules = ('uc','lc','num','spec');
       $datatable .= '<td class="LC_left_item"><table>';
       for (my $i=0; $i<@possrules; $i++) {
           my ($rem,$checked);
           if ($chars{$possrules[$i]}) {
               $checked = ' checked="checked"';
           }
           $rem = $i%($numinrow);
           if ($rem == 0) {
               if ($i > 0) {
                   $datatable .= '</tr>';
               }
               $datatable .= '<tr>';
           }
           $datatable .= '<td><span class="LC_nobreak"><label>'.
                         '<input type="checkbox" name="'.$prefix.'_chars" value="'.$possrules[$i].'"'.$checked.' />'.
                         $rulenames{$possrules[$i]}.'</label></span></td>';
       }
       my $rem = @possrules%($numinrow);
       my $colsleft = $numinrow - $rem;
       if ($colsleft > 1 ) {
           $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
                         '&nbsp;</td>';
       } elsif ($colsleft == 1) {
           $datatable .= '<td class="LC_left_item">&nbsp;</td>';
       }
       $datatable .='</table></td></tr>';
       $itemcount ++;
       if ($prefix eq 'passwords') {
           $titles{'numsaved'} = &mt('Number of previous passwords to save and disallow reuse');
           $css_class = $itemcount%2?' class="LC_odd_row"':'';
           $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
                         '<td class="LC_left_item"><span class="LC_nobreak">'.
                         '<input type="text" name="'.$prefix.'_numsaved" value="'.$numsaved.'" size="3" '.
                         'onblur="javascript:warnInt'.$prefix.'(this);" />'.
                         '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
                         '</span></td></tr>';
           $itemcount ++;
       }
       if (ref($itemcountref)) {
           $$itemcountref += $itemcount;
       }
       return $datatable;
   }
   
   sub print_wafproxy {
       my ($position,$dom,$settings,$rowtotal) = @_;
       my $css_class;
       my $itemcount = 0;
       my $datatable;
       my %servers = &Apache::lonnet::internet_dom_servers($dom);
       my (%othercontrol,%otherdoms,%aliases,%saml,%values,$setdom,$showdom);
       my %lt = &wafproxy_titles();
       foreach my $server (sort(keys(%servers))) {
           my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
           next if ($serverhome eq '');
           my $serverdom;
           if ($serverhome ne $server) {
               $serverdom = &Apache::lonnet::host_domain($serverhome);
               if (($serverdom ne '') && (&Apache::lonnet::domain($serverdom) ne '')) {
                   $othercontrol{$server} = $serverdom;
               }
           } else {
               $serverdom = &Apache::lonnet::host_domain($server);
               next if (($serverdom eq '') || (&Apache::lonnet::domain($serverdom) eq ''));
               if ($serverdom ne $dom) {
                   $othercontrol{$server} = $serverdom;
               } else {
                   $setdom = 1;
                   if (ref($settings) eq 'HASH') {
                       if (ref($settings->{'alias'}) eq 'HASH') {
                           $aliases{$dom} = $settings->{'alias'};
                           if ($aliases{$dom} ne '') {
                               $showdom = 1;
                           }
                       }
                       if (ref($settings->{'saml'}) eq 'HASH') {
                           $saml{$dom} = $settings->{'saml'};
                       }
                   }
               }
           }
       }
       if ($setdom) {
           %{$values{$dom}} = ();
           if (ref($settings) eq 'HASH') {
               foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
                   $values{$dom}{$item} = $settings->{$item};
               }
           }
       }
       if (keys(%othercontrol)) {
           %otherdoms = reverse(%othercontrol);
           foreach my $domain (keys(%otherdoms)) {
               %{$values{$domain}} = ();
               my %config = &Apache::lonnet::get_dom('configuration',['wafproxy'],$domain);
               if (ref($config{'wafproxy'}) eq 'HASH') {
                   $aliases{$domain} = $config{'wafproxy'}{'alias'};
                   if (exists($config{'wafproxy'}{'saml'})) {
                       $saml{$domain} = $config{'wafproxy'}{'saml'};
                   }
                   foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
                       $values{$domain}{$item} = $config{'wafproxy'}{$item};
                   }
               }
           }
       }
       if ($position eq 'top') {
           my %servers = &Apache::lonnet::internet_dom_servers($dom);
           my %aliasinfo;
           foreach my $server (sort(keys(%servers))) {
               $itemcount ++;
               my $dom_in_effect;
               my $aliasrows = '<tr>'.
                               '<td class="LC_left_item" style="vertical-align: baseline;">'.
                               &mt('Hostname').':&nbsp;'.
                               '<i>'.&Apache::lonnet::hostname($server).'</i></td><td>&nbsp;</td>';
               if ($othercontrol{$server}) {
                   $dom_in_effect = $othercontrol{$server};
                   my ($current,$forsaml);
                   if (ref($aliases{$dom_in_effect}) eq 'HASH') {
                       $current = $aliases{$dom_in_effect}{$server};
                   }
                   if (ref($saml{$dom_in_effect}) eq 'HASH') {
                       if ($saml{$dom_in_effect}{$server}) {
                           $forsaml = 1;
                       }
                   }
                   $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
                                 &mt('Alias').':&nbsp';
                   if ($current) {
                       $aliasrows .= $current;
                       if ($forsaml) {
                            $aliasrows .= '&nbsp;('.&mt('also for SSO Auth').')';
                       }
                   } else {
                       $aliasrows .= &mt('None');
                   }
                   $aliasrows .= '&nbsp;<span class="LC_small">('.
                                 &mt('controlled by domain: [_1]',
                                     '<b>'.$dom_in_effect.'</b>').')</span></td>';
               } else {
                   $dom_in_effect = $dom;
                   my ($current,$samlon,$samloff);
                   $samloff = ' checked="checked"';
                   if (ref($aliases{$dom}) eq 'HASH') {
                       if ($aliases{$dom}{$server}) {
                           $current = $aliases{$dom}{$server};
                       }
                   }
                   if (ref($saml{$dom}) eq 'HASH') {
                       if ($saml{$dom}{$server}) {
                           $samlon = $samloff;
                           undef($samloff);
                       }
                   }
                   $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
                                 &mt('Alias').':&nbsp;'.
                                 '<input type="text" name="wafproxy_alias_'.$server.'" '.
                                 'value="'.$current.'" size="30" />'.
                                 ('&nbsp;'x2).'<span class="LC_nobreak">'.
                                 &mt('Alias used for SSO Auth').':&nbsp;<label>'.
                                 '<input type="radio" value="0"'.$samloff.' name="wafproxy_alias_saml_'.$server.'" />'.
                                 &mt('No').'</label>&nbsp;<label>'.
                                 '<input type="radio" value="1"'.$samlon.' name="wafproxy_alias_saml_'.$server.'" />'.
                                 &mt('Yes').'</label></span>'.
                                 '</td>';
               }
               $aliasrows .= '</tr>';
               $aliasinfo{$dom_in_effect} .= $aliasrows;
           }
           if ($aliasinfo{$dom}) {
               my ($onclick,$wafon,$wafoff,$showtable);
               $onclick = ' onclick="javascript:toggleWAF();"';
               $wafoff = ' checked="checked"';
               $showtable = ' style="display:none";';
               if ($showdom) {
                   $wafon = $wafoff;
                   $wafoff = '';
                   $showtable = ' style="display:inline;"';
               }
               $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
               $datatable = '<tr'.$css_class.'>'.
                            '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
                            '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
                            '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
                            &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
                            '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
                            &mt('No').'</label></span></td>'.
                            '<td class="LC_left_item">'.
                            '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
                            '</table></td></tr>';
               $itemcount++;
           }
           if (keys(%otherdoms)) {
               foreach my $key (sort(keys(%otherdoms))) {
                   $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
                   $datatable .= '<tr'.$css_class.'>'.
                                 '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
                                 '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
                                 '</table></td></tr>';
                   $itemcount++;
               }
           }
       } else {
           my %ip_methods = &remoteip_methods();
           if ($setdom) {
               $itemcount ++;
               $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
               my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
                   $currwafvpn,$wafrangestyle,$alltossl,$ssltossl);
               $wafstyle = ' style="display:none;"';
               $nowafstyle = ' style="display:table-row;"';
               $currwafdisplay = ' style="display: none"';
               $wafrangestyle = ' style="display: none"';
               $curr_remotip = 'n';
               $ssltossl = ' checked="checked"';
               if ($showdom) {
                   $wafstyle = ' style="display:table-row;"';
                   $nowafstyle =  ' style="display:none;"';
                   if (keys(%{$values{$dom}})) {
                       if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
                           $curr_remotip = $values{$dom}{remoteip};
                       }
                       if ($curr_remotip eq 'h') {
                           $currwafdisplay = ' style="display:table-row"';
                           $wafrangestyle = ' style="display:inline-block;"';
                       }
                       if ($values{$dom}{'sslopt'}) {
                           $alltossl = ' checked="checked"';
                           $ssltossl = '';
                       }
                   }
                   if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
                       $vpndircheck = ' checked="checked"';
                       $currwafvpn = ' style="display:table-row;"';
                       $wafrangestyle = ' style="display:inline-block;"';
                   } else {
                       $vpnaliascheck = ' checked="checked"';
                       $currwafvpn = ' style="display:none;"';
                   }
               }
               $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
                             '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
                             '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
                             '</tr>'.
                             '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
                             '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
                             '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
                             &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
                             &mt('Range(s) stored in CIDR notation').'</div></td>'.
                             '<td class="LC_left_item"><table>'.
                             '<tr>'.
                             '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
                             '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
               foreach my $option ('m','h','n') {
                   my $sel;
                   if ($option eq $curr_remotip) {
                      $sel = ' selected="selected"';
                   }
                   $datatable .= '<option value="'.$option.'"'.$sel.'>'.
                                 $ip_methods{$option}.'</option>';
               }
               $datatable .= '</select></td></tr>'."\n".
                             '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
                             $lt{'ipheader'}.':&nbsp;'.
                             '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
                             'name="wafproxy_ipheader" />'.
                             '</td></tr>'."\n".
                             '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
                             $lt{'trusted'}.':<br />'.
                             '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
                             $values{$dom}{'trusted'}.'</textarea>'.
                             '</td></tr>'."\n".
                             '<tr><td><hr /></td></tr>'."\n".
                             '<tr>'.
                             '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
                             '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
                             $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
                             '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
                             $lt{'vpnaliased'}.'</label></span></td></tr>';
               foreach my $item ('vpnint','vpnext') {
                   $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
                                 '<td valign="top">'.$lt{$item}.':<br />'.
                                 '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
                                 $values{$dom}{$item}.'</textarea>'.
                                 '</td></tr>'."\n";
               }
               $datatable .= '<tr><td><hr /></td></tr>'."\n".
                             '<tr>'.
                             '<td valign="top">'.$lt{'sslopt'}.':<br /><span class="LC_nobreak">'.
                             '<label><input type="radio" name="wafproxy_sslopt"'.$alltossl.' value="1" />'.
                             $lt{'alltossl'}.'</label>'.('&nbsp;'x2).
                             '<label><input type="radio" name="wafproxy_sslopt"'.$ssltossl.' value="0" />'.
                             $lt{'ssltossl'}.'</label></span></td></tr>'."\n".
                             '</table></td></tr>';
           }
           if (keys(%otherdoms)) {
               foreach my $domain (sort(keys(%otherdoms))) {
                   $itemcount ++;
                   $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
                   $datatable .= '<tr'.$css_class.'>'.
                                 '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$domain.'</b>').'</td>'.
                                 '<td class="LC_left_item"><table>';
                   foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
                       my $showval = &mt('None');
                       if ($item eq 'ssl') {
                           $showval = $lt{'ssltossl'};
                       }
                       if ($values{$domain}{$item}) {
                           $showval = $values{$domain}{$item};
                           if ($item eq 'ssl') {
                               $showval = $lt{'alltossl'};
                           } elsif ($item eq 'remoteip') {
                               $showval = $ip_methods{$values{$domain}{$item}};
                           }
                       }
                       $datatable .= '<tr>'.
                                     '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
                   }
                   $datatable .= '</table></td></tr>';
               }
           }
       }
       $$rowtotal += $itemcount;
       return $datatable;
   }
   
   sub wafproxy_titles {
       return &Apache::lonlocal::texthash(
                  remoteip   => "Method for determining user's IP",
                  ipheader   => 'Request header containing remote IP',
                  trusted    => 'Trusted IP range(s)',
                  vpnaccess  => 'Access from institutional VPN',
                  vpndirect  => 'via regular hostname (no WAF)',
                  vpnaliased => 'via aliased hostname (WAF)',
                  vpnint     => 'Internal IP Range(s) for VPN sessions',
                  vpnext     => 'IP Range(s) for backend WAF connections',
                  sslopt     => 'Forwarding http/https',
                  alltossl   => 'WAF forwards both http and https requests to https',
                  ssltossl   => 'WAF forwards http requests to http and https to https',
              );
   }
   
   sub remoteip_methods {
       return &Apache::lonlocal::texthash(
                 m => 'Use Apache mod_remoteip',
                 h => 'Use headers parsed by LON-CAPA',
                 n => 'Not in use',
              );
   }
   
 sub print_usersessions {  sub print_usersessions {
     my ($position,$dom,$settings,$rowtotal) = @_;      my ($position,$dom,$settings,$rowtotal) = @_;
     my ($css_class,$datatable,%checked,%choices);      my ($css_class,$datatable,%checked,%choices);
Line 7430  ENDSCRIPT Line 9326  ENDSCRIPT
 }  }
   
 sub passwords_javascript {  sub passwords_javascript {
     my %intalert = &Apache::lonlocal::texthash (      my ($prefix) = @_;
         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.',      my %intalert;
         authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',      if ($prefix eq 'passwords') {
         passmin => 'Warning: minimum password length must be a positive integer greater than 6.',          %intalert = &Apache::lonlocal::texthash (
         passmax => 'Warning: maximum password length must be a positive integer (or blank).',              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.',
         passexp => 'Warning: days before password expiration must be a positive integer (or blank).',              authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
         passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',              passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
     );              passmax => 'Warning: maximum password length must be a positive integer (or blank).',
               passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
           );
       } elsif ($prefix eq 'secrets') {
           %intalert = &Apache::lonlocal::texthash (
               passmin => 'Warning: minimum secret length must be a positive integer greater than 6.',
               passmax => 'Warning: maximum secret length must be a positive integer (or blank).',
           );
       }
     &js_escape(\%intalert);      &js_escape(\%intalert);
     my $defmin = $Apache::lonnet::passwdmin;      my $defmin = $Apache::lonnet::passwdmin;
     my $intauthjs = <<"ENDSCRIPT";      my $intauthjs;
       if ($prefix eq 'passwords') { $intauthjs = <<"ENDSCRIPT";
   
 function warnIntAuth(field) {  function warnIntAuth(field) {
     if (field.name == 'intauth_check') {      if (field.name == 'intauth_check') {
Line 7460  function warnIntAuth(field) { Line 9365  function warnIntAuth(field) {
     return;      return;
 }  }
   
 function warnIntPass(field) {  ENDSCRIPT
   
        }
   
        $intauthjs .= <<"ENDSCRIPT";
   
   function warnInt$prefix(field) {
     field.value.replace(/^\s+/,'');      field.value.replace(/^\s+/,'');
     field.value.replace(/\s+\$/,'');      field.value.replace(/\s+\$/,'');
     var regexdigit=/^\\d+\$/;      var regexdigit=/^\\d+\$/;
     if (field.name == 'passwords_min') {      if (field.name == '${prefix}_min') {
         if (field.value == '') {          if (field.value == '') {
             alert('$intalert{passmin}');              alert('$intalert{passmin}');
             field.value = '$defmin';              field.value = '$defmin';
Line 7484  function warnIntPass(field) { Line 9395  function warnIntPass(field) {
             field.value = '';              field.value = '';
         }          }
         if (field.value != '') {          if (field.value != '') {
             if (field.name == 'passwords_expire') {              if (!regexdigit.test(field.value)) {
                 var regexpposnum=/^\\d+(|\\.\\d*)\$/;                  if (field.name == '${prefix}_max') {
                 if (!regexpposnum.test(field.value)) {                      alert('$intalert{passmax}');
                     alert('$intalert{passexp}');  
                     field.value = '';  
                 } else {                  } else {
                     var expval = parseFloat(field.value);                      if (field.name == '${prefix}_numsaved') {
                     if (expval == 0) {                          alert('$intalert{passnum}');
                         alert('$intalert{passexp}');  
                         field.value = '';  
                     }                      }
                 }                  }
             } else {                  field.value = '';
                 if (!regexdigit.test(field.value)) {  
                     if (field.name == 'passwords_max') {  
                         alert('$intalert{passmax}');  
                     } else {  
                         if (field.name == 'passwords_numsaved') {  
                             alert('$intalert{passnum}');  
                         }  
                     }  
                     field.value = '';  
                 }  
             }              }
         }          }
     }      }
Line 8084  sub usertype_update_row { Line 9981  sub usertype_update_row {
 sub modify_login {  sub modify_login {
     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;      my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,      my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon);          %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon,
           %currsaml,%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso);
     %title = ( coursecatalog => 'Display course catalog',      %title = ( coursecatalog => 'Display course catalog',
                adminmail => 'Display administrator E-mail address',                 adminmail => 'Display administrator E-mail address',
                helpdesk  => 'Display "Contact Helpdesk" link',                 helpdesk  => 'Display "Contact Helpdesk" link',
                newuser => 'Link for visitors to create a user account',                 newuser => 'Link for visitors to create a user account',
                loginheader => 'Log-in box header');                 loginheader => 'Log-in box header',
                  saml => 'Dual SSO and non-SSO login');
     @offon = ('off','on');      @offon = ('off','on');
     if (ref($domconfig{login}) eq 'HASH') {      if (ref($domconfig{login}) eq 'HASH') {
         if (ref($domconfig{login}{loginvia}) eq 'HASH') {          if (ref($domconfig{login}{loginvia}) eq 'HASH') {
Line 8097  sub modify_login { Line 9996  sub modify_login {
                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};                  $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
             }              }
         }          }
           if (ref($domconfig{login}{'saml'}) eq 'HASH') {
               foreach my $lonhost (keys(%{$domconfig{login}{'saml'}})) {
                   if (ref($domconfig{login}{'saml'}{$lonhost}) eq 'HASH') {
                       $currsaml{$lonhost} = $domconfig{login}{'saml'}{$lonhost};
                       $saml{$lonhost} = 1;
                       $samltext{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'text'};
                       $samlurl{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'url'};
                       $samlalt{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'alt'};
                       $samlimg{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'img'};
                       $samltitle{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'title'};
                       $samlnotsso{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'notsso'};
                   }
               }
           }
     }      }
     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],      ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
                                            \%domconfig,\%loginhash);                                             \%domconfig,\%loginhash);
Line 8343  sub modify_login { Line 10256  sub modify_login {
             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';              $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
         }          }
     }      }
       my @delsamlimg = &Apache::loncommon::get_env_multiple('form.saml_img_del');
       my @newsamlimgs;
       foreach my $lonhost (keys(%domservers)) {
           if ($env{'form.saml_'.$lonhost}) {
               if ($env{'form.saml_img_'.$lonhost.'.filename'}) {
                   push(@newsamlimgs,$lonhost);
               }
               foreach my $item ('text','alt','url','title','notsso') {
                   $env{'form.saml_'.$item.'_'.$lonhost} =~ s/^\s+|\s+$//g;
               }
               if ($saml{$lonhost}) {
                   if (grep(/^\Q$lonhost\E$/,@delsamlimg)) {
   #FIXME Need to obsolete published image
                       delete($currsaml{$lonhost}{'img'});
                       $changes{'saml'}{$lonhost} = 1;
                   }
                   if ($env{'form.saml_alt_'.$lonhost} ne $samlalt{$lonhost}) {
                       $changes{'saml'}{$lonhost} = 1;
                   }
                   if ($env{'form.saml_text_'.$lonhost} ne $samltext{$lonhost}) {
                       $changes{'saml'}{$lonhost} = 1;
                   }
                   if ($env{'form.saml_url_'.$lonhost} ne $samlurl{$lonhost}) {
                       $changes{'saml'}{$lonhost} = 1;
                   }
                   if ($env{'form.saml_title_'.$lonhost} ne $samltitle{$lonhost}) {
                       $changes{'saml'}{$lonhost} = 1;
                   }
                   if ($env{'form.saml_notsso_'.$lonhost} ne $samlnotsso{$lonhost}) {
                       $changes{'saml'}{$lonhost} = 1;
                   }
               } else {
                   $changes{'saml'}{$lonhost} = 1;
               }
               foreach my $item ('text','alt','url','title','notsso') {
                   $currsaml{$lonhost}{$item} = $env{'form.saml_'.$item.'_'.$lonhost};
               }
           } else {
               if ($saml{$lonhost}) {
                   $changes{'saml'}{$lonhost} = 1;
                   delete($currsaml{$lonhost});
               }
           }
       }
       foreach my $posshost (keys(%currsaml)) {
           unless (exists($domservers{$posshost})) {
               delete($currsaml{$posshost});
           }
       }
       %{$loginhash{'login'}{'saml'}} = %currsaml;
       if (@newsamlimgs) {
           my $error;
           my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
           if ($configuserok eq 'ok') {
               if ($switchserver) {
                   $error = &mt("Upload of SSO Button Image is not permitted to this server: [_1].",$switchserver);
               } elsif ($author_ok eq 'ok') {
                   foreach my $lonhost (@newsamlimgs) {
                       my $formelem = 'saml_img_'.$lonhost;
                       my ($result,$imgurl) = &publishlogo($r,'upload',$formelem,$dom,$confname,
                                                           "login/saml/$lonhost",'','',
                                                           $env{'form.saml_img_'.$lonhost.'.filename'});
                       if ($result eq 'ok') {
                           $currsaml{$lonhost}{'img'} = $imgurl;
                           $loginhash{'login'}{'saml'}{$lonhost}{'img'} = $imgurl;
                           $changes{'saml'}{$lonhost} = 1;
                       } else {
                           my $puberror = &mt("Upload of SSO button image failed for [_1] because an error occurred publishing the file in RES space. Error was: [_2].",
                                              $lonhost,$result);
                           $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
                       }
                   }
               } else {
                   $error = &mt("Upload of SSO button image 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);
               }
           } else {
               $error = &mt("Upload of SSO button image file(s) failed because a Domain Configuration user ([_1]) could not be created in domain: [_2].  Error was: [_3].",$confname,$dom,$configuserok);
           }
           if ($error) {
               &Apache::lonnet::logthis($error);
               $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
           }
       }
     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});      &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
   
     my $defaulthelpfile = '/adm/loginproblems.html';      my $defaulthelpfile = '/adm/loginproblems.html';
Line 8383  sub modify_login { Line 10379  sub modify_login {
         }          }
         if (keys(%changes) > 0 || $colchgtext) {          if (keys(%changes) > 0 || $colchgtext) {
             &Apache::loncommon::devalidate_domconfig_cache($dom);              &Apache::loncommon::devalidate_domconfig_cache($dom);
               if (exists($changes{'saml'})) {
                   my $hostid_in_use;
                   my @hosts = &Apache::lonnet::current_machine_ids();
                   if (@hosts > 1) {
                       foreach my $hostid (@hosts) {
                           if (&Apache::lonnet::host_domain($hostid) eq $dom) {
                               $hostid_in_use = $hostid;
                               last;
                           }
                       }
                   } else {
                       $hostid_in_use = $r->dir_config('lonHostID');
                   }
                   if (($hostid_in_use) &&
                       (&Apache::lonnet::host_domain($hostid_in_use) eq $dom)) {
                       &Apache::lonnet::devalidate_cache_new('samllanding',$hostid_in_use);
                   }
                   if (ref($lastactref) eq 'HASH') {
                       if (ref($changes{'saml'}) eq 'HASH') {
                           my %updates;
                           map { $updates{$_} = 1; } keys(%{$changes{'saml'}});
                           $lastactref->{'samllanding'} = \%updates;
                       }
                   }
               }
             if (ref($lastactref) eq 'HASH') {              if (ref($lastactref) eq 'HASH') {
                 $lastactref->{'domainconfig'} = 1;                  $lastactref->{'domainconfig'} = 1;
             }              }
Line 8462  sub modify_login { Line 10483  sub modify_login {
                             }                              }
                         }                          }
                     }                      }
                   } elsif ($item eq 'saml') {
                       if (ref($changes{$item}) eq 'HASH') {
                           my %notlt = (
                                          text   => 'Text for log-in by SSO',
                                          img    => 'SSO button image',
                                          alt    => 'Alt text for button image',
                                          url    => 'SSO URL',
                                          title  => 'Tooltip for SSO link',
                                          notsso => 'Text for non-SSO log-in',
                                       );
                           foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
                               if (ref($currsaml{$lonhost}) eq 'HASH') {
                                   $resulttext .= '<li>'.&mt("$title{$item} in use for [_1]","<b>$lonhost</b>").
                                                  '<ul>';
                                   foreach my $key ('text','img','alt','url','title','notsso') {
                                       if ($currsaml{$lonhost}{$key} eq '') {
                                           $resulttext .= '<li>'.&mt("$notlt{$key} not in use").'</li>';
                                       } else {
                                           my $value = "'$currsaml{$lonhost}{$key}'";
                                           if ($key eq 'img') {
                                               $value = '<img src="'.$currsaml{$lonhost}{$key}.'" />';
                                           }
                                           $resulttext .= '<li>'.&mt("$notlt{$key} set to: [_1]",
                                                                     $value).'</li>';
                                       }
                                   }
                                   $resulttext .= '</ul></li>';
                               } else {
                                   $resulttext .= '<li>'.&mt("$title{$item} not in use for [_1]",$lonhost).'</li>';
                               }
                           }
                       }
                 } elsif ($item eq 'captcha') {                  } elsif ($item eq 'captcha') {
                     if (ref($loginhash{'login'}) eq 'HASH') {                      if (ref($loginhash{'login'}) eq 'HASH') {
                         my $chgtxt;                          my $chgtxt;
Line 8564  sub color_font_choices { Line 10617  sub color_font_choices {
     return %choices;      return %choices;
 }  }
   
   sub modify_ipaccess {
       my ($dom,$lastactref,%domconfig) = @_;
       my (@allpos,%changes,%confhash,$errors,$resulttext);
       my (@items,%deletions,%itemids,@warnings);
       my ($typeorder,$types) = &commblocktype_text();
       if ($env{'form.ipaccess_add'}) {
           my $name = $env{'form.ipaccess_name_add'};
           my ($newid,$error) = &get_ipaccess_id($dom,$name);
           if ($newid) {
               $itemids{'add'} = $newid;
               push(@items,'add');
               $changes{$newid} = 1;
           } else {
               $error = &mt('Failed to acquire unique ID for new IP access control item');
               $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
           }
       }
       if (ref($domconfig{'ipaccess'}) eq 'HASH') {
           my @todelete = &Apache::loncommon::get_env_multiple('form.ipaccess_del');
           if (@todelete) {
               map { $deletions{$_} = 1; } @todelete;
           }
           my $maxnum = $env{'form.ipaccess_maxnum'};
           for (my $i=0; $i<$maxnum; $i++) {
               my $itemid = $env{'form.ipaccess_id_'.$i};
               $itemid =~ s/\D+//g;
               if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
                   if ($deletions{$itemid}) {
                       $changes{$itemid} = $domconfig{'ipaccess'}{$itemid}{'name'};
                   } else {
                       push(@items,$i);
                       $itemids{$i} = $itemid;
                   }
               }
           }
       }
       foreach my $idx (@items) {
           my $itemid = $itemids{$idx};
           next unless ($itemid);
           my %current;
           unless ($idx eq 'add') {
               if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
                   %current = %{$domconfig{'ipaccess'}{$itemid}};
               }
           }
           my $position = $env{'form.ipaccess_pos_'.$itemid};
           $position =~ s/\D+//g;
           if ($position ne '') {
               $allpos[$position] = $itemid;
           }
           my $name = $env{'form.ipaccess_name_'.$idx};
           $name =~ s/^\s+|\s+$//g;
           $confhash{$itemid}{'name'} = $name;
           my $possrange = $env{'form.ipaccess_range_'.$idx};
           $possrange =~ s/^\s+|\s+$//g;
           unless ($possrange eq '') {
               $possrange =~ s/[\r\n]+/\s/g;
               $possrange =~ s/\s*-\s*/-/g;
               $possrange =~ s/\s+/,/g;
               $possrange =~ s/,+/,/g;
               if ($possrange ne '') {
                   my (@ok,$count);
                   $count = 0;
                   foreach my $poss (split(/\,/,$possrange)) {
                       $count ++;
                       $poss = &validate_ip_pattern($poss);
                       if ($poss ne '') {
                           push(@ok,$poss);
                       }
                   }
                   my $diff = $count - scalar(@ok);
                   if ($diff) {
                       $errors .= '<li><span class="LC_error">'.
                                  &mt('[quant,_1,IP] invalid and excluded from saved value for IP range(s) for [_2]',
                                      $diff,$name).
                                  '</span></li>';
                   }
                   if (@ok) {
                       my @cidr_list;
                       foreach my $item (@ok) {
                           @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
                       }
                       $confhash{$itemid}{'ip'} = join(',',@cidr_list);
                   }
               }
           }
           foreach my $field ('name','ip') {
               unless (($idx eq 'add') || ($changes{$itemid})) {
                   if ($current{$field} ne $confhash{$itemid}{$field}) {
                       $changes{$itemid} = 1;
                       last;
                   }
               }
           }
           $confhash{$itemid}{'commblocks'} = {};
   
           my %commblocks;
           map { $commblocks{$_} = 1; } &Apache::loncommon::get_env_multiple('form.ipaccess_block_'.$idx);
           foreach my $type (@{$typeorder}) {
               if ($commblocks{$type}) {
                   $confhash{$itemid}{'commblocks'}{$type} = 'on';
               }
               unless (($idx eq 'add') || ($changes{$itemid})) {
                   if (ref($current{'commblocks'}) eq 'HASH') {
                       if ($confhash{$itemid}{'commblocks'}{$type} ne $current{'commblocks'}{$type}) {
                           $changes{$itemid} = 1;
                       }
                   } elsif ($confhash{$itemid}{'commblocks'}{$type}) {
                       $changes{$itemid} = 1;
                   }
               }
           }
           $confhash{$itemid}{'courses'} = {};
           my %crsdeletions;
           my @delcrs = &Apache::loncommon::get_env_multiple('form.ipaccess_course_delete_'.$idx);
           if (@delcrs) {
               map { $crsdeletions{$_} = 1; } @delcrs;
           }
           if (ref($current{'courses'}) eq 'HASH') {
               foreach my $cid (sort(keys(%{$current{'courses'}}))) {
                   if ($crsdeletions{$cid}) {
                       $changes{$itemid} = 1;
                   } else {
                       $confhash{$itemid}{'courses'}{$cid} = 1;
                   }
               }
           }
           $env{'form.ipaccess_cnum_'.$idx} =~ s/^\s+|\s+$//g;
           $env{'form.ipaccess_cdom_'.$idx} =~ s/^\s+|\s+$//g;
           if (($env{'form.ipaccess_cnum_'.$idx} =~ /^$match_courseid$/) &&
               ($env{'form.ipaccess_cdom_'.$idx} =~ /^$match_domain$/)) {
               if (&Apache::lonnet::homeserver($env{'form.ipaccess_cnum_'.$idx},
                                               $env{'form.ipaccess_cdom_'.$idx}) eq 'no_host') {
                   $errors .= '<li><span class="LC_error">'.
                              &mt('Invalid courseID [_1] omitted from list of allowed courses',
                                  $env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}).
                              '</span></li>';
               } else {
                   $confhash{$itemid}{'courses'}{$env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}} = 1;
                   $changes{$itemid} = 1;
               }
           }
       }
       if (@allpos > 0) {
           my $idx = 0;
           foreach my $itemid (@allpos) {
               if ($itemid ne '') {
                   $confhash{$itemid}{'order'} = $idx;
                   unless ($changes{$itemid}) {
                       if (ref($domconfig{'ipaccess'}) eq 'HASH') {
                           if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
                               if ($domconfig{'ipaccess'}{$itemid}{'order'} ne $idx) {
                                   $changes{$itemid} = 1;
                               }
                           }
                       }
                   }
                   $idx ++;
               }
           }
       }
       if (keys(%changes)) {
           my %defaultshash = (
                                 ipaccess => \%confhash,
                              );
           my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
                                                    $dom);
           if ($putresult eq 'ok') {
               my $cachetime = 1800;
               &Apache::lonnet::do_cache_new('ipaccess',$dom,\%confhash,$cachetime);
               if (ref($lastactref) eq 'HASH') {
                   $lastactref->{'ipaccess'} = 1;
               }
               $resulttext = &mt('Changes made:').'<ul>';
               my %bynum;
               foreach my $itemid (sort(keys(%changes))) {
                   if (ref($confhash{$itemid}) eq 'HASH') {
                       my $position = $confhash{$itemid}{'order'};
                       if ($position =~ /^\d+$/) {
                           $bynum{$position} = $itemid;
                       }
                   }
               }
               if (keys(%deletions)) {
                   foreach my $itemid (sort { $a <=> $b } keys(%deletions)) {
                       $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
                   }
               }
               foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
                   my $itemid = $bynum{$pos};
                   if (ref($confhash{$itemid}) eq 'HASH') {
                       $resulttext .= '<li><b>'.$confhash{$itemid}{'name'}.'</b><ul>';
                       my $position = $pos + 1;
                       $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
                       if ($confhash{$itemid}{'ip'} eq '') {
                           $resulttext .= '<li>'.&mt('No IP Range(s) set').'</li>';
                       } else {
                           $resulttext .= '<li>'.&mt('IP Range(s): [_1]',$confhash{$itemid}{'ip'}).'</li>';
                       }
                       if (keys(%{$confhash{$itemid}{'commblocks'}})) {
                           $resulttext .= '<li>'.&mt('Functionality Blocked: [_1]',
                                                     join(', ', map { $types->{$_}; } sort(keys(%{$confhash{$itemid}{'commblocks'}})))).
                                          '</li>';
                       } else {
                           $resulttext .= '<li>'.&mt('No functionality blocked').'</li>';
                       }
                       if (keys(%{$confhash{$itemid}{'courses'}})) {
                           my @courses;
                           foreach my $cid (sort(keys(%{$confhash{$itemid}{'courses'}}))) {
                               my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
                               push(@courses,$courseinfo{'description'}.' ('.$cid.')');
                           }
                           $resulttext .= '<li>'.&mt('Courses/Communities allowed').':<ul><li>'.
                                                join('</li><li>',@courses).'</li></ul>';
                       } else {
                           $resulttext .= '<li>'.&mt('No courses allowed').'</li>';
                       }
                       $resulttext .= '</ul></li>';
                   }
               }
               $resulttext .= '</ul>';
           } else {
               $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
           }
       } else {
           $resulttext = &mt('No changes made');
       }
       if ($errors) {
           $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
                          $errors.'</ul></p>';
       }
       return $resulttext;
   }
   
   sub get_ipaccess_id {
       my ($domain,$location) = @_;
       # get lock on ipaccess db
       my $lockhash = {
                         lock => $env{'user.name'}.
                                 ':'.$env{'user.domain'},
                      };
       my $tries = 0;
       my $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
       my ($id,$error);
   
       while (($gotlock ne 'ok') && ($tries<10)) {
           $tries ++;
           sleep (0.1);
           $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
       }
       if ($gotlock eq 'ok') {
           my %currids = &Apache::lonnet::dump_dom('ipaccess',$domain);
           if ($currids{'lock'}) {
               delete($currids{'lock'});
               if (keys(%currids)) {
                   my @curr = sort { $a <=> $b } keys(%currids);
                   if ($curr[-1] =~ /^\d+$/) {
                       $id = 1 + $curr[-1];
                   }
               } else {
                   $id = 1;
               }
               if ($id) {
                   unless (&Apache::lonnet::newput_dom('ipaccess',{ $id => $location },$domain) eq 'ok') {
                       $error = 'nostore';
                   }
               } else {
                   $error = 'nonumber';
               }
           }
           my $dellockoutcome = &Apache::lonnet::del_dom('ipaccess',['lock'],$domain);
       } else {
           $error = 'nolock';
       }
       return ($id,$error);
   }
   
 sub modify_rolecolors {  sub modify_rolecolors {
     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;      my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
     my ($resulttext,%rolehash);      my ($resulttext,%rolehash);
Line 8671  sub modify_colors { Line 11001  sub modify_colors {
             $domconfig->{$role} = {};              $domconfig->{$role} = {};
         }          }
         foreach my $img (@images) {          foreach my $img (@images) {
             if (($role eq 'login') && (($img eq 'img') || ($img eq 'logo'))) {                if ($role eq 'login') {
                 if (defined($env{'form.login_showlogo_'.$img})) {                  if (($img eq 'img') || ($img eq 'logo')) {  
                     $confhash->{$role}{'showlogo'}{$img} = 1;                      if (defined($env{'form.login_showlogo_'.$img})) {
                 } else {                           $confhash->{$role}{'showlogo'}{$img} = 1;
                     $confhash->{$role}{'showlogo'}{$img} = 0;                      } else { 
                           $confhash->{$role}{'showlogo'}{$img} = 0;
                       }
                 }                  }
             }                   if ($env{'form.login_alt_'.$img} ne '') {
                       $confhash->{$role}{'alttext'}{$img} = $env{'form.login_alt_'.$img};
                   }
               }
     if ( ! $env{'form.'.$role.'_'.$img.'.filename'}       if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
  && !defined($domconfig->{$role}{$img})   && !defined($domconfig->{$role}{$img})
  && !$env{'form.'.$role.'_del_'.$img}   && !$env{'form.'.$role.'_del_'.$img}
Line 8752  sub modify_colors { Line 11087  sub modify_colors {
                             $changes{$role}{'images'}{$img} = 1;                              $changes{$role}{'images'}{$img} = 1;
                         }                           } 
                     }                      }
                     if (($role eq 'login') && (($img eq 'logo') || ($img eq 'img'))) {                      if ($role eq 'login') {
                         if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {                          if (($img eq 'logo') || ($img eq 'img')) {
                             if ($confhash->{$role}{'showlogo'}{$img} ne                               if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
                                 $domconfig->{$role}{'showlogo'}{$img}) {                                  if ($confhash->{$role}{'showlogo'}{$img} ne 
                                 $changes{$role}{'showlogo'}{$img} = 1;                                       $domconfig->{$role}{'showlogo'}{$img}) {
                                       $changes{$role}{'showlogo'}{$img} = 1; 
                                   }
                               } else {
                                   if ($confhash->{$role}{'showlogo'}{$img} == 0) {
                                       $changes{$role}{'showlogo'}{$img} = 1;
                                   }
                             }                              }
                         } else {                          }
                             if ($confhash->{$role}{'showlogo'}{$img} == 0) {                          if ($img ne 'login') {
                                 $changes{$role}{'showlogo'}{$img} = 1;                              if (ref($domconfig->{$role}{'alttext'}) eq 'HASH') {
                                   if ($confhash->{$role}{'alttext'}{$img} ne
                                       $domconfig->{$role}{'alttext'}{$img}) {
                                       $changes{$role}{'alttext'}{$img} = 1;
                                   }
                               } else {
                                   if ($confhash->{$role}{'alttext'}{$img} ne '') {
                                       $changes{$role}{'alttext'}{$img} = 1;
                                   }
                             }                              }
                         }                          }
                     }                      }
Line 8871  sub default_change_checker { Line 11220  sub default_change_checker {
             if ($confhash->{$role}{'showlogo'}{$img} == 0) {              if ($confhash->{$role}{'showlogo'}{$img} == 0) {
                 $changes->{$role}{'showlogo'}{$img} = 1;                  $changes->{$role}{'showlogo'}{$img} = 1;
             }              }
               if (ref($confhash->{$role}{'alttext'}) eq 'HASH') {
                   if ($confhash->{$role}{'alttext'}{$img} ne '') {
                       $changes->{$role}{'alttext'}{$img} = 1;
                   }
               }
         }          }
     }      }
     if ($confhash->{$role}{'font'}) {      if ($confhash->{$role}{'font'}) {
Line 8909  sub display_colorchgs { Line 11263  sub display_colorchgs {
                             } else {                              } else {
                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';                                  $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
                             }                              }
                           } elsif (($role eq 'login') && ($key eq 'alttext')) {
                               if ($confhash->{$role}{$key}{$item} ne '') {
                                   $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} set to [_1].",
                                                  $confhash->{$role}{$key}{$item}).'</li>';
                               } else {
                                   $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} deleted.").'</li>';
                               }
                         } elsif ($confhash->{$role}{$item} eq '') {                          } elsif ($confhash->{$role}{$item} eq '') {
                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';                              $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
                         } else {                          } else {
Line 10014  sub process_textbook_image { Line 12375  sub process_textbook_image {
     return ($url,$error);      return ($url,$error);
 }  }
   
   sub modify_ltitools {
       my ($r,$dom,$action,$lastactref,%domconfig) = @_;
       my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
       my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
       my $confname = $dom.'-domainconfig';
       my $servadm = $r->dir_config('lonAdmEMail');
       my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
       my (%posslti,%possfield);
       my @courseroles = ('cc','in','ta','ep','st');
       my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
       map { $posslti{$_} = 1; } @ltiroles;
       my @allfields = ('fullname','firstname','lastname','email','user','roles');
       map { $possfield{$_} = 1; } @allfields;
       my %lt = &ltitools_names();
       if ($env{'form.ltitools_add'}) {
           my $title = $env{'form.ltitools_add_title'};
           $title =~ s/(`)/'/g;
           ($newid,my $error) = &get_ltitools_id($dom,$title);
           if ($newid) {
               my $position = $env{'form.ltitools_add_pos'};
               $position =~ s/\D+//g;
               if ($position ne '') {
                   $allpos[$position] = $newid;
               }
               $changes{$newid} = 1;
               foreach my $item ('title','url','key','secret','lifetime') {
                   $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
                   if ($item eq 'lifetime') {
                       $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
                   }
                   if ($env{'form.ltitools_add_'.$item}) {
                       if (($item eq 'key') || ($item eq 'secret')) {
                           $encconfig{$newid}{$item} = $env{'form.ltitools_add_'.$item};
                       } else {
                           $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
                       }
                   }
               }
               if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
                   $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
               }
               if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
                   $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
               }
               if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
                   $confhash{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
               } else {
                   $confhash{$newid}{'sigmethod'} = 'HMAC-SHA1';
               }
               foreach my $item ('width','height','linktext','explanation') {
                   $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
                   $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
                   if (($item eq 'width') || ($item eq 'height')) {
                       if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
                           $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
                       }
                   } else {
                       if ($env{'form.ltitools_add_'.$item} ne '') {
                           $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
                       }
                   }
               }
               if ($env{'form.ltitools_add_target'} eq 'window') {
                   $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
               } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
                   $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
               } else {
                   $confhash{$newid}{'display'}{'target'} = 'iframe';
               }
               if ($env{'form.ltitools_add_image.filename'} ne '') {
                   my ($imageurl,$error) =
                       &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$newid,
                                               $configuserok,$switchserver,$author_ok);
                   if ($imageurl) {
                       $confhash{$newid}{'image'} = $imageurl;
                   }
                   if ($error) {
                       &Apache::lonnet::logthis($error);
                       $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
                   }
               }
               my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
               foreach my $field (@fields) {
                   if ($possfield{$field}) {
                       if ($field eq 'roles') {
                           foreach my $role (@courseroles) {
                               my $choice = $env{'form.ltitools_add_roles_'.$role};
                               if (($choice ne '') && ($posslti{$choice})) {
                                   $confhash{$newid}{'roles'}{$role} = $choice;
                                   if ($role eq 'cc') {
                                       $confhash{$newid}{'roles'}{'co'} = $choice;
                                   }
                               }
                           }
                       } else {
                           $confhash{$newid}{'fields'}{$field} = 1;
                       }
                   }
               }
               if (ref($confhash{$newid}{'fields'}) eq 'HASH') {
                   if ($confhash{$newid}{'fields'}{'user'}) {
                       if ($env{'form.ltitools_userincdom_add'}) {
                           $confhash{$newid}{'incdom'} = 1;
                       }
                   }
               }
               my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
               foreach my $item (@courseconfig) {
                   $confhash{$newid}{'crsconf'}{$item} = 1;
               }
               if ($env{'form.ltitools_add_custom'}) {
                   my $name = $env{'form.ltitools_add_custom_name'};
                   my $value = $env{'form.ltitools_add_custom_value'};
                   $value =~ s/(`)/'/g;
                   $name =~ s/(`)/'/g;
                   $confhash{$newid}{'custom'}{$name} = $value;
               }
           } else {
               my $error = &mt('Failed to acquire unique ID for new external tool');
               $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
           }
       }
       if (ref($domconfig{$action}) eq 'HASH') {
           my %deletions;
           my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
           if (@todelete) {
               map { $deletions{$_} = 1; } @todelete;
           }
           my %customadds;
           my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
           if (@newcustom) {
               map { $customadds{$_} = 1; } @newcustom;
           }
           my %imgdeletions;
           my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
           if (@todeleteimages) {
               map { $imgdeletions{$_} = 1; } @todeleteimages;
           }
           my $maxnum = $env{'form.ltitools_maxnum'};
           for (my $i=0; $i<=$maxnum; $i++) {
               my $itemid = $env{'form.ltitools_id_'.$i};
               $itemid =~ s/\D+//g;
               if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
                   if ($deletions{$itemid}) {
                       if ($domconfig{$action}{$itemid}{'image'}) {
                           #FIXME need to obsolete item in RES space
                       }
                       $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
                       next;
                   } else {
                       my $newpos = $env{'form.ltitools_'.$itemid};
                       $newpos =~ s/\D+//g;
                       foreach my $item ('title','url','lifetime') {
                           $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
                           if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
                               $changes{$itemid} = 1;
                           }
                       }
                       foreach my $item ('key','secret') {
                           $encconfig{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
                           if ($domconfig{$action}{$itemid}{$item} ne $encconfig{$itemid}{$item}) {
                               $changes{$itemid} = 1;
                           }
                       }
                       if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
                           $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
                       }
                       if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
                           $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
                       }
                       if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
                           $confhash{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
                       } else {
                           $confhash{$itemid}{'sigmethod'} = 'HMAC-SHA1';
                       }
                       if ($domconfig{$action}{$itemid}{'sigmethod'} eq '') {
                           if ($confhash{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
                               $changes{$itemid} = 1;
                           }
                       } elsif ($domconfig{$action}{$itemid}{'sigmethod'} ne $confhash{$itemid}{'sigmethod'}) {
                           $changes{$itemid} = 1;
                       }
                       foreach my $size ('width','height') {
                           $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
                           $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
                           if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
                               $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
                               if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
                                   if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
                                       $changes{$itemid} = 1;
                                   }
                               } else {
                                   $changes{$itemid} = 1;
                               }
                           } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
                               if ($domconfig{$action}{$itemid}{'display'}{$size} ne '') {
                                   $changes{$itemid} = 1;
                               }
                           }
                       }
                       foreach my $item ('linktext','explanation') {
                           $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
                           $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
                           if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
                               $confhash{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
                               if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
                                   if ($domconfig{$action}{$itemid}{'display'}{$item} ne $confhash{$itemid}{'display'}{$item}) {
                                       $changes{$itemid} = 1;
                                   }
                               } else {
                                   $changes{$itemid} = 1;
                               }
                           } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
                               if ($domconfig{$action}{$itemid}{'display'}{$item} ne '') {
                                   $changes{$itemid} = 1;
                               }
                           }
                       }
                       if ($env{'form.ltitools_target_'.$i} eq 'window') {
                           $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
                       } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
                           $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
                       } else {
                           $confhash{$itemid}{'display'}{'target'} = 'iframe';
                       }
                       if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
                           if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
                               $changes{$itemid} = 1;
                           }
                       } else {
                           $changes{$itemid} = 1;
                       }
                       my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
                       foreach my $item ('label','title','target','linktext','explanation','append') {
                           if (grep(/^\Q$item\E$/,@courseconfig)) {
                               $confhash{$itemid}{'crsconf'}{$item} = 1;
                               if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
                                   if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
                                       $changes{$itemid} = 1;
                                   }
                               } else {
                                   $changes{$itemid} = 1;
                               }
                           }
                       }
                       my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
                       foreach my $field (@fields) {
                           if ($possfield{$field}) {
                               if ($field eq 'roles') {
                                   foreach my $role (@courseroles) {
                                       my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
                                       if (($choice ne '') && ($posslti{$choice})) {
                                           $confhash{$itemid}{'roles'}{$role} = $choice;
                                           if ($role eq 'cc') {
                                               $confhash{$itemid}{'roles'}{'co'} = $choice;
                                           }
                                       }
                                       if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
                                           if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
                                               $changes{$itemid} = 1;
                                           }
                                       } elsif ($confhash{$itemid}{'roles'}{$role}) {
                                           $changes{$itemid} = 1;
                                       }
                                   }
                               } else {
                                   $confhash{$itemid}{'fields'}{$field} = 1;
                                   if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
                                       if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
                                           $changes{$itemid} = 1;
                                       }
                                   } else {
                                       $changes{$itemid} = 1;
                                   }
                               }
                           }
                       }
                       if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
                           if ($confhash{$itemid}{'fields'}{'user'}) {
                               if ($env{'form.ltitools_userincdom_'.$i}) {
                                   $confhash{$itemid}{'incdom'} = 1;
                               }
                               if ($domconfig{$action}{$itemid}{'incdom'} ne $confhash{$itemid}{'incdom'}) {
                                   $changes{$itemid} = 1;
                               }
                           }
                       }
                       $allpos[$newpos] = $itemid;
                   }
                   if ($imgdeletions{$itemid}) {
                       $changes{$itemid} = 1;
                       #FIXME need to obsolete item in RES space
                   } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
                       my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
                                                                    $itemid,$configuserok,$switchserver,
                                                                    $author_ok);
                       if ($imgurl) {
                           $confhash{$itemid}{'image'} = $imgurl;
                           $changes{$itemid} = 1;
                       }
                       if ($error) {
                           &Apache::lonnet::logthis($error);
                           $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
                       }
                   } elsif ($domconfig{$action}{$itemid}{'image'}) {
                       $confhash{$itemid}{'image'} =
                          $domconfig{$action}{$itemid}{'image'};
                   }
                   if ($customadds{$i}) {
                       my $name = $env{'form.ltitools_custom_name_'.$i};
                       $name =~ s/(`)/'/g;
                       $name =~ s/^\s+//;
                       $name =~ s/\s+$//;
                       my $value = $env{'form.ltitools_custom_value_'.$i};
                       $value =~ s/(`)/'/g;
                       $value =~ s/^\s+//;
                       $value =~ s/\s+$//;
                       if ($name ne '') {
                           $confhash{$itemid}{'custom'}{$name} = $value;
                           $changes{$itemid} = 1;
                       }
                   }
                   my %customdels;
                   my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i);
                   if (@customdeletions) {
                       $changes{$itemid} = 1;
                   }
                   map { $customdels{$_} = 1; } @customdeletions;
                   if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
                       foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
                           unless ($customdels{$key}) {
                               if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
                                   $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i};
                               }
                               if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
                                   $changes{$itemid} = 1;
                               }
                           }
                       }
                   }
                   unless ($changes{$itemid}) {
                       foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
                           if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
                               if (ref($confhash{$itemid}{$key}) eq 'HASH') {
                                   foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
                                       unless (exists($confhash{$itemid}{$key}{$innerkey})) {
                                           $changes{$itemid} = 1;
                                           last;
                                       }
                                   }
                               } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
                                   $changes{$itemid} = 1;
                               }
                           }
                           last if ($changes{$itemid});
                       }
                   }
               }
           }
       }
       if (@allpos > 0) {
           my $idx = 0;
           foreach my $itemid (@allpos) {
               if ($itemid ne '') {
                   $confhash{$itemid}{'order'} = $idx;
                   if (ref($domconfig{$action}) eq 'HASH') {
                       if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
                           if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
                               $changes{$itemid} = 1;
                           }
                       }
                   }
                   $idx ++;
               }
           }
       }
       my %ltitoolshash = (
                             $action => { %confhash }
                          );
       my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
                                                $dom);
       if ($putresult eq 'ok') {
           my %ltienchash = (
                                $action => { %encconfig }
                            );
           &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
           if (keys(%changes) > 0) {
               my $cachetime = 24*60*60;
               my %ltiall = %confhash;
               foreach my $id (keys(%ltiall)) {
                   if (ref($encconfig{$id}) eq 'HASH') {
                       foreach my $item ('key','secret') {
                           $ltiall{$id}{$item} = $encconfig{$id}{$item};
                       }
                   }
               }
               &Apache::lonnet::do_cache_new('ltitools',$dom,\%ltiall,$cachetime);
               if (ref($lastactref) eq 'HASH') {
                   $lastactref->{'ltitools'} = 1;
               }
               $resulttext = &mt('Changes made:').'<ul>';
               my %bynum;
               foreach my $itemid (sort(keys(%changes))) {
                   my $position = $confhash{$itemid}{'order'};
                   $bynum{$position} = $itemid;
               }
               foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
                   my $itemid = $bynum{$pos};
                   if (ref($confhash{$itemid}) ne 'HASH') {
                       $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
                   } else {
                       $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
                       if ($confhash{$itemid}{'image'}) {
                           $resulttext .= '&nbsp;'.
                                          '<img src="'.$confhash{$itemid}{'image'}.'"'.
                                          ' alt="'.&mt('Tool Provider icon').'" />';
                       }
                       $resulttext .= '</li><ul>';
                       my $position = $pos + 1;
                       $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
                       foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
                           if ($confhash{$itemid}{$item} ne '') {
                               $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
                           }
                       }
                       if ($encconfig{$itemid}{'key'} ne '') {
                           $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
                       }
                       if ($encconfig{$itemid}{'secret'} ne '') {
                           $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
                           my $num = length($encconfig{$itemid}{'secret'});
                           $resulttext .= ('*'x$num).'</li>';
                       }
                       $resulttext .= '<li>'.&mt('Configurable in course:');
                       my @possconfig = ('label','title','target','linktext','explanation','append');
                       my $numconfig = 0;
                       if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') {
                           foreach my $item (@possconfig) {
                               if ($confhash{$itemid}{'crsconf'}{$item}) {
                                   $numconfig ++;
                                   $resulttext .= ' "'.$lt{'crs'.$item}.'"';
                               }
                           }
                       }
                       if (!$numconfig) {
                           $resulttext .= &mt('None');
                       }
                       $resulttext .= '</li>';
                       if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
                           my $displaylist;
                           if ($confhash{$itemid}{'display'}{'target'}) {
                               $displaylist = &mt('Display target').':&nbsp;'.
                                              $confhash{$itemid}{'display'}{'target'}.',';
                           }
                           foreach my $size ('width','height') {
                               if ($confhash{$itemid}{'display'}{$size}) {
                                   $displaylist .= ('&nbsp;'x2).$lt{$size}.':&nbsp;'.
                                                   $confhash{$itemid}{'display'}{$size}.',';
                               }
                           }
                           if ($displaylist) {
                               $displaylist =~ s/,$//;
                               $resulttext .= '<li>'.$displaylist.'</li>';
                           }
                           foreach my $item ('linktext','explanation') {
                               if ($confhash{$itemid}{'display'}{$item}) {
                                   $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{'display'}{$item}.'</li>';
                               }
                           }
                       }
                       if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
                           my $fieldlist;
                           foreach my $field (@allfields) {
                               if ($confhash{$itemid}{'fields'}{$field}) {
                                   $fieldlist .= ('&nbsp;'x2).$lt{$field}.',';
                               }
                           }
                           if ($fieldlist) {
                               $fieldlist =~ s/,$//;
                               if ($confhash{$itemid}{'fields'}{'user'}) {
                                   if ($confhash{$itemid}{'incdom'}) {
                                       $fieldlist .= ' ('.&mt('username:domain').')';
                                   } else {
                                       $fieldlist .= ' ('.&mt('username').')';
                                   }
                               }
                               $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
                           }
                       }
                       if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
                           my $rolemaps;
                           foreach my $role (@courseroles) {
                               if ($confhash{$itemid}{'roles'}{$role}) {
                                   $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
                                                $confhash{$itemid}{'roles'}{$role}.',';
                               }
                           }
                           if ($rolemaps) {
                               $rolemaps =~ s/,$//;
                               $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
                           }
                       }
                       if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
                           my $customlist;
                           if (keys(%{$confhash{$itemid}{'custom'}})) {
                               foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
                                   $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.('&nbsp;'x2);
                               }
                           }
                           if ($customlist) {
                               $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
                           }
                       }
                       $resulttext .= '</ul></li>';
                   }
               }
               $resulttext .= '</ul>';
           } else {
               $resulttext = &mt('No changes made.');
           }
       } else {
           $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
       }
       if ($errors) {
           $resulttext .= &mt('The following errors occurred: ').'<ul>'.
                          $errors.'</ul>';
       }
       return $resulttext;
   }
   
   sub process_ltitools_image {
       my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
       my $filename = $env{'form.'.$caller.'.filename'};
       my ($error,$url);
       my ($width,$height) = (21,21);
       if ($configuserok eq 'ok') {
           if ($switchserver) {
               $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
                            $switchserver);
           } elsif ($author_ok eq 'ok') {
               my ($result,$imageurl,$madethumb) =
                   &publishlogo($r,'upload',$caller,$dom,$confname,
                                "ltitools/$itemid/icon",$width,$height);
               if ($result eq 'ok') {
                   if ($madethumb) {
                       my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
                       my $imagethumb = "$path/tn-".$imagefile;
                       $url = $imagethumb;
                   } else {
                       $url = $imageurl;
                   }
               } else {
                   $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
               }
           } else {
               $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);
           }
       } else {
           $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);
       }
       return ($url,$error);
   }
   
   sub get_ltitools_id {
       my ($cdom,$title) = @_;
       # get lock on ltitools db
       my $lockhash = {
                         lock => $env{'user.name'}.
                                 ':'.$env{'user.domain'},
                      };
       my $tries = 0;
       my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
       my ($id,$error);
   
       while (($gotlock ne 'ok') && ($tries<10)) {
           $tries ++;
           sleep (0.1);
           $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
       }
       if ($gotlock eq 'ok') {
           my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
           if ($currids{'lock'}) {
               delete($currids{'lock'});
               if (keys(%currids)) {
                   my @curr = sort { $a <=> $b } keys(%currids);
                   if ($curr[-1] =~ /^\d+$/) {
                       $id = 1 + $curr[-1];
                   }
               } else {
                   $id = 1;
               }
               if ($id) {
                   unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
                       $error = 'nostore';
                   }
               } else {
                   $error = 'nonumber';
               }
           }
           my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
       } else {
           $error = 'nolock';
       }
       return ($id,$error);
   }
   
   sub modify_lti {
       my ($r,$dom,$action,$lastactref,%domconfig) = @_;
       my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
       my (%encconfig,$errors,$resulttext);
   
       my (%currltisec,%secchanges,%newltisec,%newltienc,%keyset,%newkeyset);
       $newltisec{'private'}{'keys'} = [];
       $newltisec{'encrypt'} = {};
       $newltisec{'rules'} = {};
       $newltisec{'linkprot'} = {};
       if (ref($domconfig{'ltisec'}) eq 'HASH') {
           %currltisec = %{$domconfig{'ltisec'}};
           if (ref($currltisec{'linkprot'}) eq 'HASH') {
               foreach my $id (keys(%{$currltisec{'linkprot'}})) {
                   unless ($id =~ /^\d+$/) {
                       delete($currltisec{'linkprot'}{$id});
                   }
               }
           }
           if (ref($currltisec{'private'}) eq 'HASH') {
               if (ref($currltisec{'private'}{'keys'}) eq 'ARRAY') {
                   $newltisec{'private'}{'keys'} = $currltisec{'private'}{'keys'};
                   map { $keyset{$_} = 1; } @{$currltisec{'private'}{'keys'}};
               }
           }
       }
       foreach my $item ('crs','dom') {
           my $formelement = 'form.ltisec_'.$item.'linkprot';
           if ($env{$formelement}) {
               $newltisec{'encrypt'}{$item} = 1;
               if (ref($currltisec{'encrypt'}) eq 'HASH') {
                   unless ($currltisec{'encrypt'}{$item}) {
                       $secchanges{'encrypt'} = 1;
                   }
               } else {
                   $secchanges{'encrypt'} = 1;
               }
           } elsif (ref($currltisec{'encrypt'}) eq 'HASH') {
               if ($currltisec{'encrypt'}{$item}) {
                   $secchanges{'encrypt'} = 1;
               }
           }
       }
       unless (exists($currltisec{'rules'})) {
           $currltisec{'rules'} = {};
       }
       &password_rule_changes('secrets',$newltisec{'rules'},$currltisec{'rules'},\%secchanges);
   
       my @ids=&Apache::lonnet::current_machine_ids();
       my %servers = &Apache::lonnet::get_servers($dom,'library');
   
       foreach my $hostid (keys(%servers)) {
           if (($hostid ne '') && (grep(/^\Q$hostid\E$/,@ids))) {
               my $newkey;
               my $keyitem = 'form.ltisec_privkey_'.$hostid;
               if (exists($env{$keyitem})) {
                   $env{$keyitem} =~ s/(`)/'/g;
                   if ($keyset{$hostid}) {
                       if ($env{'form.ltisec_changeprivkey_'.$hostid}) {
                           if ($env{$keyitem} ne '') {
                               $secchanges{'private'} = 1;
                               $newkeyset{$hostid} = $env{$keyitem};
                           }
                       }
                   } elsif ($env{$keyitem} ne '') {
                       unless (grep(/^\Q$hostid\E$/,@{$newltisec{'private'}{'keys'}})) {
                           push(@{$newltisec{'private'}{'keys'}},$hostid);
                       }
                       $secchanges{'private'} = 1;
                       $newkeyset{$hostid} = $env{$keyitem};
                   }
               }
           }
       }
   
       my (%linkprotchg,$linkprotoutput,$is_home);
       my $proterror = &Apache::courseprefs::process_linkprot($dom,'',$currltisec{'linkprot'},
                                                              \%linkprotchg,'domain');
       my $home = &Apache::lonnet::domain($dom,'primary');
       unless (($home eq 'no_host') || ($home eq '')) {
           my @ids=&Apache::lonnet::current_machine_ids();
           foreach my $id (@ids) { if ($id eq $home) { $is_home=1; } }
       }
   
       if (keys(%linkprotchg)) {
           $secchanges{'linkprot'} = 1;
           my %oldlinkprot;
           if (ref($currltisec{'linkprot'}) eq 'HASH') {
               %oldlinkprot = %{$currltisec{'linkprot'}};
           }
           foreach my $id (keys(%linkprotchg)) {
               if (ref($linkprotchg{$id}) eq 'HASH') {
                   foreach my $inner (keys(%{$linkprotchg{$id}})) {
                       if (($inner eq 'secret') || ($inner eq 'key')) {
                           if ($is_home) {
                               $newltienc{$id}{$inner} = $linkprotchg{$id}{$inner};
                           }
                       }
                   }
               } else {
                   $newltisec{'linkprot'}{$id} = $linkprotchg{$id};
               }
           }
           $linkprotoutput = &Apache::courseprefs::store_linkprot($dom,'','domain',\%linkprotchg,\%oldlinkprot);
           if (keys(%linkprotchg)) {
               %{$newltisec{'linkprot'}} = %linkprotchg;
           }
       }
       if (ref($currltisec{'linkprot'}) eq 'HASH') {
           foreach my $id (%{$currltisec{'linkprot'}}) {
               next if ($id !~ /^\d+$/);
               unless (exists($linkprotchg{$id})) {
                   if (ref($currltisec{'linkprot'}{$id}) eq 'HASH') {
                       foreach my $inner (keys(%{$currltisec{'linkprot'}{$id}})) {
                           if (($inner eq 'secret') || ($inner eq 'key')) {
                               if ($is_home) {
                                   $newltienc{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
                               }
                           } else {
                               $newltisec{'linkprot'}{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
                           }
                       }
                   } else {
                       $newltisec{'linkprot'}{$id} = $currltisec{'linkprot'}{$id};
                   }
               }
           }
       }
       if ($proterror) {
           $errors .= '<li>'.$proterror.'</li>';
       }
   
       my $putresult;
       if (keys(%secchanges)) {
           my %ltienchash;
           my %ltihash = (
                             'ltisec' => { %newltisec }
                         );
           $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,$dom);
           if ($putresult eq 'ok') {
               my %keystore;
               if ($secchanges{'private'}) {
                   my $who = &escape($env{'user.name'}.':'.$env{'user.domain'});
                   foreach my $hostid (keys(%newkeyset)) {
                       my $storehash = {
                                          key => $newkeyset{$hostid},
                                          who => $env{'user.name'}.':'.$env{'user.domain'},
                                       };
                       $keystore{$hostid} = &Apache::lonnet::store_dom($storehash,'lti','private',
                                                                       $dom,$hostid);
                   }
               }
               if (ref($lastactref) eq 'HASH') {
                   if (($secchanges{'encrypt'}) || ($secchanges{'private'})) {
                       $lastactref->{'domdefaults'} = 1;
                   }
               }
               if (($secchanges{'linkprot'}) && ($is_home)) {
                   my %ltienchash = (
                                        'linkprot' =>  { %newltienc }
                                    );
                   &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
               }
           }
       } else {
           return &mt('No changes made.');
       }
       if ($putresult eq 'ok') {
           $resulttext = &mt('Changes made:').'<ul>';
           foreach my $item (keys(%secchanges)) {
               if ($item eq 'encrypt') {
                   my %encrypted = (
                             crs  => {
                                       on => &mt('Encryption of stored link protection secrets defined in courses enabled'),
                                       off => &mt('Encryption of stored link protection secrets defined in courses disabled'),
                                     },
                             dom => {
                                      on => &mt('Encryption of stored link protection secrets defined in domain enabled'),
                                      off => &mt('Encryption of stored link protection secrets defined in domain disabled'),
                                    },
                   );
                   foreach my $type ('crs','dom') {
                       my $shown = $encrypted{$type}{'off'};
                       if (ref($newltisec{$item}) eq 'HASH') {
                           if ($newltisec{$item}{$type}) {
                               $shown = $encrypted{$type}{'on'};
                           }
                       }
                       $resulttext .= '<li>'.$shown.'</li>';
                   }
               } elsif ($item eq 'rules') {
                   my %titles = &Apache::lonlocal::texthash(
                                     min   => 'Minimum password length',
                                     max   => 'Maximum password length',
                                     chars => 'Required characters',
                   );
                   foreach my $rule ('min','max') {
                       if ($newltisec{rules}{$rule} eq '') {
                           if ($rule eq 'min') {
                               $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
                                              ' '.&mt('Default of [_1] will be used',
                                                          $Apache::lonnet::passwdmin).'</li>';
                           } else {
                               $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
                           }
                       } else {
                           $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$newltisec{rules}{$rule}).'</li>';
                       }
                   }
                   if (ref($newltisec{'rules'}{'chars'}) eq 'ARRAY') {
                       if (@{$newltisec{'rules'}{'chars'}} > 0) {
                           my %rulenames = &Apache::lonlocal::texthash(
                                               uc => 'At least one upper case letter',
                                               lc => 'At least one lower case letter',
                                               num => 'At least one number',
                                               spec => 'At least one non-alphanumeric',
                                               );
                           my $needed = '<ul><li>'.
                                        join('</li><li>',map {$rulenames{$_} } @{$newltisec{'rules'}{'chars'}}).
                                        '</li></ul>';
                           $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
                       } else {
                           $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
                       }
                   } else {
                       $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
                   }
               } elsif ($item eq 'private') {
                   if (keys(%newkeyset)) {
                       foreach my $hostid (sort(keys(%newkeyset))) {
                           if ($keystore{$hostid} eq 'ok') {
                               $resulttext .= '<li>'.&mt('Encryption key for storage of shared secrets saved for [_1]',$hostid).'</li>';
                           }
                       }
                   }
               } elsif ($item eq 'linkprot') {
                   $resulttext .= $linkprotoutput;
               }
           }
           $resulttext .= '</ul>';
       } else {
           $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
       }
       if ($errors) {
           $resulttext .= &mt('The following errors occurred: ').'<ul>'.
                          $errors.'</ul>';
       }
       return $resulttext;
   }
   
 sub modify_autoenroll {  sub modify_autoenroll {
     my ($dom,$lastactref,%domconfig) = @_;      my ($dom,$lastactref,%domconfig) = @_;
     my ($resulttext,%changes);      my ($resulttext,%changes);
Line 10027  sub modify_autoenroll { Line 13244  sub modify_autoenroll {
     my %title = ( run => 'Auto-enrollment active',      my %title = ( run => 'Auto-enrollment active',
                   sender => 'Sender for notification messages',                    sender => 'Sender for notification messages',
                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',                    coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
                   failsafe => 'Failsafe for no drops if institutional data missing for a section');                    autofailsafe => 'Failsafe for no drops if institutional data missing for a section');
     my @offon = ('off','on');      my @offon = ('off','on');
     my $sender_uname = $env{'form.sender_uname'};      my $sender_uname = $env{'form.sender_uname'};
     my $sender_domain = $env{'form.sender_domain'};      my $sender_domain = $env{'form.sender_domain'};
Line 10037  sub modify_autoenroll { Line 13254  sub modify_autoenroll {
         $sender_domain = '';          $sender_domain = '';
     }      }
     my $coowners = $env{'form.autoassign_coowners'};      my $coowners = $env{'form.autoassign_coowners'};
       my $autofailsafe = $env{'form.autoenroll_autofailsafe'};
       $autofailsafe =~ s{^\s+|\s+$}{}g;
       if ($autofailsafe =~ /\D/) {
           undef($autofailsafe);
       }
     my $failsafe = $env{'form.autoenroll_failsafe'};      my $failsafe = $env{'form.autoenroll_failsafe'};
     $failsafe =~ s{^\s+|\s+$}{}g;      unless (($failsafe eq 'zero') || ($failsafe eq 'any')) {
     if ($failsafe =~ /\D/) {          $failsafe = 'off';
         undef($failsafe);          undef($autofailsafe);
     }      }
     my %autoenrollhash =  (      my %autoenrollhash =  (
                        autoenroll => { 'run' => $env{'form.autoenroll_run'},                         autoenroll => { 'run' => $env{'form.autoenroll_run'},
                                        'sender_uname' => $sender_uname,                                         'sender_uname' => $sender_uname,
                                        'sender_domain' => $sender_domain,                                         'sender_domain' => $sender_domain,
                                        'co-owners' => $coowners,                                         'co-owners' => $coowners,
                                        'autofailsafe' => $failsafe,                                         'autofailsafe' => $autofailsafe,
                                          'failsafe' => $failsafe,
                                 }                                  }
                      );                       );
     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,      my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
Line 10075  sub modify_autoenroll { Line 13298  sub modify_autoenroll {
         } elsif ($coowners) {          } elsif ($coowners) {
             $changes{'coowners'} = 1;              $changes{'coowners'} = 1;
         }          }
         if ($currautoenroll{'autofailsafe'} ne $failsafe) {          if ($currautoenroll{'autofailsafe'} ne $autofailsafe) {
             $changes{'autofailsafe'} = 1;              $changes{'autofailsafe'} = 1;
         }          }
           if ($currautoenroll{'failsafe'} ne $failsafe) {
               $changes{'failsafe'} = 1;
           }
         if (keys(%changes) > 0) {          if (keys(%changes) > 0) {
             $resulttext = &mt('Changes made:').'<ul>';              $resulttext = &mt('Changes made:').'<ul>';
             if ($changes{'run'}) {              if ($changes{'run'}) {
Line 10098  sub modify_autoenroll { Line 13324  sub modify_autoenroll {
                 }                  }
             }              }
             if ($changes{'autofailsafe'}) {              if ($changes{'autofailsafe'}) {
                 if ($failsafe ne '') {                  if ($autofailsafe ne '') {
                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$failsafe).'</li>';                      $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$autofailsafe).'</li>';
                 } else {                  } else {
                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section: deleted');                      $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
                 }                  }
               }
               if ($changes{'failsafe'}) {
                   if ($failsafe eq 'off') {
                       unless ($changes{'autofailsafe'}) {
                           $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
                       }
                   } elsif ($failsafe eq 'zero') {
                       $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero').'</li>';
                   } else {
                       $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero or greater').'</li>';
                   }
               }
               if (($changes{'autofailsafe'}) || ($changes{'failsafe'})) {
                 &Apache::lonnet::get_domain_defaults($dom,1);                  &Apache::lonnet::get_domain_defaults($dom,1);
                 if (ref($lastactref) eq 'HASH') {                  if (ref($lastactref) eq 'HASH') {
                     $lastactref->{'domdefaults'} = 1;                      $lastactref->{'domdefaults'} = 1;
Line 10129  sub modify_autoupdate { Line 13368  sub modify_autoupdate {
     }      }
     my @offon = ('off','on');      my @offon = ('off','on');
     my %title = &Apache::lonlocal::texthash (      my %title = &Apache::lonlocal::texthash (
                    run => 'Auto-update:',                      run        => 'Auto-update:',
                    classlists => 'Updates to user information in classlists?'                      classlists => 'Updates to user information in classlists?',
                       unexpired  => 'Skip updates for users without active or future roles?',
                       lastactive => 'Skip updates for inactive users?',
                 );                  );
     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);      my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
     my %fieldtitles = &Apache::lonlocal::texthash (      my %fieldtitles = &Apache::lonlocal::texthash (
Line 10174  sub modify_autoupdate { Line 13415  sub modify_autoupdate {
     my %updatehash = (      my %updatehash = (
                       autoupdate => { run => $env{'form.autoupdate_run'},                        autoupdate => { run => $env{'form.autoupdate_run'},
                                       classlists => $env{'form.classlists'},                                        classlists => $env{'form.classlists'},
                                         unexpired  => $env{'form.unexpired'},
                                       fields => {%fields},                                        fields => {%fields},
                                       lockablenames => \@lockablenames,                                        lockablenames => \@lockablenames,
                                     }                                      }
                      );                       );
       my $lastactivedays;
       if ($env{'form.lastactive'}) {
           $lastactivedays = $env{'form.lastactivedays'};
           $lastactivedays =~ s/^\s+|\s+$//g;
           unless ($lastactivedays =~ /^\d+$/) {
               undef($lastactivedays);
               $env{'form.lastactive'} = 0;
           }
       }
       $updatehash{'autoupdate'}{'lastactive'} = $lastactivedays;
     foreach my $key (keys(%currautoupdate)) {      foreach my $key (keys(%currautoupdate)) {
         if (($key eq 'run') || ($key eq 'classlists')) {          if (($key eq 'run') || ($key eq 'classlists') || ($key eq 'unexpired') || ($key eq 'lastactive')) {
             if (exists($updatehash{autoupdate}{$key})) {              if (exists($updatehash{autoupdate}{$key})) {
                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {                  if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
                     $changes{$key} = 1;                      $changes{$key} = 1;
Line 10225  sub modify_autoupdate { Line 13477  sub modify_autoupdate {
             $changes{'lockablenames'} = 1;              $changes{'lockablenames'} = 1;
         }          }
     }      }
       unless (grep(/^unexpired$/,keys(%currautoupdate))) {
           if ($updatehash{'autoupdate'}{'unexpired'}) {
               $changes{'unexpired'} = 1;
           }
       }
       unless (grep(/^lastactive$/,keys(%currautoupdate))) {
           if ($updatehash{'autoupdate'}{'lastactive'} ne '') {
               $changes{'lastactive'} = 1;
           }
       }
     foreach my $item (@{$types},'default') {      foreach my $item (@{$types},'default') {
         if (defined($fields{$item})) {          if (defined($fields{$item})) {
             if (ref($currautoupdate{'fields'}) eq 'HASH') {              if (ref($currautoupdate{'fields'}) eq 'HASH') {
Line 10287  sub modify_autoupdate { Line 13549  sub modify_autoupdate {
                     my $newvalue;                      my $newvalue;
                     if ($key eq 'run') {                      if ($key eq 'run') {
                         $newvalue = $offon[$env{'form.autoupdate_run'}];                          $newvalue = $offon[$env{'form.autoupdate_run'}];
                       } elsif ($key eq 'lastactive') {
                           $newvalue = $offon[$env{'form.lastactive'}];
                           unless ($lastactivedays eq '') {
                               $newvalue .= '; '.&mt('inactive = no activity in last [quant,_1,day]',$lastactivedays);
                           }
                     } else {                      } else {
                         $newvalue = $offon[$env{'form.'.$key}];                          $newvalue = $offon[$env{'form.'.$key}];
                     }                      }
Line 11412  sub modify_passwords { Line 14679  sub modify_passwords {
             $updatedefaults = 1;              $updatedefaults = 1;
         }          }
     }      }
     foreach my $rule ('min','max','numsaved') {      &password_rule_changes('passwords',\%newvalues,\%current,\%changes);
         $env{'form.passwords_'.$rule} =~ s/^\s+|\s+$//g;  
         my $ruleok;  
         if ($rule eq 'min') {  
             if ($env{'form.passwords_'.$rule} =~ /^\d+$/) {  
                 if ($env{'form.passwords_'.$rule} >= $Apache::lonnet::passwdmin) {  
                     $ruleok = 1;  
                 }  
             }  
         } elsif (($env{'form.passwords_'.$rule} =~ /^\d+$/) &&  
                  ($env{'form.passwords_'.$rule} ne '0')) {  
             $ruleok = 1;  
         }  
         if ($ruleok) {  
             $newvalues{$rule} = $env{'form.passwords_'.$rule};  
             if (exists($current{$rule})) {  
                 if ($newvalues{$rule} ne $current{$rule}) {  
                     $changes{'rules'} = 1;  
                 }  
             } elsif ($rule eq 'min') {  
                 if ($staticdefaults{$rule} ne $newvalues{$rule}) {  
                     $changes{'rules'} = 1;  
                 }  
             } else {  
                 $changes{'rules'} = 1;  
             }  
         } elsif (exists($current{$rule})) {  
             $changes{'rules'} = 1;  
         }  
     }  
     my @posschars = &Apache::loncommon::get_env_multiple('form.passwords_chars');  
     my @chars;  
     foreach my $item (sort(@posschars)) {  
         if ($item =~ /^(uc|lc|num|spec)$/) {  
             push(@chars,$item);  
         }  
     }  
     $newvalues{'chars'} = \@chars;  
     unless ($changes{'rules'}) {  
         if (ref($current{'chars'}) eq 'ARRAY') {  
             my @diffs = &Apache::loncommon::compare_arrays($current{'chars'},\@chars);  
             if (@diffs > 0) {  
                 $changes{'rules'} = 1;  
             }  
         } else {  
             if (@chars > 0) {  
                 $changes{'rules'} = 1;  
             }  
         }  
     }  
     my %crsownerchg = (      my %crsownerchg = (
                         by => [],                          by => [],
                         for => [],                          for => [],
Line 11721  sub modify_passwords { Line 14939  sub modify_passwords {
     return $resulttext;      return $resulttext;
 }  }
   
   sub password_rule_changes {
       my ($prefix,$newvalues,$current,$changes) = @_;
       return unless ((ref($newvalues) eq 'HASH') &&
                      (ref($current) eq 'HASH') &&
                      (ref($changes) eq 'HASH'));
       my (@rules,%staticdefaults);
       if ($prefix eq 'passwords') {
           @rules = ('min','max','numsaved');
       } elsif ($prefix eq 'secrets') {
           @rules = ('min','max');
       }
       $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
       foreach my $rule (@rules) {
           $env{'form.'.$prefix.'_'.$rule} =~ s/^\s+|\s+$//g;
           my $ruleok;
           if ($rule eq 'min') {
               if ($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) {
                   if ($env{'form.'.$prefix.'_'.$rule} >= $staticdefaults{$rule}) {
                       $ruleok = 1;
                   }
               }
           } elsif (($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) &&
                    ($env{'form.'.$prefix.'_'.$rule} ne '0')) {
               $ruleok = 1;
           }
           if ($ruleok) {
               $newvalues->{$rule} = $env{'form.'.$prefix.'_'.$rule};
               if (exists($current->{$rule})) {
                   if ($newvalues->{$rule} ne $current->{$rule}) {
                       $changes->{'rules'} = 1;
                   }
               } elsif ($rule eq 'min') {
                   if ($staticdefaults{$rule} ne $newvalues->{$rule}) {
                       $changes->{'rules'} = 1;
                   }
               } else {
                   $changes->{'rules'} = 1;
               }
           } elsif (exists($current->{$rule})) {
               $changes->{'rules'} = 1;
           }
       }
       my @posschars = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_chars');
       my @chars;
       foreach my $item (sort(@posschars)) {
           if ($item =~ /^(uc|lc|num|spec)$/) {
               push(@chars,$item);
           }
       }
       $newvalues->{'chars'} = \@chars;
       unless ($changes->{'rules'}) {
           if (ref($current->{'chars'}) eq 'ARRAY') {
               my @diffs = &Apache::loncommon::compare_arrays($current->{'chars'},\@chars);
               if (@diffs > 0) {
                   $changes->{'rules'} = 1;
               }
           } else {
               if (@chars > 0) {
                   $changes->{'rules'} = 1;
               }
           }
       }
       return;
   }
   
 sub modify_usercreation {  sub modify_usercreation {
     my ($dom,%domconfig) = @_;      my ($dom,%domconfig) = @_;
     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);      my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
Line 14132  sub modify_coursedefaults { Line 17415  sub modify_coursedefaults {
     my ($resulttext,$errors,%changes,%defaultshash);      my ($resulttext,$errors,%changes,%defaultshash);
     my %defaultchecked = (      my %defaultchecked = (
                            'uselcmath'       => 'on',                             'uselcmath'       => 'on',
                            'usejsme'         => 'on'                             'usejsme'         => 'on',
                              'inline_chem'     => 'on',
                              'ltiauth'         => 'off',
                          );                           );
     my @toggles = ('uselcmath','usejsme');      my @toggles = ('uselcmath','usejsme','inline_chem','ltiauth');
     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',      my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
                    'uploadquota_community','uploadquota_textbook','mysqltables_official',                     'uploadquota_community','uploadquota_textbook','mysqltables_official',
                    'mysqltables_unofficial','mysqltables_community','mysqltables_textbook');                     'mysqltables_unofficial','mysqltables_community','mysqltables_textbook');
Line 14343  sub modify_coursedefaults { Line 17628  sub modify_coursedefaults {
             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);              my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
             if (($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||              if (($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||                  ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'})) {                  ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'}) ||
                 foreach my $item ('uselcmath','usejsme','texengine') {                  ($changes{'inline_chem'}) || ($changes{'ltiauth'})) {
                   foreach my $item ('uselcmath','usejsme','inline_chem','texengine','ltiauth') {
                     if ($changes{$item}) {                      if ($changes{$item}) {
                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};                          $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
                     }                      }
Line 14407  sub modify_coursedefaults { Line 17693  sub modify_coursedefaults {
                     } else {                      } else {
                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';                          $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
                     }                      }
                   } elsif ($item eq 'inline_chem') {
                       if ($env{'form.'.$item} eq '1') {
                           $resulttext .= '<li>'.&mt('Chemical Reaction Response uses inline previewer').'</li>';
                       } else {
                           $resulttext .= '<li>'.&mt('Chemical Reaction Response uses pop-up previewer').'</li>';
                       }
                 } elsif ($item eq 'texengine') {                  } elsif ($item eq 'texengine') {
                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {                      if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',                          $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
Line 14503  sub modify_coursedefaults { Line 17795  sub modify_coursedefaults {
                     } else {                      } else {
                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';                          $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
                     }                      }
                   } elsif ($item eq 'ltiauth') {
                       if ($env{'form.'.$item} eq '1') {
                           $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL need not require re-authentication').'</li>';
                       } else {
                           $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL will require re-authentication').'</li>';
                       }
                 }                  }
             }              }
             $resulttext .= '</ul>';              $resulttext .= '</ul>';
Line 14755  sub modify_selfenrollment { Line 18053  sub modify_selfenrollment {
     return $resulttext;      return $resulttext;
 }  }
   
   sub modify_wafproxy {
       my ($dom,$action,$lastactref,%domconfig) = @_;
       my %servers = &Apache::lonnet::internet_dom_servers($dom);
       my (%othercontrol,%canset,%values,%curralias,%currsaml,%currvalue,@warnings,
           %wafproxy,%changes,%expirecache,%expiresaml);
       foreach my $server (sort(keys(%servers))) {
           my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
           if ($serverhome eq $server) {
               my $serverdom = &Apache::lonnet::host_domain($server);
               if ($serverdom eq $dom) {
                   $canset{$server} = 1;
               }
           }
       }
       if (ref($domconfig{'wafproxy'}) eq 'HASH') {
           %{$values{$dom}} = ();
           if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
               %curralias = %{$domconfig{'wafproxy'}{'alias'}};
           }
           if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
               %currsaml = %{$domconfig{'wafproxy'}{'saml'}};
           }
           foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
               $currvalue{$item} = $domconfig{'wafproxy'}{$item};
           }
       }
       my $output;
       if (keys(%canset)) {
           %{$wafproxy{'alias'}} = ();
           %{$wafproxy{'saml'}} = ();
           foreach my $key (sort(keys(%canset))) {
               if ($env{'form.wafproxy_'.$dom}) {
                   $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
                   $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
                   if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
                       $changes{'alias'} = 1;
                   }
                   if ($env{'form.wafproxy_alias_saml_'.$key}) {
                       $wafproxy{'saml'}{$key} = 1;
                   }
                   if ($wafproxy{'saml'}{$key} ne $currsaml{$key}) {
                       $changes{'saml'} = 1;
                   }
               } else {
                   $wafproxy{'alias'}{$key} = '';
                   $wafproxy{'saml'}{$key} = '';
                   if ($curralias{$key}) {
                       $changes{'alias'} = 1;
                   }
                   if ($currsaml{$key}) {
                       $changes{'saml'} = 1;
                   }
               }
               if ($wafproxy{'alias'}{$key} eq '') {
                   if ($curralias{$key}) {
                       $expirecache{$key} = 1;
                   }
                   delete($wafproxy{'alias'}{$key});
               }
               if ($wafproxy{'saml'}{$key} eq '') {
                   if ($currsaml{$key}) {
                       $expiresaml{$key} = 1;
                   }
                   delete($wafproxy{'saml'}{$key});
               }
           }
           unless (keys(%{$wafproxy{'alias'}})) {
               delete($wafproxy{'alias'});
           }
           unless (keys(%{$wafproxy{'saml'}})) {
               delete($wafproxy{'saml'});
           }
           # Localization for values in %warn occurs in &mt() calls separately.
           my %warn = (
                        trusted => 'trusted IP range(s)',
                        vpnint => 'internal IP range(s) for VPN sessions(s)',
                        vpnext => 'IP range(s) for backend WAF connections',
                      );
           foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
               my $possible = $env{'form.wafproxy_'.$item};
               $possible =~ s/^\s+|\s+$//g;
               if ($possible ne '') {
                   if ($item eq 'remoteip') {
                       if ($possible =~ /^[mhn]$/) {
                           $wafproxy{$item} = $possible;
                       }
                   } elsif ($item eq 'ipheader') {
                       if ($wafproxy{'remoteip'} eq 'h') {
                           $wafproxy{$item} = $possible;
                       }
                   } elsif ($item eq 'sslopt') {
                       if ($possible =~ /^0|1$/) {
                           $wafproxy{$item} = $possible;
                       }
                   } else {
                       my (@ok,$count);
                       if (($item eq 'vpnint') || ($item eq 'vpnext')) {
                           unless ($env{'form.wafproxy_vpnaccess'}) {
                               $possible = '';
                           }
                       } elsif ($item eq 'trusted') {
                           unless ($wafproxy{'remoteip'} eq 'h') {
                               $possible = '';
                           }
                       }
                       unless ($possible eq '') {
                           $possible =~ s/[\r\n]+/\s/g;
                           $possible =~ s/\s*-\s*/-/g;
                           $possible =~ s/\s+/,/g;
                           $possible =~ s/,+/,/g;
                       }
                       $count = 0;
                       if ($possible ne '') {
                           foreach my $poss (split(/\,/,$possible)) {
                               $count ++;
                               $poss = &validate_ip_pattern($poss);
                               if ($poss ne '') {
                                   push(@ok,$poss);
                               }
                           }
                           my $diff = $count - scalar(@ok);
                           if ($diff) {
                               push(@warnings,'<li>'.
                                    &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
                                        $diff,$warn{$item}).
                                    '</li>');
                           }
                           if (@ok) {
                               my @cidr_list;
                               foreach my $item (@ok) {
                                   @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
                               }
                               $wafproxy{$item} = join(',',@cidr_list);
                           }
                       }
                   }
                   if ($wafproxy{$item} ne $currvalue{$item}) {
                       $changes{$item} = 1;
                   }
               } elsif ($currvalue{$item}) {
                   $changes{$item} = 1;
               }
           }
       } else {
           if (keys(%curralias)) {
               $changes{'alias'} = 1;
           }
           if (keys(%currsaml)) {
               $changes{'saml'} = 1;
           }
           if (keys(%currvalue)) {
               foreach my $key (keys(%currvalue)) {
                   $changes{$key} = 1;
               }
           }
       }
       if (keys(%changes)) {
           my %defaultshash = (
                                 wafproxy => \%wafproxy,
                              );
           my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
                                                    $dom);
           if ($putresult eq 'ok') {
               my $cachetime = 24*60*60;
               my (%domdefaults,$updatedomdefs);
               foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
                   if ($changes{$item}) {
                       unless ($updatedomdefs) {
                           %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                           $updatedomdefs = 1;
                       }
                       if ($wafproxy{$item}) {
                           $domdefaults{'waf_'.$item} = $wafproxy{$item};
                       } elsif (exists($domdefaults{'waf_'.$item})) {
                           delete($domdefaults{'waf_'.$item});
                       }
                   }
               }
               if ($updatedomdefs) {
                   &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
                   if (ref($lastactref) eq 'HASH') {
                       $lastactref->{'domdefaults'} = 1;
                   }
               }
               if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
                   my %updates = %expirecache;
                   foreach my $key (keys(%expirecache)) {
                       &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
                   }
                   if (ref($wafproxy{'alias'}) eq 'HASH') {
                       my $cachetime = 24*60*60;
                       foreach my $key (keys(%{$wafproxy{'alias'}})) {
                           $updates{$key} = 1;
                           &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
                                                         $cachetime);
                       }
                   }
                   if (ref($lastactref) eq 'HASH') {
                       $lastactref->{'proxyalias'} = \%updates;
                   }
               }
               if ((exists($wafproxy{'saml'})) || (keys(%expiresaml))) {
                   my %samlupdates = %expiresaml;
                   foreach my $key (keys(%expiresaml)) {
                       &Apache::lonnet::devalidate_cache_new('proxysaml',$key);
                   }
                   if (ref($wafproxy{'saml'}) eq 'HASH') {
                       my $cachetime = 24*60*60;
                       foreach my $key (keys(%{$wafproxy{'saml'}})) {
                           $samlupdates{$key} = 1;
                           &Apache::lonnet::do_cache_new('proxysaml',$key,$wafproxy{'saml'}{$key},
                                                         $cachetime);
                       }
                   }
                   if (ref($lastactref) eq 'HASH') {
                       $lastactref->{'proxysaml'} = \%samlupdates;
                   }
               }
               $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
               foreach my $item ('alias','saml','remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
                   if ($changes{$item}) {
                       if ($item eq 'alias') {
                           my $numaliased = 0;
                           if (ref($wafproxy{'alias'}) eq 'HASH') {
                               my $shown;
                               if (keys(%{$wafproxy{'alias'}})) {
                                   foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
                                       $shown .= '<li>'.&mt('[_1] aliased by [_2]',
                                                            &Apache::lonnet::hostname($server),
                                                            $wafproxy{'alias'}{$server}).'</li>';
                                       $numaliased ++;
                                   }
                                   if ($numaliased) {
                                       $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
                                                             '<ul>'.$shown.'</ul>').'</li>';
                                   }
                               }
                           }
                           unless ($numaliased) {
                               $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
                           }
                       } elsif ($item eq 'saml') {
                           my $shown;
                           if (ref($wafproxy{'saml'}) eq 'HASH') {
                               if (keys(%{$wafproxy{'saml'}})) {
                                   $shown = join(', ',sort(keys(%{$wafproxy{'saml'}})));
                               }
                           }
                           if ($shown) {
                               $output .= '<li>'.&mt('Alias used by SSO Auth for: [_1]',
                                                     $shown).'</li>';
                           } else {
                               $output .= '<li>'.&mt('No alias used for SSO Auth').'</li>';
                           }
                       } else {
                           if ($item eq 'remoteip') {
                               my %ip_methods = &remoteip_methods();
                               if ($wafproxy{$item} =~ /^[mh]$/) {
                                   $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
                                                         $ip_methods{$wafproxy{$item}}).'</li>';
                               } else {
                                   if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
                                       $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
                                                  '</li>';
                                   } else {
                                       $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
                                   }
                               }
                           } elsif ($item eq 'ipheader') {
                               if ($wafproxy{$item}) {
                                   $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
                                                         $wafproxy{$item}).'</li>';
                               } else {
                                   $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
                               }
                           } elsif ($item eq 'trusted') {
                               if ($wafproxy{$item}) {
                                   $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
                                                         $wafproxy{$item}).'</li>';
                               } else {
                                   $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
                               }
                           } elsif ($item eq 'vpnint') {
                               if ($wafproxy{$item}) {
                                   $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
                                                          $wafproxy{$item}).'</li>';
                               } else {
                                   $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
                               }
                           } elsif ($item eq 'vpnext') {
                               if ($wafproxy{$item}) {
                                   $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
                                                          $wafproxy{$item}).'</li>';
                               } else {
                                   $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
                               }
                           } elsif ($item eq 'sslopt') {
                               if ($wafproxy{$item}) {
                                   $output .= '<li>'.&mt('WAF/Reverse Proxy expected to forward requests to https on LON-CAPA node, regardless of original protocol in web browser (http or https).').'</li>';
                               } else {
                                   $output .= '<li>'.&mt('WAF/Reverse Proxy expected to preserve original protocol in web browser (either http or https) when forwarding to LON-CAPA node.').'</li>';
                               }
                           }
                       }
                   }
               }
           } else {
               $output = '<span class="LC_error">'.
                         &mt('An error occurred: [_1]',$putresult).'</span>';
           }
       } elsif (keys(%canset)) {
           $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
       }
       if (@warnings) {
           $output .= '<br />'.&mt('Warnings:').'<ul>'.
                          join("\n",@warnings).'</ul>';
       }
       return $output;
   }
   
   sub validate_ip_pattern {
       my ($pattern) = @_;
       if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
           my ($start,$end) = ($1,$2);
           if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
               if (($start !~ m{/}) && ($end !~ m{/})) {
                   return $start.'-'.$end;
               }
           }
       } elsif ($pattern ne '') {
           $pattern = &Net::CIDR::cidrvalidate($pattern);
           if ($pattern ne '') {
               return $pattern;
           }
       }
       return;
   }
   
 sub modify_usersessions {  sub modify_usersessions {
     my ($dom,$lastactref,%domconfig) = @_;      my ($dom,$lastactref,%domconfig) = @_;
     my @hostingtypes = ('version','excludedomain','includedomain');      my @hostingtypes = ('version','excludedomain','includedomain');
Line 15364  sub modify_loadbalancing { Line 19000  sub modify_loadbalancing {
                             }                              }
                         }                          }
                         if ($changes{'curr'}{$balancer}{'cookie'}) {                          if ($changes{'curr'}{$balancer}{'cookie'}) {
                             $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',                              if ($currcookies{$balancer}) {
                                                       $balancer).'</li>';                                  $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use disabled',
                                                             $balancer).'</li>';
                               } else {
                                   $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
                                                             $balancer).'</li>';
                               }
                         }                          }
                     }                      }
                 }                  }
Line 16143  sub devalidate_remote_domconfs { Line 19784  sub devalidate_remote_domconfs {
     my %servers = &Apache::lonnet::internet_dom_servers($dom);      my %servers = &Apache::lonnet::internet_dom_servers($dom);
     my %thismachine;      my %thismachine;
     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();      map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
     my @posscached = ('domainconfig','domdefaults','usersessions',      my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
                       'directorysrch','passwdconf','cats');                        'directorysrch','passwdconf','cats','proxyalias','proxysaml',
                         'ipaccess');
       my %cache_by_lonhost;
       if (exists($cachekeys->{'samllanding'})) {
           if (ref($cachekeys->{'samllanding'}) eq 'HASH') {
               my %landing = %{$cachekeys->{'samllanding'}};
               my %domservers = &Apache::lonnet::get_servers($dom);
               if (keys(%domservers)) {
                   foreach my $server (keys(%domservers)) {
                       my @cached;
                       next if ($thismachine{$server});
                       if ($landing{$server}) {
                           push(@cached,&escape('samllanding').':'.&escape($server));
                       }
                       if (@cached) {
                           $cache_by_lonhost{$server} = \@cached;
                       }
                   }
               }
           }
       }
     if (keys(%servers)) {      if (keys(%servers)) {
         foreach my $server (keys(%servers)) {          foreach my $server (keys(%servers)) {
             next if ($thismachine{$server});              next if ($thismachine{$server});
             my @cached;              my @cached;
             foreach my $name (@posscached) {              foreach my $name (@posscached) {
                 if ($cachekeys->{$name}) {                  if ($cachekeys->{$name}) {
                     push(@cached,&escape($name).':'.&escape($dom));                      if (($name eq 'proxyalias') || ($name eq 'proxysaml')) {
                           if (ref($cachekeys->{$name}) eq 'HASH') {
                               foreach my $key (keys(%{$cachekeys->{$name}})) {
                                   push(@cached,&escape($name).':'.&escape($key));
                               }
                           }
                       } else {
                           push(@cached,&escape($name).':'.&escape($dom));
                       }
                 }                  }
             }              }
               if ((exists($cache_by_lonhost{$server})) &&
                   (ref($cache_by_lonhost{$server}) eq 'ARRAY')) {
                   push(@cached,@{$cache_by_lonhost{$server}});
               }
             if (@cached) {              if (@cached) {
                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);                  &Apache::lonnet::remote_devalidate_cache($server,\@cached);
             }              }

Removed from v.1.160.6.112  
changed lines
  Added in v.1.160.6.118.2.5


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