ezyang / htmlpurifier

Standards compliant HTML filter written in PHP
http://htmlpurifier.org
GNU Lesser General Public License v2.1
3.03k stars 323 forks source link

How do I allow base64 svg in img src? #313

Closed Artem-Schander closed 2 years ago

Artem-Schander commented 2 years ago

Hi, thank you for the awesome lib.

I'm having a hard time with base64 images. The regular one is already solved.
$config->set('URI.AllowedSchemes', ['data' => true]); But how about the following? <img src="data:image/svg+xml;base64,PHN2Zy...4MTEpIi8+PC9zdmc+Cg==" />

bytestream commented 2 years ago

Only a restricted subset of image types are permitted - https://github.com/ezyang/htmlpurifier/blob/master/library/HTMLPurifier/URIScheme/data.php#L16

Possible duplicate of https://github.com/ezyang/htmlpurifier/issues/88

Artem-Schander commented 2 years ago

Hi @bytestream, thanks for the reply. I dont think that this issue is a duplicate of #88.

In the source you linked is a comment

// you better write validation code for other types if you
// decide to allow them

Would you point me to the documentation covering custom validation? I can not find it on my own :(

Artem-Schander commented 2 years ago

For the googlers..

<?php

namespace App\Services\HTMLPurifier;

use HTMLPurifier_AttrDef_URI;

/**
 * Class ParameterURIDef
 * @author Artem Schander
 */
class ParameterURIDef extends HTMLPurifier_AttrDef_URI
{
    public function validate($uri, $config, $context)
    {
        if (preg_match('/^data:image\/svg\+xml;base64,([^\"]*)$/', $uri)) {
            return true;
        }

        return parent::validate($uri, $config, $context);
    }
}
$config = HTMLPurifier_Config::createDefault();
$config->set('URI.AllowedSchemes', ['data' => true]);
$definition = $config->getHTMLDefinition(true);
$definition->addAttribute('img', 'src', new \App\Services\HTMLPurifier\ParameterURIDef());

$HTMLPurifier = new HTMLPurifier($config);