<?php
namespace Moto\Filter; use Zend\Filter\Exception; class StripCode extends AbstractFilter { protected $_options = array( 'php' => true, 'script' => true, 'maxIteration' => 10 ); public function filter($value) { $value = (string) $value; if (!is_string($value)) { throw new \Exception('BAD_PARAMS_TYPE'); } if (empty($value)) return $value; $maxIteration = abs($this->getOption('maxIteration', 3)); if ($this->getOption('php', true)) { for ($i = 0; $i < $maxIteration; $i++) { $value = $this->stripPhpCode($value); $_value = $value; $value = str_replace(array('<?', '<?='), '<?php ', $value); $value = str_replace(array('<%', '%>'), array('<?php ', '?>'), $value); if ($value === $_value) { break; } } } if ($this->getOption('script', true)) { $_value = null; $i = 0; while($_value !== $value) { $_value = $value; $value = $this->stripJsCode($value); $i ++; if ($i > $maxIteration) { break; } } $value = preg_replace('/<[\/]*script([^>]*)>/isu', '', $value); } return $value; } public function stripPhpCode($value) { $tokens = token_get_all($value); $tokens = array_filter($tokens, function ($token) { return $token[0] == T_INLINE_HTML; }); $tokens = array_map(function ($token) { return (is_array($token) && !empty($token[1]) ? $token[1] : ''); }, $tokens); $value = implode('', $tokens); return $value; } public function stripJsCode($value) { $value = preg_replace('/<script(.*?)>(.*?)<\/script>/isu', '', $value); return $value; } }