Skip to content

Instantly share code, notes, and snippets.

@SeanJA
Created June 16, 2010 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SeanJA/440672 to your computer and use it in GitHub Desktop.
Save SeanJA/440672 to your computer and use it in GitHub Desktop.
<?php
//add rel="nofollow" and target="_blank" to links with htmlpurifier 4.1.1
require_once '../../library/HTMLPurifier.auto.php';
class HTMLPurifier_AttrTransform_AValidator extends HTMLPurifier_AttrTransform
{
var $name = 'Link validation';
function transform($attr, $config, $context) {
$attr['target'] = '_blank';
$attr['rel'] = 'nofollow';
return $attr;
}
}
$config = HTMLPurifier_Config::createDefault();
// configuration goes here:
$config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
//let them use basic html
$config->set('HTML.AllowedElements', array('br', 'em', 'i', 'b', 'strong', 'strike', 'sub', 'sup', 'a'));
//href is the only one allowed
$config->set('HTML.AllowedAttributes', array('href'));
//new definition
$config->set('HTML.DefinitionID', 'blank_nofollow');
$config->set('HTML.DefinitionRev', 1);
//remove this when you go live and set 'Cache.SerializerPath'
$config->set('Cache.DefinitionImpl', null);
//$config->set('Cache.SerializerPath', 'some/path/for/caching');
$def =& $config->getHTMLDefinition(true);
$a =& $def->addBlankElement('a');
$a->attr_transform_post[] = new HTMLPurifier_AttrTransform_AValidator();
$purifier = new HTMLPurifier($config);
// untrusted input HTML
$html = '<a rel="test" target="test2" href="mylink.php">Simple and short';
$pure_html = $purifier->purify($html);
echo $pure_html;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment