Search code examples
phphtmlpurifier

HTMLPurifier - add name attribute to anchor tag


HTMLPurifier strips the name attribute from the anchor tag Using the documentation in the past, I've successfully created a new element "include".

But I can't get the code to also add the name attribute for the anchor tag. My preference is NOT to limit the name values. Any help would be appreciated.

This is the code:

$config = HTMLPurifier_Config::createDefault();
// custom tag for included files
$config->set('HTML.DefinitionID', 'include');
$config->set('HTML.DefinitionRev', 16);
if ($def = $config->maybeGetRawHTMLDefinition()) {
    // this works for adding the include element
    $def->addElement('include', 'Block', 'Empty', 'Common', array('file*' => 'URI', 'height' => 'Text', 'width' => 'Text'));

  // This doesn't work - among the many things, I've tried...
  // 1) trying to get at least name ="target" to work
  // $def->addAttribute('a', 'name', 'Enum#target');
  // 2) trying to get any text to work
  // $def->addAttribute('a', 'name', 'text');
  // $def->addAttribute('a', 'name', new HTMLPurifier_AttrDef_Text());
}

$purifier = new HTMLPurifier($config);

Solution

  • It looks like there are two options. One is to define all elements and tags using HTML.Allowed. Simpler is to set Attr.EnableID which allows id and name attributes. Setting Attr.IDPrefix will help prevent name collisions. This works:

    $config = HTMLPurifier_Config::createDefault();
    // allow name and id attributes
    $config->set('Attr.EnableID', true);
    // prefix all id and names with user_
    $config->set('Attr.IDPrefix', 'user_');
    
    // custom tag 
    $config->set('HTML.DefinitionID', 'include');
    $config->set('HTML.DefinitionRev', 2);
    if ($def = $config->maybeGetRawHTMLDefinition()) {
        $def->addElement('include', 'Block', 'Empty', 'Common', array('file*' => 'URI', 'height' => 'Text', 'width' => 'Text'));
    }
    
    $purifier = new HTMLPurifier($config);