Welcome! » Log In » Create A New Profile

background-image in style

Posted by KM 
background-image in style
February 27, 2017 04:32PM

I have version 4.3.0 HTMLpurifer I have a problem with the background-image in style.

In CSS.AllowedProperties I have shown, among other things 'background-image', 'background-position', 'background-repeat', 'background-repeat', 'background-color', 'background'

In HTML.Allowed I have img [alt | src | style], a [href | target], div [align | style | title | dir] The problem is that it cleans background-image.

Other CSS from the list above will let, but will remove the background-image. As for the other url, the img(scr) and a(href)works well, only background-image in the style remove.

In the file library/HTMLPurifier/AttrDef/CSS/Background.php I have:


 * Validates shorthand CSS property background.
 * @warning Does not support url tokens that have internal spaces.
class HTMLPurifier_AttrDef_CSS_Background extends HTMLPurifier_AttrDef

     * Local copy of component validators.
     * @note See HTMLPurifier_AttrDef_Font::$info for a similar impl.
    protected $info;

    public function __construct($config) {
        $def = $config->getCSSDefinition();
        $this->info[&#039;background-color&#039;] = $def->info[&#039;background-color&#039;];
        $this->info[&#039;background-image&#039;] = $def->info[&#039;background-image&#039;];
        $this->info[&#039;background-repeat&#039;] = $def->info[&#039;background-repeat&#039;];
        $this->info[&#039;background-attachment&#039;] = $def->info[&#039;background-attachment&#039;];
        $this->info[&#039;background-position&#039;] = $def->info[&#039;background-position&#039;];

    public function validate($string, $config, $context) {

        // regular pre-processing
        $string = $this->parseCDATA($string);
        if ($string === &#039;&#039;) return false;

        // munge rgb() decl if necessary
        $string = $this->mungeRgb($string);

        // assumes URI doesn&#039;t have spaces in it
        $bits = explode(&#039; &#039;, strtolower($string)); // bits to process

        $caught = array();
        $caught[&#039;color&#039;]    = false;
        $caught[&#039;image&#039;]    = false;
        $caught[&#039;repeat&#039;]   = false;
        $caught[&#039;attachment&#039;] = false;
        $caught[&#039;position&#039;] = false;

        $i = 0; // number of catches
        $none = false;

        foreach ($bits as $bit) {
            if ($bit === &#039;&#039;) continue;
            foreach ($caught as $key => $status) {
                if ($key != &#039;position&#039;) {
                    if ($status !== false) continue;
                    $r = $this->info[&#039;background-&#039; . $key]->validate($bit, $config, $context);
                } else {
                    $r = $bit;
                if ($r === false) continue;
                if ($key == &#039;position&#039;) {
                    if ($caught[$key] === false) $caught[$key] = &#039;&#039;;
                    $caught[$key] .= $r . &#039; &#039;;
                } else {
                    $caught[$key] = $r;

        if (!$i) return false;
        if ($caught[&#039;position&#039;] !== false) {
            $caught[&#039;position&#039;] = $this->info[&#039;background-position&#039;]->
                validate($caught[&#039;position&#039;], $config, $context);

        $ret = array();
        foreach ($caught as $value) {
            if ($value === false) continue;
            $ret[] = $value;

        if (empty($ret)) return false;
        return implode(&#039; &#039;, $ret);



// vim: et sw=4 sts=4

In the file library/HTMLPurifier/AttrTransform/Background.php I have:


 * Pre-transform that changes proprietary background attribute to CSS.
class HTMLPurifier_AttrTransform_Background extends HTMLPurifier_AttrTransform {

    public function transform($attr, $config, $context) {

        if (!isset($attr[&#039;background&#039;])) return $attr;

        $background = $this->confiscateAttr($attr, &#039;background&#039;);
        // some validation should happen here

        $this->prependCSS($attr, "background-image:url($background);");

        return $attr;



// vim: et sw=4 sts=4

How do you do not clean the background-image in style?

According to what is in the files should work well.

Re: background-image in style
February 27, 2017 05:00PM

What is the HTML that is failing to purify? Here is a working sample.

Re: background-image in style
February 27, 2017 06:26PM

For example, after the addition of:

<Div style = "background: url (http://htmlpurifier.org/art/bglogo.png)"> Foo </div>

I get:


So no image. All other html and css is goot, but the "background" and "background-image" deletes from code.

Re: background-image in style
February 27, 2017 06:33PM

I guess the parser doesn't know how to deal with spaces. Would be worth fixing!

Re: background-image in style
February 27, 2017 06:40PM

For example, without spaces:

<Div style="background:url(http://htmlpurifier.org/art/bglogo.png)">Foo</div>

It's the same:

Re: background-image in style
February 27, 2017 06:43PM

Ah, but this one is OK with the demo. What if you use the default configuration; is there still a problem?

Re: background-image in style
February 27, 2017 06:58PM

I do not really understand. The question is, what to do and how to not erase the 'background' and 'background-image'?

Re: background-image in style
February 27, 2017 07:00PM

What I am asking is this: if you take your HTML Purifier configuration and delete all the lines involving the config object (i.e. stop setting HTML.Allowed and CSS.AllowedProperties), does your second example still get purified away?

Re: background-image in style
February 27, 2017 07:13PM

Can I ask for an example of how stop setting HTML.Allowed and CSS.AllowedProperties?

Remove all the allowed HTML tags and CSS styles ?

Re: background-image in style
February 27, 2017 07:15PM

If you post some code I'd be able to better help you. But usually you have some line like $config->set('Foo', 'Bar');; delete all those lines.

Re: background-image in style
February 27, 2017 07:20PM

I have something this:


return array(
	&#039;finalize&#039; => TRUE,
	&#039;preload&#039;  => FALSE,
	 * global settings 
	&#039;settings&#039; => array(
		 * Use the application cache for HTML Purifier
		&#039;Cache.SerializerPath&#039; => APPPATH.&#039;cache&#039;,
                &#039;Attr.AllowedFrameTargets&#039; => array(&#039;_blank&#039;, &#039;_self&#039;),
		&#039;CSS.AllowedProperties&#039; => array(&#039;background-image&#039;, &#039;background-position&#039;, &#039;background-repeat&#039;, &#039;border-color&#039;, &#039;border-top-color&#039;, &#039;border-bottom-color&#039;, &#039;border-left-color&#039;, &#039;border-right-color&#039;, &#039;margin-bottom&#039;, &#039;margin-right&#039;, &#039;margin-top&#039;, &#039;border-bottom-style&#039;, &#039;border-bottom-width&#039;, &#039;border-left-style&#039;, &#039;border-left-width&#039;, &#039;border-right-style&#039;, &#039;border-right-width&#039;, &#039;border-top-style&#039;, &#039;border-top-width&#039;, &#039;border-style&#039;, &#039;border-width&#039;, &#039;margin&#039;, &#039;font-weight&#039;, &#039;font-style&#039;, &#039;background-color&#039;, &#039;color&#039;, &#039;font-family&#039;, &#039;font-size&#039;, &#039;text-align&#039;, &#039;background&#039;, &#039;height&#039;, &#039;width&#039;, &#039;border&#039;, &#039;float&#039;, &#039;clear&#039;),
//&#039;CSS.ForbiddenProperties&#039; => array(&#039;text-decoration&#039;)

	&#039;forms&#039; => array(
		&#039;news&#039; => array(	
			&#039;HTML.Allowed&#039; => &#039;img[alt|src|style],a[href|target],hr[width],h1[style],h2[style],h3[style],h4[style],h5[style],h6[style],pre[style],big,small,tt,kbd,samp,var,del,ins,cite,dfn,sub,sup,table[align|border|cellpadding|cellspacing|dir|style|summary],thead,tbody,tfoot,tr[style],th,td[style],caption,b,em,ul,li,ol,p[align|style|dir],span[style|dir],br,div[align|style|title|dir],br,strong,s&#039;

Re: background-image in style
February 27, 2017 07:27PM

OK well if you make all those arrays empty that should put you back on something like the defaults.

Re: background-image in style
February 27, 2017 10:45PM

the same situation > erases 'background' and 'background-image'

Re: background-image in style
February 27, 2017 11:11PM

Do you have the ability to edit HTML Purifier? Can you have it print out what the input output HTML is?

Re: background-image in style
February 28, 2017 08:53AM

In the which file I find it?

Most of the settings I have a file purifier.php , whose contents pasted in the penultimate post.

Re: background-image in style
February 28, 2017 04:18PM

find -name HTMLPurifier.php

Re: background-image in style
February 28, 2017 06:24PM

file content \library\HTMLPurifier.php


/*! @mainpage
 * HTML Purifier is an HTML filter that will take an arbitrary snippet of
 * HTML and rigorously test, validate and filter it into a version that
 * is safe for output onto webpages. It achieves this by:
 *  -# Lexing (parsing into tokens) the document,
 *  -# Executing various strategies on the tokens:
 *      -# Removing all elements not in the whitelist,
 *      -# Making the tokens well-formed,
 *      -# Fixing the nesting of the nodes, and
 *      -# Validating attributes of the nodes; and
 *  -# Generating HTML from the purified tokens.
 * However, most users will only need to interface with the HTMLPurifier
 * and HTMLPurifier_Config.

    HTML Purifier 4.3.0 - Standards Compliant HTML Filtering
    Copyright (C) 2006-2008 Edward Z. Yang

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

 * Facade that coordinates HTML Purifier&#039;s subsystems in order to purify HTML.
 * @note There are several points in which configuration can be specified
 *       for HTML Purifier.  The precedence of these (from lowest to
 *       highest) is as follows:
 *          -# Instance: new HTMLPurifier($config)
 *          -# Invocation: purify($html, $config)
 *       These configurations are entirely independent of each other and
 *       are *not* merged (this behavior may change in the future).
 * @todo We need an easier way to inject strategies using the configuration
 *       object.
class HTMLPurifier

    /** Version of HTML Purifier */
    public $version = &#039;4.3.0&#039;;

    /** Constant with version of HTML Purifier */
    const VERSION = &#039;4.3.0&#039;;

    /** Global configuration object */
    public $config;

    /** Array of extra HTMLPurifier_Filter objects to run on HTML, for backwards compatibility */
    private $filters = array();

    /** Single instance of HTML Purifier */
    private static $instance;

    protected $strategy, $generator;

     * Resultant HTMLPurifier_Context of last run purification. Is an array
     * of contexts if the last called method was purifyArray().
    public $context;

     * Initializes the purifier.
     * @param $config Optional HTMLPurifier_Config object for all instances of
     *                the purifier, if omitted, a default configuration is
     *                supplied (which can be overridden on a per-use basis).
     *                The parameter can also be any type that
     *                HTMLPurifier_Config::create() supports.
    public function __construct($config = null) {

        $this->config = HTMLPurifier_Config::create($config);

        $this->strategy     = new HTMLPurifier_Strategy_Core();


     * Adds a filter to process the output. First come first serve
     * @param $filter HTMLPurifier_Filter object
    public function addFilter($filter) {
        trigger_error(&#039;HTMLPurifier->addFilter() is deprecated, use configuration directives in the Filter namespace or Filter.Custom&#039;, E_USER_WARNING);
        $this->filters[] = $filter;

     * Filters an HTML snippet/document to be XSS-free and standards-compliant.
     * @param $html String of HTML to purify
     * @param $config HTMLPurifier_Config object for this operation, if omitted,
     *                defaults to the config object specified during this
     *                object&#039;s construction. The parameter can also be any type
     *                that HTMLPurifier_Config::create() supports.
     * @return Purified HTML
    public function purify($html, $config = null) {

        // :TODO: make the config merge in, instead of replace
        $config = $config ? HTMLPurifier_Config::create($config) : $this->config;

        // implementation is partially environment dependant, partially
        // configuration dependant
        $lexer = HTMLPurifier_Lexer::create($config);

        $context = new HTMLPurifier_Context();

        // setup HTML generator
        $this->generator = new HTMLPurifier_Generator($config, $context);
        $context->register(&#039;Generator&#039;, $this->generator);

        // set up global context variables
        if ($config->get(&#039;Core.CollectErrors&#039;)) {
            // may get moved out if other facilities use it
            $language_factory = HTMLPurifier_LanguageFactory::instance();
            $language = $language_factory->create($config, $context);
            $context->register(&#039;Locale&#039;, $language);

            $error_collector = new HTMLPurifier_ErrorCollector($context);
            $context->register(&#039;ErrorCollector&#039;, $error_collector);

        // setup id_accumulator context, necessary due to the fact that
        // AttrValidator can be called from many places
        $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context);
        $context->register(&#039;IDAccumulator&#039;, $id_accumulator);

        $html = HTMLPurifier_Encoder::convertToUTF8($html, $config, $context);

        // setup filters
        $filter_flags = $config->getBatch(&#039;Filter&#039;);
        $custom_filters = $filter_flags[&#039;Custom&#039;];
        $filters = array();
        foreach ($filter_flags as $filter => $flag) {
            if (!$flag) continue;
            if (strpos($filter, &#039;.&#039;) !== false) continue;
            $class = "HTMLPurifier_Filter_$filter";
            $filters[] = new $class;
        foreach ($custom_filters as $filter) {
            // maybe "HTMLPurifier_Filter_$filter", but be consistent with AutoFormat
            $filters[] = $filter;
        $filters = array_merge($filters, $this->filters);
        // maybe prepare(), but later

        for ($i = 0, $filter_size = count($filters); $i < $filter_size; $i++) {
            $html = $filters[$i]->preFilter($html, $config, $context);

        // purified HTML
        $html =
                // list of tokens
                    // list of un-purified tokens
                        // un-purified HTML
                        $html, $config, $context
                    $config, $context

        for ($i = $filter_size - 1; $i >= 0; $i--) {
            $html = $filters[$i]->postFilter($html, $config, $context);

        $html = HTMLPurifier_Encoder::convertFromUTF8($html, $config, $context);
        $this->context =& $context;
        return $html;

     * Filters an array of HTML snippets
     * @param $config Optional HTMLPurifier_Config object for this operation.
     *                See HTMLPurifier::purify() for more details.
     * @return Array of purified HTML
    public function purifyArray($array_of_html, $config = null) {
        $context_array = array();
        foreach ($array_of_html as $key => $html) {
            $array_of_html[$key] = $this->purify($html, $config);
            $context_array[$key] = $this->context;
        $this->context = $context_array;
        return $array_of_html;

     * Singleton for enforcing just one HTML Purifier in your system
     * @param $prototype Optional prototype HTMLPurifier instance to
     *                   overload singleton with, or HTMLPurifier_Config
     *                   instance to configure the generated version with.
    public static function instance($prototype = null) {
        if (!self::$instance || $prototype) {
            if ($prototype instanceof HTMLPurifier) {
                self::$instance = $prototype;
            } elseif ($prototype) {
                self::$instance = new HTMLPurifier($prototype);
            } else {
                self::$instance = new HTMLPurifier();
        return self::$instance;

     * @note Backwards compatibility, see instance()
    public static function getInstance($prototype = null) {
        return HTMLPurifier::instance($prototype);


// vim: et sw=4 sts=4

Your Email:


HTML input is enabled. Make sure you escape all HTML and angled brackets with &lt; and &gt;.

Auto-paragraphing is enabled. Double newlines will be converted to paragraphs; for single newlines, use the pre tag.

Allowed tags: a, abbr, acronym, b, blockquote, caption, cite, code, dd, del, dfn, div, dl, dt, em, i, ins, kbd, li, ol, p, pre, s, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, var.

For inputting literal code such as HTML and PHP for display, use CDATA tags to auto-escape your angled brackets, and pre to preserve newlines:

Place code here

Power users, you can hide this notice with:

.htmlpurifier-help {display:none;}