Re: Fwd: stripping or escaping php code in templates
Ionut Matei <johnutzm <at> ...> writes:
>
>
> If a template contains php code, it gets into the compiled template and will
be executed...I think a pre-filter can be created for stripping php code, but Is
there a feature or setting in PHPTAL for preventing executing php code placed
inside php tags (e.g. like $php_handling in smarty)?thanks.
>
Hi,
My solution was to do modify the XML parser to add this support.
In XmlParser.php
1. Disable ST_PREPROC
comment out $builder->onProcessingInstruction(substr($src, $mark, $i-$mark+1));
2. remove any language attribute with the value of php in a script tag
case self::ST_ATTR_QUOTE:
if ($c === $quoteStyle) {
$value = $this->sanitizeEscapedText(substr($src, $mark, $i-$mark));
if (!(strtolower($tagname) == 'script' && strtolower($attribute) ==
'language' && strtolower($value) == 'php'))
$attributes[$attribute] = $value;
3. Filter CDATA and comments through a remove php functions
$builder->onCDATASection($this->removePHP(substr($src, $mark, $i-$mark-2)));
$builder->onComment($this->removePHP(substr($src, $mark, $i-$mark+1)));
private function removePHP($source)
{
if (preg_match_all('/(<\?(php|=)?|\?>|language\s*=\s*["\']?php["\']?)/is',
$source, $matches)) {
$matches[1] = array_unique($matches[1]);
foreach ($matches[1] as $key => $value) {
$source = str_replace($value, '', $source);
}
}
return $source;
}
The other way to handle the comment and CDATA would be to encapsulate them in a
php echo statement:
<?echo <<<NOPHPALLOWED
...CDATA OR COMMENTS...
NOPHPALLOWED;
?>
Or you could add a pre-filter like so:
class removePHP implements PHPTAL_Filter {
public function filter($source){
if (preg_match_all('/(<\?(php|=)?|\?>|language\s*=\s*["\']?php["\']?)/is',
$source, $matches)) {
$matches[1] = array_unique($matches[1]);
foreach ($matches[1] as $key => $value) {
$source = str_replace($value, '', $source);
}
}
return $source;
}
}