You are here

class FilterOEmbed in oEmbed 8

Provides a fallback placeholder filter to use for missing filters.

The filter system uses this filter to replace missing filters (for example, if a filter module has been disabled) that are still part of defined text formats. It returns an empty string.

Plugin annotation


@Filter(
  id = "oembed",
  title = @Translation("oEmbed filter"),
  description = @Translation("Embeds content for oEmbed-enabled web addresses and turns the rest, and e-mail addresses, into clickable links."),
  type = Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE,
  settings = {
    "options" = "",
    "autoembed" = true
  },
  weight = -10
)

Hierarchy

Expanded class hierarchy of FilterOEmbed

File

src/Plugin/Filter/FilterOEmbed.php, line 37
Contains \Drupal\filter\Plugin\Filter\FilterOEmbed.

Namespace

Drupal\oembed\Plugin\Filter
View source
class FilterOEmbed extends FilterBase implements ContainerFactoryPluginInterface {
  const OEMBED_PATTERN_AUTOEMBED = '|^\\s*(https?://[^\\s"]+)\\s*$|im';
  const OEMBED_PATTERN_EMBED_SHORTCODE = '/(.?)\\[embed\\b(.*?)\\](.+?)\\[\\/embed\\](.?)/s';
  const OEMBED_PATTERN_EMBED_UNWRAP = '/<p>\\s*+(\\[embed\\b.*?\\].+?\\[\\/embed\\])\\s*+<\\/p>/s';

  /**
   * @var \Bangpound\oEmbed\Consumer
   */
  private $consumer;
  public function __construct(array $configuration, $plugin_id, $plugin_definition, Consumer $consumer) {
    $this->consumer = $consumer;
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * Creates an instance of the plugin.
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   *   The container to pull out services used in the plugin.
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin ID for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   *
   * @return static
   *   Returns an instance of this plugin.
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {

    /** @var \Bangpound\oEmbed\Consumer $consumer */
    $consumer = $container
      ->get('oembed.consumer');
    return new static($configuration, $plugin_id, $plugin_definition, $consumer);
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form['options'] = array(
      '#type' => 'textfield',
      '#title' => t('Default oEmbed request options'),
      '#default_value' => $this->settings['options'],
      '#description' => t('A series of attribute value pairs for the default request options. For example, <em>maxwidth="500"</em>.'),
    );
    $form['autoembed'] = array(
      '#type' => 'checkbox',
      '#title' => t('Automatically embed URLs'),
      '#default_value' => $this->settings['autoembed'],
      '#description' => t('When possible, embed the media content from a URL directly in the input.'),
    );
    return $form;
  }
  public function prepare($text, $langcode) {
    if ($this->settings['autoembed']) {
      $text = preg_replace_callback(self::OEMBED_PATTERN_AUTOEMBED, array(
        $this,
        'oembed_preg_auto_replace',
      ), $text);
    }
    return $text;
  }

  /**
   * Performs the filter processing.
   *
   * @param string $text
   *   The text string to be filtered.
   * @param string $langcode
   *   The language code of the text to be filtered.
   *
   * @return \Drupal\filter\FilterProcessResult
   *   The filtered text, wrapped in a FilterProcessResult object, and possibly
   *   with associated assets, cacheability metadata and placeholders.
   *
   * @see \Drupal\filter\FilterProcessResult
   */
  public function process($text, $langcode) {

    // Undo auto paragraph around oEmbed shortcodes.
    $text = preg_replace(self::OEMBED_PATTERN_EMBED_UNWRAP, '$1', $text);
    $text = preg_replace_callback(self::OEMBED_PATTERN_EMBED_SHORTCODE, array(
      $this,
      'oembed_preg_tag_replace',
    ), $text);
    return new FilterProcessResult($text);
  }
  public function tips($long = FALSE) {
    if ($long) {
      return t('Embed content by wrapping a supported URL in [embed] &hellip; [/embed]. Set options such as width and height with attributes [embed width="123" height="456"] &hellip; [/embed]. Unsupported options will be ignored.');
    }
    else {
      return t('Embed content by wrapping a supported URL in [embed] &hellip; [/embed].');
    }
  }

  /**
   * PREG replace callback finds [embed] shortcodes, URLs and request options.
   * @param $match
   * @return string
   */
  private function oembed_preg_tag_replace($match) {

    // allow [[oembed]] syntax for escaping a tag
    if ($match[1] == '[' && $match[4] == ']') {
      return substr($match[0], 1, -1);
    }
    $url = $match[3];
    $shortcode_options = !empty($match[2]) ? self::oembed_parse_attr($match[2]) : array();
    $options = !empty($this->settings['options']) ? self::oembed_parse_attr($this->settings['options']) : array();
    $options = array_merge($options, $shortcode_options);
    return $match[1] . $this
      ->oembed_resolve_link($url, $options) . $match[4];
  }

  /**
   * Retrieve all attributes from the shortcodes tag.
   *
   * @see shortcode_parse_atts in WordPress 3.1.3.
   * @param string $text
   * @return array List of attributes and their value.
   */
  private static function oembed_parse_attr($text) {
    $attributes = array();
    $pattern = '/([\\w-]+)\\s*=\\s*"([^"]*)"(?:\\s|$)|([\\w-]+)\\s*=\\s*\'([^\']*)\'(?:\\s|$)|([\\w-]+)\\s*=\\s*([^\\s\'"]+)(?:\\s|$)|"([^"]*)"(?:\\s|$)|(\\S+)(?:\\s|$)/';
    $text = preg_replace("/[\\x{00a0}\\x{200b}]+/u", " ", $text);
    if (preg_match_all($pattern, $text, $matches, PREG_SET_ORDER)) {
      foreach ($matches as $match) {
        if (!empty($match[1])) {
          $attributes[strtolower($match[1])] = stripcslashes($match[2]);
        }
        elseif (!empty($match[3])) {
          $attributes[strtolower($match[3])] = stripcslashes($match[4]);
        }
        elseif (!empty($match[5])) {
          $attributes[strtolower($match[5])] = stripcslashes($match[6]);
        }
        elseif (isset($match[7]) && strlen($match[7])) {
          $attributes[] = stripcslashes($match[7]);
        }
        elseif (isset($match[8])) {
          $attributes[] = stripcslashes($match[8]);
        }
      }

      // Reject any unclosed HTML elements
      foreach ($attributes as &$value) {
        if (false !== strpos($value, '<')) {
          if (1 !== preg_match('/^[^<]*+(?:<[^>]*+>[^<]*+)*+$/', $value)) {
            $value = '';
          }
        }
      }
    }
    else {
      $attributes = ltrim($text);
    }
    return $attributes;
  }

  /**
   * PREG replace callback finds [embed] shortcodes, URLs and request options.
   *
   * Override in Drupal system variable `oembed_resolve_link_callback`
   *
   * @see MediaInternetOEmbedHandler::preSave().
   *
   * @param string $url
   *   URL to embed.
   * @param array $options
   *   oEmbed request options.
   *
   * @return string
   *   Rendered oEmbed response.
   */
  private function oembed_resolve_link($url, $options = array()) {
    $url = Html::decodeEntities($url);
    $embed = $this->consumer
      ->get($url, $options);
    $return = (string) $embed;
    if (empty($return)) {
      $return = $url;
    }
    return new FilterProcessResult($return);
  }

  /**
   * PREG replace callback finds URLs
   * @param $match
   * @return string
   */
  private static function oembed_preg_auto_replace($match) {
    return '[embed]' . $match[1] . "[/embed]\n";
  }

}

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::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration 1
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.
FilterOEmbed::$consumer private property
FilterOEmbed::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
FilterOEmbed::oembed_parse_attr private static function Retrieve all attributes from the shortcodes tag.
FilterOEmbed::OEMBED_PATTERN_AUTOEMBED constant
FilterOEmbed::OEMBED_PATTERN_EMBED_SHORTCODE constant
FilterOEmbed::OEMBED_PATTERN_EMBED_UNWRAP constant
FilterOEmbed::oembed_preg_auto_replace private static function PREG replace callback finds URLs
FilterOEmbed::oembed_preg_tag_replace private function PREG replace callback finds [embed] shortcodes, URLs and request options.
FilterOEmbed::oembed_resolve_link private function PREG replace callback finds [embed] shortcodes, URLs and request options.
FilterOEmbed::prepare public function Prepares the text for processing. Overrides FilterBase::prepare
FilterOEmbed::process public function Performs the filter processing. Overrides FilterInterface::process
FilterOEmbed::settingsForm public function Generates a filter's settings form. Overrides FilterBase::settingsForm
FilterOEmbed::tips public function Generates a filter's tip. Overrides FilterBase::tips
FilterOEmbed::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides FilterBase::__construct
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.