Trying to implement a form that sanitizes html input according to https://symfony.com/doc/current/html_sanitizer.html#sanitizing-html-from-form-input but I cannot make it work properly. Here is my setup:
html_sanitizer.yaml
framework:
html_sanitizer:
sanitizers:
app.post_sanitizer:
allow_safe_elements: true
#allow_static_elements: true
allow_relative_medias: true
allowed_link_schemes: ['http', 'https', 'href']
allow_relative_links: true
allow_elements:
img: '*'
div: '*'
span: '*'
p: '*'
a: '*'
i: '*'
ActivityRichTextFormType.php
class ActivityRichTextFormType extends AbstractType
{
public function __construct(
private readonly HtmlSanitizerInterface $appPostSanitizer,
) {
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
//$data1 = $options['data']->getContent();
//$data1 = $this->appPostSanitizer->sanitize($data1);
//$options['data']->setContent($data1);
$builder->add('content', TextareaType::class,
['label' => '', 'empty_data' => '']
);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => ActRichText::class,
'sanitize_html' => true,
'sanitizer' => 'app.post_sanitizer',
'translation_domain' => false
]);
}
}
entity field:
#[ORM\Column(type: Types::TEXT , nullable: true)]
#[Assert\Length(max: 2255)]
private ?string $content = null;
then to test functionality I enter something like
<h2>Testing html form</h2>
<script>// <![CDATA[
(function(i,s,o,g,r,a,m){var ql=document.querySelectorAll('A[quiz],DIV[quiz]');
// ]]></script>
When I just use 'sanitize_html' => true, 'sanitizer' => 'app.post_sanitizer', in the resolver, the html text does NOT get sanitized. i.e. the script tag is kept in the content.
As a temporary workaround I added a manual sanitizer:
$data1 = $options['data']->getContent();
$data1 = $this->appPostSanitizer->sanitize($data1);
$options['data']->setContent($data1);
when i remove comments and activate this workaround, the html DOES get sanitized and the script tag is removed.
Any hints why the sanitize_html in the resolver does not work?
Thanks!
Update:
Created a fresh new project to test this issue and uploaded it at
github symfony-html-sanitizer.
I used a Model instead of an Entity to simplify things if anyone would like to check it out.
TextTypeforms, or any form extending this type (such as TextareaType)". Is ActRichText and extension of TextType or perhaps another type? That might be the problem.ActRichTextis the entity that has the field$content. Instead of listing the whole entity i only posted the 1 field used in the form.ArtRichTextin the options, when the entity type is Types:TEXT ? What happens if you omit:data_class' => ActRichText::class,?