diff --git a/common/framework/parsers/template/TemplateParser_v2.php b/common/framework/parsers/template/TemplateParser_v2.php
index 4b32977d7..ec5a6c873 100644
--- a/common/framework/parsers/template/TemplateParser_v2.php
+++ b/common/framework/parsers/template/TemplateParser_v2.php
@@ -179,18 +179,33 @@ class TemplateParser_v2
*/
protected function _addContextSwitches(string $content): string
{
- return preg_replace_callback('#(]*)|config->context = "HTML"; ?>' . $match[1];
}
- else
+ elseif (!str_contains($match[2] ?? '', 'src="'))
{
return $match[1] . 'config->context = "JS"; ?>';
}
+ else
+ {
+ return $match[0];
+ }
}, $content);
}
+ /**
+ * Remove context switch points.
+ *
+ * @param string $content
+ * @return string
+ */
+ protected static function _removeContextSwitches(string $content): string
+ {
+ return preg_replace('#<\?php \$this->config->context = "[A-Z]+"; \?>#', '', $content);
+ }
+
/**
* Remove comments that should not be visible in the output.
*
@@ -266,7 +281,7 @@ class TemplateParser_v2
$open = '';
- return $open . self::_convertVariableScope($match[2]) . $close;
+ return $open . self::_convertVariableScope(self::_removeContextSwitches($match[2])) . $close;
};
$content = preg_replace_callback('#(<\?php|<\?=?)(.+?)(\?>)#s', $callback, $content);
diff --git a/tests/unit/framework/parsers/TemplateParserV2Test.php b/tests/unit/framework/parsers/TemplateParserV2Test.php
index d5c5d18cd..15c010ad3 100644
--- a/tests/unit/framework/parsers/TemplateParserV2Test.php
+++ b/tests/unit/framework/parsers/TemplateParserV2Test.php
@@ -366,6 +366,11 @@ class TemplateParserV2Test extends \Codeception\Test\Unit
$target = "foo ?? ''); ?>";
$this->assertEquals($target, $this->_parse($source));
+ // Context-aware escape
+ $source = '';
+ $target = '';
+ $this->assertEquals($target, $this->_parse($source));
+
// JSON using context-aware escape
$source = '{{ $foo|json }}';
$target = implode('', [
@@ -563,12 +568,12 @@ class TemplateParserV2Test extends \Codeception\Test\Unit
// Script tag with local path
$source = '';
- $target = '';
+ $target = '';
$this->assertEquals($target, $this->_parse($source));
// Absolute URL
@@ -1057,6 +1062,11 @@ class TemplateParserV2Test extends \Codeception\Test\Unit
$source = '@php $foo = 42; @endphp';
$target = 'foo = 42; ?>';
$this->assertEquals($target, $this->_parse($source));
+
+ // Turn off context-aware escape within raw PHP blocks
+ $source = "@php Context::addHtmlFooter(''); @endphp";
+ $target = "'); ?>";
+ $this->assertEquals($target, $this->_parse($source));
}
public function testDeprecationMessages()