htmlpurifier允许特定标签的方案

时间:2016-01-19 11:53:35

标签: php html htmlpurifier

$config->set('URI.AllowedSchemes', array('data' => true, 'http' => true));

$config->set('HTML.AllowedElements', array(
    'a', 'img'
));

$config->set('HTML.AllowedAttributes', array(
    'a.href', 'img.src'
));

我有一个像上面这样的htmlpurifier配置。我希望URI.AllowedSchemes应用特定的html标记。例如,img标记只能包含数据,而a标记只能包含http。有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:1)

这是我的解决方案;

过滤器;

class ImgSrcTransform extends HTMLPurifier_AttrTransform
{
    protected $parse;

    public function __construct(){
        $this->parser = new HTMLPurifier_URIParser();
    }
    public function transform($attr, $config, $context)
    {
        if(!isset($attr['src'])){
            return $attr;
        }

        $url = $this->parser->parse($attr['src']);
        if($url->scheme == 'http' || $url->scheme == 'https'){
            unset($attr['src']);
        }

        return $attr;
    }
}

class LinkHrefTransform extends HTMLPurifier_AttrTransform
{
    protected $parse;

    public function __construct(){
        $this->parser = new HTMLPurifier_URIParser();
    }
    public function transform($attr, $config, $context)
    {
        if(!isset($attr['href'])){
            return $attr;
        }

        $url = $this->parser->parse($attr['href']);


        if($url->scheme == 'data'){
            unset($attr['href']);
        }

        return $attr;
    }
}

使用过滤器;

$config = HTMLPurifier_Config::createDefault();
$config->set('URI.AllowedSchemes', array('data' => true, 'http' => true, 'https' => true));
$config->set('HTML.AllowedElements', $elements);
$config->set('HTML.AllowedAttributes', $attributes);

$htmlDef = $config->getHTMLDefinition(true);

$img = $htmlDef->addBlankElement('img');
$img->attr_transform_pre[] = new ImgSrcTransform();

$anchor = $htmlDef->addBlankElement('a');
$anchor->attr_transform_pre[] = new LinkHrefTransform();

$purifier = new HTMLPurifier($config);