allowing data-* attributes with HTMLPurifier

后端 未结 3 1668
青春惊慌失措
青春惊慌失措 2021-02-07 21:33

Currently I am using this code with HTMLPurifier to allow data-* HTML tag attributes:

    $def = $config->getHTMLDefinition(true);
    $def->a         


        
3条回答
  •  独厮守ぢ
    2021-02-07 22:09

    This coded can be improved, but I altered the AttrValidator.php I added the following function:

        /*=======================================
        ==--    LLS start wildcard handling
        ==--
        ==--    data-*          ^data-(((?![\s=]).)+)
        =========================================*/
        private function checkWildCardAttributes($deflist, $attr_key, $value, $config, $context) {
            $result = false;
            foreach ($deflist as $def_key => $def_value) {
                if (strpos($def_key, '*') !== FALSE) {
                    // found a wildcard
                    // does wildcard match this attr
                    $re = implode('(((?![\s=]).)+)',explode("*",$def_key));
                    preg_match('#^'.$re.'#',$attr_key,$wcout);
                    if (count($wcout)>0) {
                        // the attribute matched against the wildcard definition
                        $result = $deflist[$attr_key]->validate(
                            $value,
                            $config,
                            $context
                        );
                        break;
                    }
                }
            }
            return $result;
        }
    
    

    in the function validateToken find the following line:

    // put the results into effect
    

    Just before this line add this:

                    /*=======================================
                    ==--    start wildcard handling
                    =========================================*/
                    if (!$result) {
                        // definitions
                        $result = $this->checkWildCardAttributes($defs, $attr_key, $value, $config, $context);
                        if (!$result) {
                            // global definitions
                            $result = $this->checkWildCardAttributes($d_defs, $attr_key, $value, $config, $context);
                        }   
                    }   
                    //=======================================
    
    
                // put the results into effect
                if ($result === false || $result === null) {
    

    After this you can use * wildcards in your attribute definition. example:

        // See: AttrValidator.php in the HTMLPurifier for the wildcard addition
        $def->info_global_attr['data-*'] = new HTMLPurifier_AttrDef_Text;               
    
    

    Like i said, it can be improved... but it does the job :)

    Have fun....

提交回复
热议问题