Skip to content

Commit f03d988

Browse files
authored
Update force-https.php
1 parent b07f89d commit f03d988

File tree

1 file changed

+20
-11
lines changed

1 file changed

+20
-11
lines changed

force-https.php

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -126,25 +126,34 @@ function force_https_filter_output( $content ) {
126126
add_filter( 'widget_text', 'force_https_filter_output', 20 );
127127
add_filter( 'widget_text_content', 'force_https_filter_output', 20 );
128128

129-
// force https on essential elements with urls
129+
// enforce https on elements and inline content
130130
add_filter( 'the_content', 'force_https_process_content', 20 );
131+
131132
function force_https_process_content( $content ) {
132-
return preg_replace_callback(
133-
'#(<(?:a|img|iframe|video|audio|source|form|link)\b[^>]*\s*(?:href|src|action)=["\'])http://([^"\']+)#i',
134-
function( $matches ) {
133+
// match elements with src, href, action, content, cite, or background attributes
134+
static $element_pattern = '#(?i)(<(?:a|img|iframe|video|audio|source|form|link|embed|object|track|script|meta|input|button)\b[^>]*\s*(?:href|src|action|content|formaction)=["\'])http://([^"\']+)#';
135+
136+
// match script and style content
137+
static $script_style_pattern = '#(<(?i:script|style)\b[^>]*>)(.*?)</(?i:script|style)>#s';
138+
139+
// replace http with https in elements
140+
$content = preg_replace_callback(
141+
$element_pattern,
142+
function ( $matches ) {
135143
return $matches[1] . 'https://' . $matches[2];
136144
},
137145
$content
138146
);
139-
}
140147

141-
// force https inside inline script and style content
142-
add_filter( 'the_content', 'force_https_fix_scripts_styles', 20 );
143-
function force_https_fix_scripts_styles( $content ) {
148+
// replace http and escaped http in script and style blocks
144149
return preg_replace_callback(
145-
'#(<script\b[^>]*>|<style\b[^>]*>)(.*?)</(script|style)>#is',
146-
function( $matches ) {
147-
return $matches[1] . str_replace(['http://', 'http:\\/\\/'], ['https://', 'https:\\/\\/'], $matches[2]) . '</' . $matches[3] . '>';
150+
$script_style_pattern,
151+
function ( $matches ) {
152+
return $matches[1] . str_replace(
153+
['http://', 'http:\\/\\/'],
154+
['https://', 'https:\\/\\/'],
155+
$matches[2]
156+
) . '</' . ($matches[1][1] === 's' ? 'script' : 'style') . '>';
148157
},
149158
$content
150159
);

0 commit comments

Comments
 (0)