我刚刚阅读了这篇博文,并成功创建并使用了自定义过滤器。我对代码进行了一些更改并添加了 Vimeo 支持:
/**
* Based on: http://sachachua.com/blog/2011/08/drupal-html-purifier-embedding-iframes-youtube/
* Iframe filter that does some primitive whitelisting in a somewhat recognizable and tweakable way
*/
class HTMLPurifier_Filter_MyIframe extends HTMLPurifier_Filter
{
public $name = 'MyIframe';
/**
*
* @param string $html
* @param HTMLPurifier_Config $config
* @param HTMLPurifier_Context $context
* @return string
*/
public function preFilter($html, HTMLPurifier_Config $config, HTMLPurifier_Context $context)
{
$html = preg_replace('#<iframe#i', '<img class="MyIframe"', $html);
$html = preg_replace('#</iframe>#i', '</img>', $html);
return $html;
}
/**
*
* @param string $html
* @param HTMLPurifier_Config $config
* @param HTMLPurifier_Context $context
* @return string
*/
public function postFilter($html, HTMLPurifier_Config $config, HTMLPurifier_Context $context)
{
$post_regex = '#<img class="MyIframe"([^>]+?)>#';
return preg_replace_callback($post_regex, array($this, 'postFilterCallback'), $html);
}
/**
*
* @param array $matches
* @return string
*/
protected function postFilterCallback($matches)
{
// Domain Whitelist
$youTubeMatch = preg_match('#src="https?://www.youtube(-nocookie)?.com/#i', $matches[1]);
$vimeoMatch = preg_match('#src="http://player.vimeo.com/#i', $matches[1]);
if ($youTubeMatch || $vimeoMatch) {
$extra = ' frameborder="0"';
if ($youTubeMatch) {
$extra .= ' allowfullscreen';
} elseif ($vimeoMatch) {
$extra .= ' webkitAllowFullScreen mozallowfullscreen allowFullScreen';
}
return '<iframe ' . $matches[1] . $extra . '></iframe>';
} else {
return '';
}
}
}
将过滤器添加到您的 HTML Purifier 配置中
$config->set('Filter.Custom', array(new HTMLPurifier_Filter_MyIframe()));