SourceEditingPreventSelfXssConstraintValidator.php in Drupal 10
File
core/modules/ckeditor5/src/Plugin/Validation/Constraint/SourceEditingPreventSelfXssConstraintValidator.php
View source
<?php
declare (strict_types=1);
namespace Drupal\ckeditor5\Plugin\Validation\Constraint;
use Drupal\ckeditor5\HTMLRestrictions;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class SourceEditingPreventSelfXssConstraintValidator extends ConstraintValidator {
use TextEditorObjectDependentValidatorTrait;
public function validate($value, Constraint $constraint) {
if (!$constraint instanceof SourceEditingPreventSelfXssConstraint) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\SourceEditingPreventSelfXssConstraint');
}
if (empty($value)) {
return;
}
$restrictions = HTMLRestrictions::fromString($value);
if ($restrictions
->allowsNothing() || count($restrictions
->getAllowedElements()) > 1) {
return;
}
$allowed_elements = $restrictions
->getAllowedElements(FALSE);
assert(count($allowed_elements) === 1);
$tag = array_key_first($allowed_elements);
$attribute_restrictions = $allowed_elements[$tag];
if (!is_array($attribute_restrictions)) {
return;
}
$text_editor = $this
->createTextEditorObjectFromContext();
$text_format_allowed_elements = HTMLRestrictions::fromTextFormat($text_editor
->getFilterFormat())
->getAllowedElements();
$forbidden_attributes = [];
if (array_key_exists('*', $text_format_allowed_elements)) {
$forbidden_attributes = array_keys(array_filter($text_format_allowed_elements['*'], function ($attribute_value_restriction, string $attribute_name) {
return $attribute_value_restriction === FALSE;
}, ARRAY_FILTER_USE_BOTH));
}
foreach ($forbidden_attributes as $forbidden_attribute_name) {
if (!self::isWildcardAttributeName($forbidden_attribute_name)) {
if (array_key_exists($forbidden_attribute_name, $attribute_restrictions)) {
$this->context
->buildViolation($constraint->message)
->setParameter('%dangerous_tag', $value)
->addViolation();
}
}
else {
$regex = self::getRegExForWildCardAttributeName($forbidden_attribute_name);
if (!empty(preg_grep($regex, array_keys($attribute_restrictions)))) {
$this->context
->buildViolation($constraint->message)
->setParameter('%dangerous_tag', $value)
->addViolation();
}
}
}
}
private static function isWildcardAttributeName(string $attribute_name) : bool {
assert($attribute_name !== '*');
return strpos($attribute_name, '*') !== FALSE;
}
private static function getRegExForWildCardAttributeName(string $wildcard_attribute_name) : string {
assert(self::isWildcardAttributeName($wildcard_attribute_name));
return '/^' . str_replace('*', '.*', $wildcard_attribute_name) . '$/';
}
}