You are here

class HtmlPurifierFilter in HTML Purifier 8

Plugin annotation


@Filter(
  id = "htmlpurifier",
  title = @Translation("HTML Purifier"),
  description = @Translation("Removes malicious HTML code and ensures that the output is standards compliant."),
  type = Drupal\filter\Plugin\FilterInterface::TYPE_HTML_RESTRICTOR
)

Hierarchy

Expanded class hierarchy of HtmlPurifierFilter

File

src/Plugin/Filter/HtmlPurifierFilter.php, line 18

Namespace

Drupal\htmlpurifier\Plugin\Filter
View source
class HtmlPurifierFilter extends FilterBase {

  /**
   * Array of error messages from HTMLPurifier configuration assignments.
   *
   * @var array
   */
  protected $configErrors = [];

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
    if (!empty($this->settings['htmlpurifier_configuration'])) {
      $purifier_config = $this
        ->applyPurifierConfig($this->settings['htmlpurifier_configuration']);
    }
    else {
      $purifier_config = \HTMLPurifier_Config::createDefault();
    }
    $purifier = new \HTMLPurifier($purifier_config);
    $purified_text = $purifier
      ->purify($text);
    return new FilterProcessResult($purified_text);
  }

  /**
   * Applies the configuration to a HTMLPurifier_Config object.
   *
   * @param string $configuration
   *
   * @return \HTMLPurifier_Config
   */
  protected function applyPurifierConfig($configuration) {

    /* @var $purifier_config \HTMLPurifier_Config */
    $purifier_config = \HTMLPurifier_Config::createDefault();
    $settings = Yaml::decode($configuration);
    foreach ($settings as $namespace => $directives) {
      if (is_array($directives)) {
        foreach ($directives as $key => $value) {
          $purifier_config
            ->set("{$namespace}.{$key}", $value);
        }
      }
      else {
        $this->configErrors[] = 'Invalid value for namespace $namespace, must be an array of directives.';
      }
    }
    return $purifier_config;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    if (empty($this->settings['htmlpurifier_configuration'])) {

      /* @var $purifier_config \HTMLPurifier_Config */
      $purifier_config = \HTMLPurifier_Config::createDefault();
      $default_value = Yaml::encode($purifier_config
        ->getAll());
    }
    else {
      $default_value = $this->settings['htmlpurifier_configuration'];
    }
    $form['htmlpurifier_configuration'] = [
      '#type' => 'textarea',
      '#rows' => 50,
      '#title' => t('HTML Purifier Configuration'),
      '#description' => t('These are the config directives in YAML format, according to the <a href="@url">HTML Purifier documentation</a>', [
        '@url' => 'http://htmlpurifier.org/live/configdoc/plain.html',
      ]),
      '#default_value' => $default_value,
      '#element_validate' => [
        [
          $this,
          'settingsFormConfigurationValidate',
        ],
      ],
    ];
    return $form;
  }

  /**
   * Settings form validation callback for htmlpurifier_configuration element.
   *
   * @param $element
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public function settingsFormConfigurationValidate($element, FormStateInterface $form_state) {
    $values = $form_state
      ->getValue('filters');
    if (isset($values['htmlpurifier']['settings']['htmlpurifier_configuration'])) {
      $this->configErrors = [];

      // HTMLPurifier library uses triger_error() for not valid settings.
      set_error_handler([
        $this,
        'configErrorHandler',
      ]);
      try {
        $this
          ->applyPurifierConfig($values['htmlpurifier']['settings']['htmlpurifier_configuration']);
      } catch (\Exception $ex) {

        // This could be a malformed YAML or any other exception.
        $form_state
          ->setError($element, $ex
          ->getMessage());
      }
      restore_error_handler();
      if (!empty($this->configErrors)) {
        foreach ($this->configErrors as $error) {
          $form_state
            ->setError($element, $error);
        }
        $this->configErrors = [];
      }
    }
  }

  /**
   * Custom error handler to manage invalid purifier configuration assignments.
   *
   * @param $errno
   * @param $errstr
   */
  public function configErrorHandler($errno, $errstr) {

    // Do not set a validation error if the error is about a deprecated use.
    if ($errno < E_DEPRECATED) {

      // \HTMLPurifier_Config::triggerError() adds ' invoked on line ...' to the
      // error message. Remove that part from our validation error message.
      $needle = 'invoked on line';
      $pos = strpos($errstr, $needle);
      if ($pos !== FALSE) {
        $message = substr($errstr, 0, $pos - 1);
        $this->configErrors[] = $message;
      }
      else {
        $this->configErrors[] = 'HTMLPurifier configuration is not valid. Error: ' . $errstr;
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FilterBase::$provider public property The name of the provider that owns this filter.
FilterBase::$settings public property An associative array containing the configured settings of this filter.
FilterBase::$status public property A Boolean indicating whether this filter is enabled.
FilterBase::$weight public property The weight of this filter compared to others in a filter collection.
FilterBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 1
FilterBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration
FilterBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
FilterBase::getDescription public function Returns the administrative description for this filter plugin. Overrides FilterInterface::getDescription
FilterBase::getHTMLRestrictions public function Returns HTML allowed by this filter's configuration. Overrides FilterInterface::getHTMLRestrictions 4
FilterBase::getLabel public function Returns the administrative label for this filter plugin. Overrides FilterInterface::getLabel
FilterBase::getType public function Returns the processing type of this filter plugin. Overrides FilterInterface::getType
FilterBase::prepare public function Prepares the text for processing. Overrides FilterInterface::prepare
FilterBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration 1
FilterBase::tips public function Generates a filter's tip. Overrides FilterInterface::tips 9
FilterBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct 4
FilterInterface::TYPE_HTML_RESTRICTOR constant HTML tag and attribute restricting filters to prevent XSS attacks.
FilterInterface::TYPE_MARKUP_LANGUAGE constant Non-HTML markup language filters that generate HTML.
FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE constant Irreversible transformation filters.
FilterInterface::TYPE_TRANSFORM_REVERSIBLE constant Reversible transformation filters.
HtmlPurifierFilter::$configErrors protected property Array of error messages from HTMLPurifier configuration assignments.
HtmlPurifierFilter::applyPurifierConfig protected function Applies the configuration to a HTMLPurifier_Config object.
HtmlPurifierFilter::configErrorHandler public function Custom error handler to manage invalid purifier configuration assignments.
HtmlPurifierFilter::process public function Performs the filter processing. Overrides FilterInterface::process
HtmlPurifierFilter::settingsForm public function Generates a filter's settings form. Overrides FilterBase::settingsForm
HtmlPurifierFilter::settingsFormConfigurationValidate public function Settings form validation callback for htmlpurifier_configuration element.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.